Files
drip-runner/test/run.js
T

100 lines
9.3 KiB
JavaScript

// End-to-end on a local boot: hand-off + allowlist, a run with drip claims checked against the
// schedule, a chapter clear with the pool empty (pays nothing), a refuel callback that funds the
// pool, a paid clear, a replay that pays nothing, refused claims, the hangar sink, the payout
// sweep. No faucet, no outbound.
'use strict';
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const PORT = 8898, DIR = path.join(__dirname, '..', 'data-test');
fs.rmSync(DIR, { recursive: true, force: true });
const SECRET = 'y'.repeat(48);
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: 'http://iap.test' });
delete env.CURTAIN; delete env.OUTBOUND; delete env.DR_WALLET_KEY; delete env.DR_RPC; delete env.DR_SIGNUPS;
const child = spawn(process.execPath, [path.join(__dirname, '..', 'server.js')], { env, stdio: ['ignore', 'pipe', 'pipe'] });
child.stderr.on('data', 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;
let jar = '';
const call = async (p, opt = {}) => {
const res = await fetch(B + p, Object.assign({ redirect: 'manual' }, opt, { headers: Object.assign({ Cookie: jar, 'Content-Type': 'application/json' }, opt.headers || {}) }));
const sc = res.headers.get('set-cookie'); if (sc && /dr\.sid=[a-f0-9]/.test(sc)) jar = sc.split(';')[0];
let body = null; try { body = await res.json(); } catch (e) {}
return { status: res.status, body, headers: res.headers };
};
const post = (p, b, h) => call(p, { method: 'POST', body: JSON.stringify(b || {}), headers: h });
const admin = (p, b) => call(p, Object.assign({ headers: { 'X-Admin-Key': 'adminkey123' } }, b ? { method: 'POST', body: JSON.stringify(b) } : {}));
const sleep = ms => new Promise(r => setTimeout(r, ms));
const spawnLib = require('../lib/spawn');
(async () => {
await sleep(1200);
process.env.DR_SSO_SECRET = SECRET; const sso = require('../lib/sso');
const h = await call('/health'); eq([h.body.sso, h.body.faucet, h.body.signups], [true, false, 'testers'], 'posture: sso on, faucet off, testers mode');
// allowlist
const tok0 = sso.mint({ memberId: 42, email: 'runner@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'runner42' });
const denied = await call('/auth?t=' + tok0); eq(denied.status, 403, 'a member not on the tester list is refused');
const st = await admin('/api/admin/settings', { testers: ['runner@example.com'], thresholdPol: 0.02, dripPol: 0.01 }); eq(st.body.settings.testers, ['runner@example.com'], 'admin adds a tester');
const tok = sso.mint({ memberId: 42, email: 'runner@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'runner42' });
const a = await call('/auth?t=' + tok); eq([a.status, a.headers.get('location')], [302, '/play'], 'a listed member signs in and lands on the game');
eq((await call('/auth?t=' + tok)).status, 400, 'the hand-off token cannot be replayed');
const me = await call('/api/me'); eq([me.body.me.memberId, me.body.player.chapter, me.body.player.goal, me.body.balance.unpaid], [42, 1, 20, 0], '/api/me: chapter 1, goal 20, balance 0');
// a run: collect the first 20 drips exactly when the schedule says they cross the courier
const W = 390, H = 760;
const r1 = (await post('/api/run/start', { W, H })).body; eq([r1.chapter, r1.goal, r1.speed], [1, 20, 230], 'run starts on chapter 1 at speed 230');
const gen = spawnLib.drips(r1.seed, W, H); const claims = []; let lastT = 0;
while (claims.length < 20) { const g = gen(); for (const d of g.drips) { if (claims.length < 20) { const t = spawnLib.arrival(g.t, d.x0, W, r1.speed) + 0.1; claims.push({ k: 'd', i: d.i, t: Math.round(t * 1000) / 1000 }); lastT = t; } } }
const bad = [{ k: 'd', i: 500, t: 1 }, { k: 'd', i: claims[0].i, t: claims[0].t }]; // a drip that has not spawned, and a duplicate
// the run clock cannot outrun the wall clock: move the start back instead of waiting 15 s
const backdate = (runId, secs) => { const runs = JSON.parse(fs.readFileSync(path.join(DIR, 'runs.json'), 'utf8')); runs[runId].startedAt = Date.now() - secs * 1000; fs.writeFileSync(path.join(DIR, 'runs.json'), JSON.stringify(runs)); };
backdate(r1.runId, lastT + 5);
const ev = await post('/api/run/events', { runId: r1.runId, t: lastT + 0.2, events: claims.concat(bad), goal: true });
eq([ev.body.ok, ev.body.refused, ev.body.why], [20, 2, ['early', 'dup']], '20 claims accepted, 2 refused with reasons');
eq([ev.body.cleared.chapter, ev.body.cleared.first, ev.body.cleared.pol, ev.body.cleared.reason], [1, true, 0, 'pool'], 'first clear of chapter 1 with an empty pool: cleared, pays nothing');
const me2 = await call('/api/me'); eq([me2.body.player.chapter, me2.body.player.bank], [2, 20], 'player is on chapter 2 with 20 drips banked');
// refuel: the game hands out a token, IAP calls back with a signed body, the pool fills
const rf = await post('/api/refuel/start', { runId: r1.runId }); eq([rf.status, rf.body.url.startsWith('http://iap.test/refuel?t=')], [200, true], 'refuel start mints an IAP link');
const nonce = rf.body.nonce;
const raw = JSON.stringify({ nonce, memberId: 42, campaignId: 77, credits: 3 }); const ts = String(Date.now());
const badSig = await call('/api/refuel/callback', { method: 'POST', body: raw, headers: { 'X-DR-Ts': ts, 'X-DR-Sig': 'nope' } }); eq(badSig.status, 401, 'an unsigned callback is refused');
const sig = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex');
const cb = await call('/api/refuel/callback', { method: 'POST', body: raw, headers: { 'X-DR-Ts': ts, 'X-DR-Sig': sig } }); eq([cb.status, cb.body.pol > 0], [200, true], 'a signed callback credits the pool');
const stA = await admin('/api/admin/state'); const expectPol = Math.round((3 * 0.01 * 0.30 / stA.body.usdPerPol) * 10000) / 10000; eq(stA.body.pool.in, expectPol, 'pool in = 3 credits x $0.01 x 30% / usdPerPol (' + expectPol + ')');
const rs = await post('/api/refuel/resume', { runId: r1.runId, nonce }); eq([rs.body.ok, rs.body.pool], [true, expectPol], 'the run resumes once the callback landed');
eq((await post('/api/refuel/resume', { runId: r1.runId, nonce })).status, 400, 'a refuel cannot be consumed twice');
// chapter 2 (goal 32) in the same run: paid from the pool
const claims2 = []; let t2 = 0; let g2; while (claims2.length < 32) { g2 = gen(); for (const d of g2.drips) if (claims2.length < 32) { const t = spawnLib.arrival(g2.t, d.x0, W, r1.speed) - 0.3; claims2.push({ k: 'd', i: d.i, t: Math.round(t * 1000) / 1000 }); t2 = t; } }
// the run clock must have moved: patch startedAt back so the wall check passes without waiting
backdate(r1.runId, t2 + 5);
const ev2 = await post('/api/run/events', { runId: r1.runId, t: t2 + 0.2, events: claims2, goal: true });
eq([ev2.body.ok, ev2.body.cleared.chapter, ev2.body.cleared.pol, ev2.body.cleared.reason], [32, 2, 0.01, 'paid'], 'chapter 2 clear pays 0.01 POL from the pool');
const bal = await call('/api/balance'); eq([bal.body.unpaid, bal.body.history[0].kind], [0.01, 'drip'], 'balance shows the drip');
await post('/api/run/end', { runId: r1.runId });
// a replay of chapter 1 pays nothing; the hangar sink works; the sweep makes a payout row
const r2 = (await post('/api/run/start', { W, H })).body; eq(r2.chapter, 3, 'a new run starts on chapter 3 (progress kept)');
await post('/api/run/end', { runId: r2.runId });
const buyNo = await post('/api/hangar/buy', { item: 'shield' }); eq(buyNo.status, 400, 'shield (0.05 POL) refused on a 0.01 balance');
await admin('/api/admin/settings', { itemPol: { slow: 0.005 } });
const buy = await post('/api/hangar/buy', { item: 'slow' }); eq([buy.status, buy.body.paid, buy.body.balance.unpaid], [200, '0.005 POL', 0.005], 'slow field bought from the POL balance');
const stB = await admin('/api/admin/state'); eq(stB.body.pool.spends, 0.005, 'the spend went back to the pool');
const magnet = await post('/api/hangar/buy', { item: 'magnet' }); eq(magnet.status, 400, 'magnet (250 drips) refused on 52 drips');
await admin('/api/admin/settings', { thresholdPol: 0.005 });
const stC = await admin('/api/admin/state'); // state does not sweep; the faucet does. call the ledger directly through a tick with no wallet: payable() is exercised by the sweep below
eq(stC.body.accounts[0].unpaid, 0.005, 'account unpaid is 0.005 before the sweep');
process.env.DATA_DIR = DIR; const store = require('../lib/store'); store.init(DIR); const ledger = require('../lib/ledger');
const due = ledger.payable(); eq([due.length, due[0].pol, due[0].wallet], [1, 0.005, '0x' + 'ab'.repeat(20)], 'the sweep turns a balance at threshold into one due payout row');
eq(ledger.account(42).unpaid, 0, 'the balance moved onto the payout row');
ledger.mark(due[0].id, { status: 'failed', error: 'test' }); eq(ledger.account(42).unpaid, 0.005, 'a failed payout returns the POL to the balance');
console.log(fails ? '\n' + fails + ' FAILED' : '\nall good');
child.kill(); fs.rmSync(DIR, { recursive: true, force: true }); process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); child.kill(); process.exit(1); });