diff --git a/qa/partnercredits.test.mjs b/qa/partnercredits.test.mjs new file mode 100644 index 0000000..5c284a7 --- /dev/null +++ b/qa/partnercredits.test.mjs @@ -0,0 +1,48 @@ +// PolHunter tour-stop credits (2026-11-17): POST /api/partner/credits against a LOCAL copy. node qa/partnercredits.test.mjs +// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, DATABASE_URL blank, devCode sign-in, minimal env). +// Checks: bad signature 401, unknown member 404, over the ceiling 400, other games refused, a good call grants earned-grade +// credits once with a credit-activity line, the same ref again answers repeat and grants nothing. 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'; +import { fileURLToPath } from 'node:url'; + +const SITE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); +const PORT = Number(process.env.PC_PORT || 8835), B = 'http://127.0.0.1:' + PORT; +const SECRET = 'qa-pc-' + crypto.randomBytes(24).toString('hex'); +const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-pc-')); fs.mkdirSync(path.join(DATA, 'uploads')); +let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (!cond && extra ? ' ' + extra : '')); if (!cond) fails++; }; +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const ENV = {}; +for (const k of ['PATH', 'Path', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'COMSPEC', 'windir']) if (process.env[k]) ENV[k] = process.env[k]; +Object.assign(ENV, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DATABASE_URL: '', HUNT_SSO_SECRET: SECRET }); +const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, env: ENV, stdio: ['ignore', 'pipe', 'pipe'] }); +let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d); +const post = async (body, secret) => { const raw = JSON.stringify(Object.assign({ game: 'polhunter' }, body)), ts = String(Date.now()); + const r = await fetch(B + '/api/partner/credits', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game-Ts': ts, 'X-Game-Sig': crypto.createHmac('sha256', secret || SECRET).update(ts + '\n' + raw).digest('hex') }, body: raw }); + let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; }; +try { + let up = false; for (let i = 0; i < 90 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(1000); } } + if (!up) throw new Error('local server did not come up:\n' + log.slice(-2000)); + const email = 'hunter-pc@example.com'; + const s = await (await fetch(B + '/api/auth/email/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) })).json(); + const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.devCode }) }); + const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; '); + ok((await post({ email, credits: 10, ref: 'tour:a1' }, 'wrong-' + SECRET)).status === 401, 'a bad signature is refused'); + ok((await post({ email: 'nobody@example.com', credits: 10, ref: 'tour:a1' })).status === 404, 'an unknown member is 404'); + ok((await post({ email, credits: 26, ref: 'tour:a1' })).status === 400, 'over the 25 ceiling is refused'); + ok((await post({ email, credits: 10, ref: 'bad ref!' })).status === 400, 'a malformed ref is refused'); + const g1 = await post({ email, credits: 10, ref: 'tour:a1', note: 'PolHunter tour stop: Site A' }); + ok(g1.status === 200 && g1.j.ok && g1.j.credits === 10 && !g1.j.repeat, 'a good call grants 10 credits', JSON.stringify(g1)); + const g2 = await post({ email, credits: 10, ref: 'tour:a1' }); + ok(g2.status === 200 && g2.j.ok && g2.j.repeat === true, 'the same ref again answers repeat', JSON.stringify(g2)); + const logFile = path.join(DATA, 'credit-log.json'); const lines = fs.existsSync(logFile) ? JSON.parse(fs.readFileSync(logFile, 'utf8')).items.filter(i => i.email === email && /tour stop/i.test(i.note)) : []; + ok(lines.length === 1 && lines[0].delta === 10 && lines[0].kind === 'earn', 'exactly one credit-activity line of +10 (earned grade)', JSON.stringify(lines)); + const ej = path.join(DATA, 'earned.json'); const ec = fs.existsSync(ej) ? JSON.parse(fs.readFileSync(ej, 'utf8')) : {}; + ok(ec[email] && ec[email].balance >= 10 && !ec[email].grade, 'earned balance holds the 10, none of it purchased grade', JSON.stringify(ec[email])); + ok((await post({ game: 'gemkingdom', email, credits: 10, ref: 'tour:b1' })).status !== 200, 'another game cannot use it'); +} catch (e) { console.log('FAIL crash', e.message); fails++; } +srv.kill(); await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} +console.log(fails ? '\nFAILURES: ' + fails : '\nALL PARTNER CREDIT CHECKS PASS'); process.exit(fails ? 1 : 0); diff --git a/server.js b/server.js index 8db80ae..dfa6620 100644 --- a/server.js +++ b/server.js @@ -4806,7 +4806,7 @@ const server = http.createServer(async (req, res) => { return json(res, 200, Object.assign({ ok: true, memberId: r.memberId, username: r.acct.username || null, wallet: r.acct.address || null, suspended: fraud.isSuspended(r.email), pass: gamepass.flag(r.email, now), caps: gamepass.capsFor(r.email, now, game), gamePassEnabled: gamepass.cfg().enabled }, game === 'shardsofvalor' ? gamepass.heroClaim(r.email) : {})); } - if ((p === '/api/partner/polgrant' || p === '/api/partner/polgrant/void' || p === '/api/partner/tournament/paid') && req.method === 'POST') { + if ((p === '/api/partner/polgrant' || p === '/api/partner/polgrant/void' || p === '/api/partner/tournament/paid' || p === '/api/partner/credits') && req.method === 'POST') { let raw; try { raw = (await readRaw(req, 16384)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); } let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); } const game = String(b.game || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error }); @@ -4816,6 +4816,22 @@ const server = http.createServer(async (req, res) => { if (p === '/api/partner/tournament/paid') { const r = gamepass.markPaid(b.week, b.place, b.tx, game); if (!r.error) console.log('gamepass prize paid', b.week, '#' + b.place, 'by', game, String(b.tx || '').slice(0, 14)); return json(res, r.error ? 400 : 200, r); } const r = await gpResolve(b.memberId, b.email); if (!r) return json(res, 404, { error: 'no such member' }); const now = gpDevNow(b.devDay); + // PolHunter tour stops (Marty 2026-11-17): a free member's repeat find pays a few earned-grade ad credits instead of POL. PolHunter + // decides the amount (its settings tourStopCredits / tourStopCreditsDailyMax); here a hard ceiling per call (siteConfig partnerCreditsMax, + // default 25), once per ref across every instance (marks), with a credit-activity line. A retry of the same ref answers repeat: true. + if (p === '/api/partner/credits') { + if (game !== 'polhunter') return json(res, 400, { error: 'not enabled for ' + game }); + const n = Math.round(Number(b.credits) || 0), max = Math.max(0, Math.round(Number(siteConfig().partnerCreditsMax) || 25)), ref = String(b.ref || ''); + if (!(n > 0) || n > max) return json(res, 400, { error: 'credits must be 1 to ' + max }); + if (!/^[A-Za-z0-9:_-]{3,60}$/.test(ref)) return json(res, 400, { error: 'bad ref' }); + const who = await gpResolve(b.memberId, b.email); if (!who) return json(res, 404, { error: 'no such member' }); + if (fraud.isSuspended(who.email)) return json(res, 403, { error: 'suspended' }); + if (!(await marks.claim('pcred:' + game + ':' + ref))) return json(res, 200, { ok: true, repeat: true, credits: n }); + try { await ads.addEarned(who.email, n, { log: { kind: 'earn', note: String(b.note || 'PolHunter tour stop').replace(/[<>]/g, '').slice(0, 120), ref: ('ph' + ref).slice(0, 40) } }); } + catch (e) { console.error('partner credits', ref, e.message); return json(res, 500, { error: 'grant failed' }); } + console.log('partner credits', game, ref, n, who.email.replace(/^(.).*(@.*)$/, '$1***$2')); + return json(res, 200, { ok: true, credits: n }); + } if (p.endsWith('/void')) return json(res, 200, gamepass.voidGrant({ game, ref: b.ref })); if (fraud.isSuspended(r.email)) return json(res, 200, { allowed: 0, deferred: 0, pass: false, day: gamepass.dayKey(now), suspended: true }); // nothing is recorded: a cleared account replays the ref later const out = gamepass.grant({ email: r.email, game, kind: b.kind, pol: b.pol, ref: b.ref, now });