Files
drip-runner/test/run.js
T
martbost 11d6f46950 Invite friends card in the lobby + ?ref attribution on every entry page
Marty: members could not find their referral link. A signed-in player now sees an
"Invite friends" card right under Play: their /r/<username> link (previews with their
own card), Copy (clipboard API, select+copy fallback, prompt last) with a Copied!
confirmation, and Share where the phone has a share sheet. Link stats and the how-it-works
line moved into the card. No username yet: the card says how to get one.

Attribution: ?ref=<name> on /, /play and /signin (and ?r= on the landing, where framed
/r/<name> lands) now sets the same dr.ref sponsor cookie as /r/<name>, last touch wins.
/r/<name> for a name the game does not know keeps it as /?ref=<name> instead of
dropping it. signin.js also reads ?ref straight from the URL. Tests cover each path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:25:22 -05:00

144 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 () => {
for (let i = 0; i < 60; i++) { try { await fetch(B + '/health'); break; } catch (e) { await sleep(250); } }
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 perkBuy = await post('/api/hangar/buy', { item: 'ship' }); eq([perkBuy.status, perkBuy.body.free], [200, true], 'the member perk (one free upgrade, 2026-10-05) pays for the first purchase'); // test/starter.js covers it in full
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');
// ---- referral layer (2026-09-30): share link, guest play, adoption on sign-in, the referrer's slice ----
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('; '); };
await admin('/api/admin/settings', { signups: 'open', thresholdPol: 5, refSharePct: 10 });
eq((await hit('/r/nobody')).loc, '/?ref=nobody', 'a share link for a name the game does not know goes to the landing page with the name kept as ?ref');
// ?ref=<name> (2026-10-05): the landing, the game and sign-in all set the same sponsor cookie; ?r= only on the landing (on /play it is the refuel receipt)
for (const [path, want] of [['/?ref=Alice', 'alice'], ['/?r=alice', 'alice'], ['/play?ref=alice', 'alice'], ['/signin?ref=@alice', 'alice'], ['/play?r=receipt', null], ['/?ref=bad%20name', null]]) {
const x = await hit(path); const c = x.set.find(s => /^dr\.ref=/.test(s)) || null;
eq([x.status, c ? /^dr\.ref=([^;]*)/.exec(c)[1] : null], [200, want], path + (want ? ' sets dr.ref=' + want : ' sets no sponsor cookie'));
}
{ const x = await hit('/?ref=alice&src=adsterra&cid=c1'); eq([x.set.some(s => /^dr\.ref=alice/.test(s)), x.set.some(s => /^dr\.src=/.test(s))], [true, true], 'a paid-traffic landing with ?ref keeps both cookies'); }
{ const x = await hit('/r/runner42', { headers: { 'Sec-Fetch-Dest': 'iframe' } }); eq(x.loc, '/?r=runner42', 'a framed share link lands on the landing with ?r'); }
const sh = await hit('/r/runner42'); eq([sh.status, sh.loc, sh.set.some(c => /^dr\.ref=runner42/.test(c))], [302, '/play', true], 'a player share link sets the referrer and opens the game');
let g = jarAdd('', sh.set);
const me401 = await hit('/api/me', {}, g); eq([me401.status, me401.body.guestOk, me401.body.signin === '/signin'], [401, true, true], 'a newcomer is offered guest play, sign-in stays in the game (/signin; the kit carries the dr.ref sponsor)');
const gs = await hit('/api/guest', { method: 'POST', body: '{}' }, g); g = jarAdd(g, gs.set); eq(gs.status, 200, 'guest session starts');
const gme = await hit('/api/me', {}, g); eq([gme.status, gme.body.me.guest, gme.body.player.chapter], [200, true, 1], 'guest plays chapter 1');
const gr = (await hit('/api/run/start', { method: 'POST', body: JSON.stringify({ W, H }) }, g)).body;
const ggen = spawnLib.drips(gr.seed, W, H); const gcl = []; let gT = 0; while (gcl.length < 20) { const gg = ggen(); for (const d of gg.drips) if (gcl.length < 20) { gT = spawnLib.arrival(gg.t, d.x0, W, gr.speed) + 0.1; gcl.push({ k: 'd', i: d.i, t: Math.round(gT * 1000) / 1000 }); } }
backdate(gr.runId, gT + 5);
const gev = (await hit('/api/run/events', { method: 'POST', body: JSON.stringify({ runId: gr.runId, t: gT + 0.2, events: gcl, goal: true }) }, g)).body;
eq([gev.cleared.chapter, gev.cleared.pol, gev.cleared.reason], [1, 0, 'guest'], 'a guest clear pays nothing yet (reason guest)');
eq((await hit('/api/refuel/start', { method: 'POST', body: JSON.stringify({ runId: gr.runId }) }, g)).status, 403, 'a guest cannot refuel before signing in');
// the newcomer joins IAP under runner42 and signs in: the guest run is adopted and the clear pays
const tokN = sso.mint({ memberId: 77, email: 'newbie@example.com', wallet: '0x' + 'cd'.repeat(20), username: 'newbie', sponsorRef: 'runner42' });
const au = await hit('/auth?t=' + tokN, {}, g); g = jarAdd(g, au.set);
eq([au.status, au.loc], [302, '/play?collected=1'], 'sign-in adopts the guest and pays the pending clear');
const nme = (await hit('/api/me', {}, g)).body; eq([nme.me.guest, nme.player.chapter, nme.player.bank, nme.balance.unpaid], [false, 2, 20, 0.01], 'progress and the drip followed the newcomer');
// the newcomer refuels: runner42 (their IAP sponsor) gets the slice
const nr = (await hit('/api/run/start', { method: 'POST', body: JSON.stringify({ W, H }) }, g)).body;
const nrf = (await hit('/api/refuel/start', { method: 'POST', body: JSON.stringify({ runId: nr.runId }) }, g)).body;
const body2 = JSON.stringify({ nonce: nrf.nonce, memberId: 77, campaignId: 88, credits: 3 }); const ts2 = String(Date.now());
await hit('/api/refuel/callback', { method: 'POST', body: body2, headers: { 'X-DR-Ts': ts2, 'X-DR-Sig': crypto.createHmac('sha256', SECRET).update(ts2 + '\n' + body2).digest('hex') } });
const stR = (await admin('/api/admin/state')).body; const refuelPol = stR.refuels[0].pol; const slice = Math.round(refuelPol * 0.10 * 10000) / 10000;
const runnerAcct = stR.accounts.find(a => a.memberId === 42); eq(runnerAcct.refTotal, slice, 'the sponsor earned 10% of the referral’s refuel pool income (' + slice + ' POL)');
const rme = await call('/api/me'); eq([rme.body.referrals.count, rme.body.referrals.clicks, /\/r\/runner42$/.test(rme.body.share)], [1, 1, true], 'the sharer sees one referral, one link visit, and their share link');
// wallet-less member later links a wallet: the email-derived history moves to the on-chain id
const tokW = sso.mint({ memberId: 0, email: 'free@example.com', wallet: null, username: 'freebie' }); let w = '';
const aw = await hit('/auth?t=' + tokW); w = jarAdd(w, aw.set); const wme = (await hit('/api/me', {}, w)).body; eq(wme.me.memberId < 0, true, 'a wallet-less member plays on a temporary id');
process.env.DATA_DIR = DIR; const gameLib = require('../lib/game'); gameLib.updPlayer(wme.me.memberId, x => { x.bank = 33; x.chapter = 4; x.cleared = { 1: true, 2: true, 3: true }; });
const tokW2 = sso.mint({ memberId: 91, email: 'free@example.com', wallet: '0x' + 'ef'.repeat(20), username: 'freebie' });
await hit('/auth?t=' + tokW2); const moved = gameLib.player(91); eq([moved && moved.chapter, moved && moved.bank, !!gameLib.player(wme.me.memberId)], [4, 33, false], 'after the wallet is linked, progress moves to the on-chain id');
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); });