Files

108 lines
10 KiB
JavaScript

// Member welcome offer + member perk (2026-10-05), on a local boot against a stub of InstantAdPay's public offer endpoint.
// Temp DATA_DIR, no faucet, no outbound. Checks: a signed-in non-member's clear carries the offer once a Central day; a
// guest and a member never see it; a member's hand-off grants one free hangar upgrade once per account; the free upgrade
// pays for exactly one purchase; the offer is skipped while InstantAdPay says off; bonus is null when the endpoint fails.
'use strict';
const { spawn } = require('child_process');
const http = require('http');
const path = require('path');
const fs = require('fs');
const PORT = 8899, STUB = 8897, DIR = path.join(__dirname, '..', 'data-test-starter');
fs.rmSync(DIR, { recursive: true, force: true });
const SECRET = 'z'.repeat(48);
let stubHits = 0, stubOn = true;
const stub = http.createServer((req, res) => {
if (req.url === '/api/starter/public') { stubHits++; res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ on: stubOn, bonus: 100, games: { driprunner: { name: 'Drip Runner', perk: 'a free hangar upgrade' } } })); }
res.writeHead(404); res.end('{}');
}).listen(STUB);
const IAPS = 'http://127.0.0.1:' + STUB;
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DIR, DR_SSO_SECRET: SECRET, ADMIN_KEY: 'adminkey123', SITE_URL: 'http://127.0.0.1:' + PORT, IAP_URL: IAPS });
delete env.CURTAIN; delete env.OUTBOUND; delete env.DR_WALLET_KEY; delete env.DR_RPC; delete env.DR_SIGNUPS; delete env.NODE_ENV;
const child = spawn(process.execPath, [path.join(__dirname, '..', 'server.js')], { env, stdio: ['ignore', 'pipe', 'pipe'] });
let serverErr = ''; child.stderr.on('data', d => { serverErr += d; process.stderr.write(d); });
let fails = 0;
const eq = (a, b, m) => { const ok = JSON.stringify(a) === JSON.stringify(b); console.log((ok ? ' ok ' : ' FAIL ') + m + (ok ? '' : ' -> got ' + JSON.stringify(a) + ' want ' + JSON.stringify(b))); if (!ok) fails++; };
const B = 'http://127.0.0.1:' + PORT;
const sleep = ms => new Promise(r => setTimeout(r, ms));
const spawnLib = require('../lib/spawn');
const hit = async (p, opt = {}, ck = '') => { const r = await fetch(B + p, Object.assign({ redirect: 'manual' }, opt, { headers: Object.assign({ Cookie: ck, 'Content-Type': 'application/json' }, opt.headers || {}) })); const set = r.headers.getSetCookie ? r.headers.getSetCookie() : []; let body = null; try { body = await r.json(); } catch (e) {} return { status: r.status, body, set, loc: r.headers.get('location') }; };
const jarAdd = (ck, set) => { const parts = ck ? ck.split('; ') : []; for (const c of set) { const m = /^([^=]+)=([^;]*)/.exec(c); if (!m) continue; const i = parts.findIndex(x => x.startsWith(m[1] + '=')); if (i >= 0) parts.splice(i, 1); if (m[2]) parts.push(m[1] + '=' + m[2]); } return parts.join('; '); };
const post = (p, b, ck) => hit(p, { method: 'POST', body: JSON.stringify(b || {}) }, ck);
const admin = (p, b) => hit(p, Object.assign({ headers: { 'X-Admin-Key': 'adminkey123' } }, b ? { method: 'POST', body: JSON.stringify(b) } : {}));
const players = () => JSON.parse(fs.readFileSync(path.join(DIR, 'players.json'), 'utf8'));
const W = 390, H = 760;
// play one run to the next chapter clear (claims timed to the schedule, start backdated so the wall check passes)
async function clearOne(ck) {
const r = (await post('/api/run/start', { W, H }, ck)).body; const gen = spawnLib.drips(r.seed, W, H); const cl = []; let T = 0;
while (cl.length < r.goal) { const g = gen(); for (const d of g.drips) if (cl.length < r.goal) { T = spawnLib.arrival(g.t, d.x0, W, r.speed) + 0.1; cl.push({ k: 'd', i: d.i, t: Math.round(T * 1000) / 1000 }); } }
const runs = JSON.parse(fs.readFileSync(path.join(DIR, 'runs.json'), 'utf8')); runs[r.runId].startedAt = Date.now() - (T + 5) * 1000; fs.writeFileSync(path.join(DIR, 'runs.json'), JSON.stringify(runs));
const ev = (await post('/api/run/events', { runId: r.runId, t: T + 0.2, events: cl, goal: true }, ck)).body;
await post('/api/run/end', { runId: r.runId }, ck);
return ev;
}
async function signIn(claims, ck) { const a = await hit('/auth?t=' + sso.mint(claims), {}, ck || ''); return { ck: jarAdd(ck || '', a.set), a }; }
let sso;
(async () => {
for (let i = 0; i < 60; i++) { try { await fetch(B + '/health'); break; } catch (e) { await sleep(250); } }
process.env.DR_SSO_SECRET = SECRET; sso = require('../lib/sso');
await admin('/api/admin/settings', { signups: 'open' });
// ---- non-member (InstantAdPay memberId 0): the offer after a win, once a Central day ----
let { ck: nm, a } = await signIn({ memberId: 0, email: 'nonmember@example.com', wallet: null, username: 'nonmem' });
eq(a.loc, '/play', 'a non-member signs in');
const nmMe = (await hit('/api/me', {}, nm)).body; eq([nmMe.me.memberId < 0, nmMe.perk, nmMe.player.freeUpgrades], [true, null, 0], 'non-member: temporary id, no perk, no free upgrade');
const c1 = await clearOne(nm);
eq([c1.cleared && c1.cleared.chapter, c1.starterOffer], [1, { bonus: 100, perk: 'a free hangar upgrade', url: IAPS + '/my?from=driprunner#buy' }], 'first clear of the day carries starterOffer {bonus 100, perk, url}');
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
eq(players()[String(nmMe.me.memberId)].starterShown, today, 'shown today is recorded on the player (Central day key ' + today + ')');
const c2 = await clearOne(nm); eq([c2.cleared && c2.cleared.chapter, c2.starterOffer === undefined], [2, true], 'second clear the same day: no offer');
const runEnd = await post('/api/run/start', { W, H }, nm); const crash = (await post('/api/run/events', { runId: runEnd.body.runId, t: 1, events: [] }, nm)).body; eq(crash.starterOffer === undefined, true, 'a sync without a clear never carries the offer');
await post('/api/run/end', { runId: runEnd.body.runId }, nm);
// tomorrow (Central): move the recorded day back
const ps = players(); ps[String(nmMe.me.memberId)].starterShown = '2000-01-01'; fs.writeFileSync(path.join(DIR, 'players.json'), JSON.stringify(ps));
const c3 = await clearOne(nm); eq([c3.cleared && c3.cleared.chapter, !!c3.starterOffer], [3, true], 'next Central day: the offer shows again, once');
eq(stubHits, 1, 'the public endpoint was fetched once (10-minute cache)');
// ---- a guest never sees it ----
await admin('/api/admin/settings', {}); let g = '';
const gs = await post('/api/guest', {}, g); g = jarAdd(g, gs.set); const gc = await clearOne(g);
eq([gc.cleared && gc.cleared.reason, gc.starterOffer === undefined], ['guest', true], 'a guest clear: no offer');
// ---- member: the perk, once per account ----
let { ck: mb } = await signIn({ memberId: 55, email: 'member@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'member55' });
const p55 = players()['55']; eq([p55.freeUpgrades, typeof p55.perkAt, p55.perkNotice], [1, 'number', true], 'member hand-off grants one free upgrade, perkAt timestamp set');
const m1 = (await hit('/api/me', {}, mb)).body; eq([m1.perk, m1.player.freeUpgrades], ['Member perk: a free hangar upgrade. Thanks for joining InstantAdPay!', 1], '/api/me carries the one-time perk message');
const m2 = (await hit('/api/me', {}, mb)).body; eq(m2.perk, null, 'the message shows once (next load has none)');
const perkAt1 = players()['55'].perkAt;
({ ck: mb } = await signIn({ memberId: 55, email: 'member@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'member55' }, mb));
eq([players()['55'].freeUpgrades, players()['55'].perkAt, (await hit('/api/me', {}, mb)).body.perk], [1, perkAt1, null], 'signing in again grants nothing more');
const mc = await clearOne(mb); eq([mc.cleared && mc.cleared.chapter, mc.starterOffer === undefined], [1, true], 'a member clear: no offer');
const bank0 = players()['55'].bank;
const buy1 = await post('/api/hangar/buy', { item: 'ship' }, mb); // 600 drips, they have ~20
eq([buy1.status, buy1.body.free, buy1.body.player.items.ship, buy1.body.player.freeUpgrades, buy1.body.player.bank], [200, true, true, 0, bank0], 'the free upgrade buys the Courier Mk II (600 drips) for nothing, token used');
const buy2 = await post('/api/hangar/buy', { item: 'magnet' }, mb); eq(buy2.status, 400, 'the next purchase costs again (magnet refused on ~20 drips)');
const st = (await admin('/api/admin/state')).body; eq([st.pool.spends, st.spends.length], [0, 0], 'the free upgrade moved no POL (pool spends 0, no spend rows)');
// ---- a free POL item ----
({ ck: nm } = await signIn({ memberId: 91, email: 'nonmember@example.com', wallet: '0x' + 'cd'.repeat(20), username: 'nonmem' }, nm)); // the non-member buys and comes back as #91
const p91 = players()['91']; eq([p91 && p91.chapter, p91 && p91.freeUpgrades, !!(p91 && p91.perkAt)], [4, 1, true], 'non-member turned member: progress moved to #91 and the perk is granted');
const sh = await post('/api/hangar/buy', { item: 'shield' }, nm); eq([sh.status, sh.body.free, sh.body.balance.unpaid, sh.body.player.items.shield], [200, true, 0, true], 'free upgrade on a POL item (shield) with a 0 balance: armed, no POL taken');
const nc = await clearOne(nm); eq(nc.starterOffer === undefined, true, 'once a member, no more offers');
// ---- in process: InstantAdPay says off; the endpoint is down ----
process.env.DATA_DIR = DIR; const store = require('../lib/store'); store.init(DIR);
const game = require('../lib/game');
game.updPlayer(-123, x => { x.email = 'x@example.com'; });
stubOn = false; process.env.IAP_URL = IAPS; delete require.cache[require.resolve('../lib/starter')]; let starter = require('../lib/starter');
eq(await starter.offerFor({ memberId: -123 }), null, 'offer skipped while InstantAdPay reports on:false');
eq(game.player(-123).starterShown, undefined, '...and not recorded as shown');
process.env.IAP_URL = 'http://127.0.0.1:1'; delete require.cache[require.resolve('../lib/starter')]; starter = require('../lib/starter');
const down = await starter.offerFor({ memberId: -123 }); eq([down && down.bonus, down && down.perk], [null, 'a free hangar upgrade'], 'endpoint down: offer still shows, bonus null');
eq(/Error|TypeError/.test(serverErr), false, 'no server errors logged');
console.log(fails ? '\n' + fails + ' FAILED' : '\nall good');
child.kill(); stub.close(); fs.rmSync(DIR, { recursive: true, force: true }); process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); child.kill(); stub.close(); process.exit(1); });