Files
instantadpay/qa/sov-passes-local.mjs
T
martbost 0688bdeb72 Pass tiers: Explorer ($20/30 days) and Champion ($40/30 days) beside the weekly Game Pass, behind sovTiers (default off, admin-only preview)
Islands and looks in Shards of Valor, never power and never more POL: every tier gets exactly the weekly pass caps and polgrant
still answers pass: true. Per-tier expiry side by side (record.tiers, legacy until mirrors weekly, lazy migration); flag() adds
tier (highest active) and tiers; hand-off token gamePass { active, until, tier }; /api/partner/player pass { active, until, tier,
tiers }. Buy { tier } with purchased credits or a waiting order per tier that a big-enough package fulfils (highest price first,
each tx once). No auto-renew, no proration. Admin: per-tier stats (Central week/month), comp per tier, end-a-tier (refund).
Tournament pool keeps weekly sales only unless passTournamentTierSales. Member card shows three tiers; /my#passes opens it.
Tests: qa/sov-passes-store.cjs, qa/sov-passes-local.mjs (bash qa/run.sh sov-passes). Cache tags my.js/admin.js 20261018tiers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 14:46:51 -05:00

140 lines
14 KiB
JavaScript

// Explorer / Champion passes end to end on a LOCAL throwaway copy (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md).
// node qa/sov-passes-local.mjs screenshots -> SHOTS (default D:/tmp/sov-passes)
// Boots server.js with a throwaway DATA_DIR and throwaway SOV secret, preloading qa/sov-passes-stub.cjs, which seeds 2500
// purchased-grade credits on one fake position owned by the admin account. Nothing touches production.
// Covers: sovTiers off -> a member sees and can buy only the weekly pass; the ADMIN_EMAIL account sees the admin preview and buys
// Explorer in the browser through the REAL ads.gamePurchase(purchasedOnly) charge; the 500 left is short for a second Explorer
// (waiting order, $20 package copy); the Shards of Valor hand-off token and GET /api/partner/player carry tier explorer;
// polgrant answers pass: true with the weekly pass caps; Admin > Game Pass shows the tier table. Exit 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 { pathToFileURL } from 'node:url';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
const PORT = Number(process.env.SOV_PORT || 8798);
const B = 'http://127.0.0.1:' + PORT;
const SHOTS = process.env.SHOTS || 'D:/tmp/sov-passes'; fs.mkdirSync(SHOTS, { recursive: true });
const SOV = crypto.randomBytes(24).toString('hex'); // throwaway, never printed
const ADMIN_PW = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com', MEMBER = 'qa-sov-member@example.com';
const SEED_ID = 9001, SEED_CREDITS = 2500;
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-sovpasses-')); fs.mkdirSync(path.join(DATA, 'uploads'));
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
const hide = page => page.evaluate(() => { document.querySelectorAll('.lgate,.iap-welcome,#onboardModal').forEach(m => m.hidden = true); });
const sleep = ms => new Promise(r => setTimeout(r, ms));
const srv = spawn(process.execPath, ['-r', './qa/sov-passes-stub.cjs', '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_PW, SOV_SSO_SECRET: SOV, DEV_POL_USD: '0.10',
QA_SEED_EMAIL: ADMIN_EMAIL, QA_SEED_ID: String(SEED_ID), QA_SEED_CREDITS: String(SEED_CREDITS) }) });
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
let browser = null;
const cleanup = async () => { try { if (browser) await browser.close(); } catch (e) {} try { srv.kill(); } catch (e) {} await sleep(300); 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 || {}), redirect: 'manual' };
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_PW };
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 cookies = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]);
const cookie = cookies.join('; ');
if (username) await api('/api/my/profile', { data: { username } }, { Cookie: cookie });
return { Cookie: cookie, pairs: cookies.map(c => { const i = c.indexOf('='); return { name: c.slice(0, i), value: c.slice(i + 1) }; }) };
}
const decode = tok => JSON.parse(Buffer.from(String(tok).split('.')[0].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
async function playerOf(email) {
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SOV).update('player:' + email + ':' + ts).digest('hex');
const r = await fetch(B + '/api/partner/player?' + new URLSearchParams({ game: 'shardsofvalor', m: '0', e: email, ts, sig })); return { status: r.status, j: await r.json() };
}
async function grant(body) {
const raw = JSON.stringify(body); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SOV).update(ts + '\n' + raw).digest('hex');
const r = await fetch(B + '/api/partner/polgrant', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game-Ts': ts, 'X-Game-Sig': sig }, body: raw }); return r.json();
}
async function pageFor(h) {
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
await ctx.addCookies(h.pairs.map(c => ({ name: c.name, value: c.value, url: B })));
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} }); // the session pop-up would block every click
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(String(e))); return { page, errs, ctx };
}
try {
let up = false; for (let i = 0; i < 40; i++) { try { if ((await fetch(B + '/api/config')).ok) { up = true; break; } } catch (e) {} await sleep(500); }
ok(up && /qa stub: position #9001/.test(srvLog), 'local copy up with the seeded position', '');
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10, gamePassEnabled: '1' } }, adminH);
const site = (await api('/api/admin/site', null, adminH)).j; const sc = (site && (site.site || site)) || {};
ok(sc.sovTiers === '0' && Number(sc.gamePassExplorerPriceCredits) === 2000 && Number(sc.gamePassChampionPriceCredits) === 4000 && Number(sc.gamePassExplorerDays) === 30 && sc.passTournamentTierSales === '0', 'defaults: sovTiers 0, Explorer 2000 / Champion 4000 credits, 30 days, passTournamentTierSales 0', JSON.stringify({ sovTiers: sc.sovTiers, e: sc.gamePassExplorerPriceCredits, c: sc.gamePassChampionPriceCredits }));
const hA = await signIn(ADMIN_EMAIL, 'qaadmin'), hM = await signIn(MEMBER, 'qasovm');
// 1. a member with sovTiers off: weekly only, Explorer refused
let g = (await api('/api/my/gamepass', null, hM)).j;
ok(g.passes && g.passes.length === 1 && g.passes[0].tier === 'weekly' && !g.tierPreview, 'member, sovTiers off: only the weekly pass is offered', JSON.stringify((g.passes || []).map(x => x.tier)));
let r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hM);
ok(r.status === 400 && r.j.error === 'The Explorer pass is not open yet.', 'member, sovTiers off: Explorer buy refused', JSON.stringify(r.j));
browser = await chromium.launch();
{ const { page, errs, ctx } = await pageFor(hM); await page.goto(B + '/my#passes'); await page.waitForSelector('#gpCard:not([hidden]) #gpBuy', { timeout: 15000 });
const txt = await page.textContent('#gpCard'); ok(!/Explorer|Champion/.test(txt) && errs.length === 0, 'member page: the weekly card as before, no Explorer/Champion text, no page errors', errs.join(' | '));
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '1-member-weekly-only.png') }); await ctx.close(); }
// 2. the admin: preview of all three, buys Explorer in the browser with the seeded purchased credits (the real charge)
g = (await api('/api/my/gamepass', null, hA)).j;
ok(g.tierPreview === true && g.passes.map(x => x.tier).join() === 'weekly,explorer,champion', 'admin, sovTiers off: preview with all three tiers', JSON.stringify(g.passes.map(x => [x.tier, x.price, x.open])));
{ const { page, errs, ctx } = await pageFor(hA); await page.goto(B + '/my?from=shardsofvalor#passes');
await page.waitForSelector('#gpCard [data-gp-tier="explorer"]', { timeout: 15000 }); await sleep(600); await hide(page);
const txt = await page.textContent('#gpCard');
ok(/never make you stronger than players who earn their gear/.test(txt) && /main story of Shards of Valor is free/.test(txt) && /Admin preview/.test(txt) && !/\u2014/.test(txt), 'tier card copy: never stronger, main story free, admin preview note, no em dashes', '');
ok(/#games/.test(page.url()), 'the Shards of Valor link (#passes) lands on the pass card, not the Buy pane', page.url());
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '2-admin-preview-three-tiers.png') });
await page.click('#gpCard [data-gp-tier="explorer"]'); await page.waitForSelector('#dlgOk', { timeout: 5000 });
await page.screenshot({ path: path.join(SHOTS, '3-admin-confirm-explorer.png') });
await page.click('#dlgOk');
await page.waitForFunction(() => /Explorer active/.test((document.getElementById('gpCard') || {}).textContent || ''), null, { timeout: 15000 }).catch(() => {});
const after = await page.textContent('#gpCard');
ok(/Explorer active/.test(after) && errs.length === 0, 'after the buy the card shows Explorer active (Central date)', errs.join(' | '));
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '4-admin-explorer-active.png') }); await ctx.close(); }
g = (await api('/api/my/gamepass', null, hA)).j;
const ex = g.passes.find(x => x.tier === 'explorer');
ok(g.active && g.tier === 'explorer' && ex.active && Math.abs(ex.until - (Date.now() + 30 * 86400000)) < 120000, 'GET /api/my/gamepass: tier explorer, 30 days', JSON.stringify({ tier: g.tier, until: ex && new Date(ex.until).toISOString() }));
ok(/gamepass bought with credits explorer qa-admin@example.com 2000/.test(srvLog), 'paid through the real ads.gamePurchase(purchasedOnly) path, 2000 credits', '');
r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hA);
ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'explorer' && r.j.available === 500 && /\$20 package/.test(r.j.message), 'a second Explorer: only 500 purchased credits left -> waiting order, "$20 package"', JSON.stringify({ needPay: r.j.needPay, available: r.j.available, payUrl: r.j.payUrl }));
// 3. the Shards of Valor hand-off token and the partner player answer carry tier explorer
const ho = await api('/api/my/shardsofvalor', null, hA);
const loc = ho.headers.get('location') || ''; const t = new URL(loc).searchParams.get('t'); const claims = t ? decode(t) : null;
ok(ho.status === 302 && claims && claims.gamePass && claims.gamePass.active === true && claims.gamePass.tier === 'explorer' && claims.gamePass.until === ex.until && !('tiers' in claims.gamePass), 'hand-off token: gamePass { active, until, tier: explorer }', JSON.stringify(claims && claims.gamePass));
const sig = t && crypto.createHmac('sha256', SOV).update(Buffer.from(t.split('.')[0].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')).digest('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
ok(sig && sig === t.split('.')[1], 'the token verifies with SOV_SSO_SECRET', '');
const pl = await playerOf(ADMIN_EMAIL);
ok(pl.status === 200 && pl.j.pass.active === true && pl.j.pass.tier === 'explorer' && pl.j.pass.tiers && pl.j.pass.tiers.explorer === ex.until && pl.j.pass.tiers.champion === null && pl.j.caps.daily === 1.5 && pl.j.caps.total === 5, 'GET /api/partner/player: pass { active, until, tier: explorer, tiers }, weekly pass caps 1.50 / 5', JSON.stringify(pl.j.pass) + ' ' + JSON.stringify({ d: pl.j.caps.daily, t: pl.j.caps.total }));
const plm = await playerOf(MEMBER);
ok(plm.j.pass.active === false && plm.j.pass.tier === null, 'a free member: pass { active false, tier null }', JSON.stringify(plm.j.pass));
const gr = await grant({ memberId: 0, email: ADMIN_EMAIL, game: 'shardsofvalor', kind: 'daily', pol: 0.2, ref: 'qa:1' });
ok(gr.pass === true && gr.allowed === 0.2, 'polgrant: pass true (a boolean) for the Explorer holder', JSON.stringify(gr));
// 4. Admin > Game Pass: the tier table
const st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
ok(st.tiers && st.tiers.explorer.active === 1 && st.tiers.explorer.soldTotal === 1 && st.tiers.explorer.usdTotal === 20 && st.tiers.explorer.waitingOrders === 1 && st.tierSales === false, 'admin stats: Explorer 1 active, 1 sold ($20), 1 waiting; sale switch off', JSON.stringify(st.tiers.explorer));
{ const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } }); const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(String(e)));
await page.goto(B + '/admin', { waitUntil: 'networkidle' });
await page.fill('#adEmail', ADMIN_EMAIL); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await sleep(1200);
const nav = await page.$('.bo-menu [data-pane="gamepass"]'); if (nav) { await nav.click(); await page.waitForFunction(() => /Explorer/.test((document.getElementById('gpTiers') || {}).textContent || ''), null, { timeout: 10000 }).catch(() => {}); }
const txt = await page.textContent('#gpTiers').catch(() => '');
ok(/Explorer/.test(txt) && /Champion/.test(txt), 'Admin > Game Pass renders the per-tier table', errs.join(' | ') || (nav ? '' : 'admin nav not found (sign-in flow)'));
await sleep(800); await page.locator('#gpTiers').evaluate(e => e.closest('.card').scrollIntoView()); await sleep(400); await page.locator('#gpTiers').evaluate(e => e.closest('.card').id = 'gpTiersCard'); await page.locator('#gpTiersCard').screenshot({ path: path.join(SHOTS, '5-admin-gamepass-tiers.png') }); await ctx.close(); }
} catch (e) {
console.error('FAIL harness error', e && e.stack || e); fails++;
} finally {
await cleanup();
}
if (fails) console.log('--- server log (tail) ---\n' + srvLog.split('\n').filter(l => /gamepass|Error|error|qa stub/.test(l)).slice(-30).join('\n'));
console.log(fails ? fails + ' FAILURE(S)' : 'ALL PASS');
process.exit(fails ? 1 : 0);