Files
instantadpay/qa/warpwares.mjs
T
martbost a058fd515d Warp & Wares integration, gated (2026-10-29): the 30-day Trade Wars-style season game, same protocol as POL Miner and Turkey Drop. WW_SSO_SECRET / WW_URL (default https://warpwares.saasy.top, staging for now) / WW_ALT_URLS / WW_SEASON_START + WW_SEASON_END (default 2026-11-30..2026-12-30, Central, end exclusive) with wwMint/wwOpen/wwIsGameUrl/wwCallback (code defaults only, no env set); GAME_AUTH warpwares (in-game sign-in kit); /api/my/warpwares hand-off + iap.return + my.js redirect; a new visit kind 'dock' in ads.js VISIT_KINDS with its own daily cap (dockCapPerDay, default 10; repeats after the cooldown like refuels; house visits count toward it) and the refuel rail serving game 'warpwares' with that kind (label 'sponsor dock', receipt kind ww-dock, note 'Warp & Wares sponsor dock', refuel.js done text 'Your bonus turns are waiting on the bridge'); GAMES() card with the season window (hidden until 'warpwares' is in gamesLive, its 'Opens' date shown only once live, gone after the season) and STRIP line; growth snapshot counts a season start only when live; walletnudge entry (idle until the secret is set); gamestats + gamepass GAMES/NAMES + GP_SECRETS; Game Pass perks row 'the Season Pass' shown only while the game is in the public games list (gpShown, the Turkey Drop pattern); cap-nudge names; promo tools Games entry (warpwares.saasy.top/?ref=, 3 posts) shown only while live; chatbot CANNED warpwares + fact follow gamesLive and the season window (coming-soon and season-over answers, KB answer kept out of the prompt unless live), KNOWLEDGE_DATE 2026-10-29b; my.js?v=20261029ww, promo.js?v=20261029ww, refuel.js?v=20261029ww. qa/warpwares.mjs (bash qa/run.sh warpwares): 21 checks on a local copy with a mock game (card gating, the hand-off token, a sponsor dock open/challenge/done with receipt + callback, the dock cap separate from refuels, chatbot gating), all passing. Not merged, not deployed.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-29 16:43:49 -05:00

113 lines
12 KiB
JavaScript

// Warp & Wares integration, end to end against a LOCAL copy (2026-10-29).
// node qa/warpwares.mjs (or: bash qa/run.sh warpwares)
// Boots server.js on its own port with a throwaway DATA_DIR and throwaway WW/DR secrets, plus a mock Warp & Wares game server
// that records the signed dock callbacks. Nothing touches production: WW_URL and DR_URL point at the mock.
// Covers: the Games card hidden until gamesLive has 'warpwares' (then live with its season window), the hand-off (/api/my/warpwares
// signed out -> /my with the return cookie; signed in -> the game's /auth with a token signed by WW_SSO_SECRET), a sponsor dock on
// the refuel rail (open -> challenge -> done -> receipt kind ww-dock + callback), the dock cap (visit kind 'dock', separate from
// refuels), and the chatbot's canned answer following gamesLive. Exit code 1 on any failure.
import http from 'node:http';
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.WW_QA_PORT || 8803), MOCK = PORT + 100;
const B = 'http://127.0.0.1:' + PORT, WW = 'http://127.0.0.1:' + MOCK;
const SECRET = crypto.randomBytes(24).toString('hex'), DRSECRET = 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-ww-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const CAP = { rocket: '\u{1F680}', 'lightning bolt': '⚡', key: '\u{1F511}', target: '\u{1F3AF}', wave: '\u{1F30A}', flame: '\u{1F525}', diamond: '\u{1F48E}', magnet: '\u{1F9F2}', bell: '\u{1F514}', moon: '\u{1F319}' };
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const ctDay = (plus) => new Date(Date.now() + (plus || 0) * 86400000).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
// -- the mock game: records dock callbacks, serves a page for the visit target
const callbacks = [];
const mock = http.createServer((req, res) => {
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
if (req.url === '/api/dock/callback' && req.method === 'POST') { callbacks.push(raw); res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end('{"ok":true}'); }
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>member page</title><p>hello</p>');
});
});
await new Promise(r => mock.listen(MOCK, '127.0.0.1', r));
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
const mint = (claims, secret, ttl) => { const p = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttl || 900000) }, claims)); return b64u(p) + '.' + b64u(crypto.createHmac('sha256', secret || SECRET).update(p).digest()); };
const verify = (tok, secret) => { const [p, s] = String(tok).split('.'); const payload = Buffer.from(p.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); return b64u(crypto.createHmac('sha256', secret || SECRET).update(payload).digest()) === s ? JSON.parse(payload) : null; };
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, WW_SSO_SECRET: SECRET, WW_URL: WW, WW_SEASON_START: ctDay(0), WW_SEASON_END: ctDay(30), DR_SSO_SECRET: DRSECRET, DR_URL: WW }) });
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
const cleanup = () => { try { srv.kill(); } catch (e) {} try { mock.close(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
try {
let up = false; for (let i = 0; i < 30 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(500); } }
if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
const api = async (p, body, hdr) => { const r = await fetch(B + p, body ? { method: body.method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: JSON.stringify(body.data || body), redirect: 'manual' } : { headers: hdr || {}, redirect: 'manual' }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j, loc: r.headers.get('location'), cookies: r.headers.getSetCookie ? r.headers.getSetCookie() : [] }; };
const adminH = { Authorization: 'Bearer ' + ADMIN };
async function signIn(email, username) {
const s = await api('/api/auth/email/start', { 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', { username }, { Cookie: cookie });
return cookie;
}
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10 } }, adminH);
await api('/api/admin/rates', { method: 'PATCH', data: { visitDwellSeconds: 2, dockCapPerDay: 1, refuelCapPerDay: 20 } }, adminH);
await signIn('house@instantadpay.com', 'househaunt');
let seed = await api('/api/admin/campaigns', { type: 'visits', name: 'QA dock', targetUrl: WW + '/member-page', title: 'A member page', count: 20 }, adminH);
if (!(seed.j && seed.j.ok)) seed = await api('/api/admin/campaigns', { type: 'visits', name: 'QA dock', targetUrl: 'https://rmcircle.team/contract', title: 'A member page', count: 20 }, adminH); // the URL check refuses custom ports
ok(seed.j && seed.j.ok, 'seed a visits pack', seed.j && seed.j.ok ? '#' + seed.j.campaign.id : JSON.stringify(seed.j));
const cid = seed.j && seed.j.campaign && seed.j.campaign.id;
// 1. hidden until gamesLive has it; the chatbot says coming soon
let g = (await api('/api/public/games')).j; ok(g && !(g.games || []).some(x => x.slug === 'warpwares'), 'Games list hides Warp & Wares before gamesLive');
let chat = (await api('/api/chat', { message: 'What is Warp & Wares?' })).j; ok(chat && /coming soon/i.test(chat.reply || '') && /Warp & Wares/.test(chat.reply || ''), 'chatbot: coming soon before gamesLive', chat && String(chat.reply).slice(0, 90));
await api('/api/admin/site', { method: 'PATCH', data: { gamesLive: 'polhunter,warpwares' } }, adminH);
g = (await api('/api/public/games')).j; const card = g && (g.games || []).find(x => x.slug === 'warpwares');
ok(card && /ends/i.test(card.tag) && card.seasonal === true && card.art === WW + '/og-warpwares.jpg', 'Games list shows the seasonal card once in gamesLive, the tag naming the season end', JSON.stringify(card));
const all = (await api('/api/public/games/all')).j; const cardAll = all && (all.games || []).find(x => x.slug === 'warpwares');
ok(!all || (cardAll && cardAll.live === true && cardAll.season && cardAll.season.ends && cardAll.open === WW + '/'), 'the full games list shows it live with its season window', JSON.stringify(cardAll && { live: cardAll.live, season: cardAll.season, open: cardAll.open }));
chat = (await api('/api/chat', { message: 'What is Warp & Wares?' })).j; ok(chat && /200 turns/.test(chat.reply || '') && !/coming soon/i.test(chat.reply || ''), 'chatbot: the canned answer once live', chat && String(chat.reply).slice(0, 90));
chat = (await api('/api/chat', { message: 'What is a sponsor dock?' })).j; ok(chat && /bonus turns/.test(chat.reply || ''), 'chatbot: sponsor dock question lands on the canned answer');
// 2. the hand-off
let h = await api('/api/my/warpwares'); ok(h.status === 302 && /^\/my/.test(h.loc || '') && h.cookies.some(c => /iap\.return=warpwares/.test(c)), 'signed out: /api/my/warpwares sends to /my with the return cookie', h.loc);
const player = 'qa-warpwares@example.com'; const playerCookie = await signIn(player, 'qaww');
h = await api('/api/my/warpwares', null, { Cookie: playerCookie }); ok(h.status === 302 && String(h.loc || '').startsWith(WW + '/auth?t='), 'signed in: the hand-off goes to the game /auth', h.loc);
const tok = h.loc && verify(decodeURIComponent(h.loc.split('t=')[1]));
ok(tok && tok.email === player && tok.username === 'qaww' && tok.nonce && tok.exp > Date.now() && !tok.kind, 'the token is signed with WW_SSO_SECRET and carries email, username, a nonce and no kind', JSON.stringify(tok && { email: tok.email, username: tok.username, memberId: tok.memberId }));
// 3. a sponsor dock on the refuel rail: open -> challenge -> done -> receipt + callback
const n1 = crypto.randomBytes(12).toString('hex'), ret1 = WW + '/play?dock=' + n1;
const t1 = mint({ aud: 'iap', kind: 'refuel', game: 'warpwares', nonce: n1, email: player, memberId: 77, username: 'qaww', ret: ret1, cb: WW + '/api/dock/callback' });
const o1 = (await api('/api/refuel/open?t=' + encodeURIComponent(t1))).j;
ok(o1 && o1.mode === 'visit' && o1.game === 'Warp & Wares' && o1.label === 'sponsor dock' && o1.dwell === 2 && o1.ret === ret1, 'open serves a visit as a sponsor dock', JSON.stringify(o1));
const bad = (await api('/api/refuel/open?t=' + encodeURIComponent(mint({ aud: 'iap', kind: 'refuel', game: 'warpwares', nonce: 'x', email: player, ret: 'https://evil.example/play', cb: WW + '/api/dock/callback' })))).j;
ok(bad && /Warp & Wares link/.test(bad.error || ''), 'a return address off the game is refused', bad && bad.error);
const early = (await api('/api/refuel/challenge?n=' + n1)).j; ok(early && early.early, 'challenge refuses before the dwell');
await sleep(2200);
let ch = (await api('/api/refuel/challenge?n=' + n1)).j; ok(ch && ch.prompt && ch.options.length === 5, 'challenge after the dwell', ch && ch.prompt);
const d1 = (await api('/api/refuel/done', { n: n1, answer: ch.options.indexOf(CAP[ch.prompt]) })).j;
ok(d1 && d1.ok && d1.posted === true && d1.game === 'Warp & Wares' && d1.label === 'sponsor dock' && String(d1.ret).startsWith(ret1 + '&ok=1&r='), 'done ok, callback posted, redirect ret&ok=1&r=<receipt>', JSON.stringify(d1 && { ok: d1.ok, posted: d1.posted, label: d1.label }));
const rc = d1 && verify(new URL(d1.ret).searchParams.get('r'));
ok(rc && rc.kind === 'ww-dock' && rc.nonce === n1 && rc.email === player && rc.campaignId === cid && Number.isFinite(rc.credits), 'receipt kind ww-dock with the nonce, email, campaign and credits (an admin pack is a house ad: 0 credits)', JSON.stringify(rc && { kind: rc.kind, campaignId: rc.campaignId, credits: rc.credits }));
const cb = callbacks[0] && JSON.parse(callbacks[0]); const cbc = cb && verify(cb.t);
ok(cbc && cbc.kind === 'ww-dock' && cbc.nonce === n1, 'the callback carried the same signed receipt');
const again = (await api('/api/refuel/open?t=' + encodeURIComponent(t1))).j; ok(again && again.done && again.ret === d1.ret, 're-open after done returns the same receipt redirect');
// 4. the dock cap (1 today) is its own kind: a second dock says cap, a Drip Runner refuel still opens
const n2 = crypto.randomBytes(12).toString('hex');
const o2 = (await api('/api/refuel/open?t=' + encodeURIComponent(mint({ aud: 'iap', kind: 'refuel', game: 'warpwares', nonce: n2, email: player, memberId: 77, username: 'qaww', ret: WW + '/play?dock=' + n2, cb: WW + '/api/dock/callback' })))).j;
ok(o2 && o2.none === true && o2.why === 'cap' && o2.game === 'Warp & Wares', 'the second dock of the day hits the dock cap (dockCapPerDay 1)', JSON.stringify(o2));
const n3 = crypto.randomBytes(12).toString('hex');
const o3 = (await api('/api/refuel/open?t=' + encodeURIComponent(mint({ aud: 'iap', kind: 'refuel', nonce: n3, email: player, memberId: 77, ret: WW + '/play?refuel=' + n3 }, DRSECRET)))).j;
ok(o3 && o3.why !== 'cap' && o3.game === 'Drip Runner', 'a Drip Runner refuel is not touched by the dock cap (separate kinds)', JSON.stringify(o3 && { mode: o3.mode, none: o3.none, why: o3.why, game: o3.game }));
const camps = (await api('/api/admin/campaigns', null, adminH)).j; const pack = camps && (camps.campaigns || []).find(x => x.id === cid);
ok(pack && pack.imps === 1, 'the dock counted one delivery on the advertiser pack', pack && String(pack.imps));
} catch (e) { ok(false, 'run', e.message); }
cleanup();
console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed'); process.exit(fails ? 1 : 0);