Referral layer: guest play from share links (/r/<username>), guest clears paid on sign-in, sharer's link via their IAP join page, 10% referrer slice of each referral refuel's pool income (IAP sponsor), share buttons + stats in the lobby and on chapter clears, wallet-less progress follows the member once a wallet is linked; 11 new checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-09-30 17:14:08 -05:00
parent 83da8c33f2
commit 06daa4ef0a
10 changed files with 203 additions and 25 deletions
+51 -10
View File
@@ -149,7 +149,8 @@ const intents = { get: n => store.read('refuel-intents', {})[n] || null, set: (n
async function creditRefuel(intent, nonce, info) {
if (intent.credited) return intent;
const me = { memberId: intent.memberId, username: intent.username, wallet: intent.wallet };
const row = await ledger.refuel(me, Object.assign({ nonce }, info));
const pl = game.player(intent.memberId) || {}; const sp = pl.sponsorRef ? game.byRef(pl.sponsorRef) : null;
const row = await ledger.refuel(me, Object.assign({ nonce, referrer: sp ? { memberId: sp.memberId, username: sp.username, wallet: sp.wallet } : null }, info));
intents.upd(nonce, x => { x.credited = row.id; x.done = true; x.campaignId = info.campaignId || null; x.pol = row.pol; });
notify('refuel', Object.assign({}, me, { campaignId: info.campaignId, credits: row.credits, share: row.share, pol: row.pol })).catch(() => {});
return intents.get(nonce);
@@ -171,11 +172,29 @@ const server = http.createServer(async (req, res) => {
let sid;
if (existing && existing.memberId === Number(r.claims.memberId)) { sso.refresh(existing.sid, r.claims); sid = existing.sid; }
else sid = sso.startSession(r.claims);
const first = !game.player(r.claims.memberId);
// progress follows the person: a guest who signs in, and a wallet-less member who has since linked a wallet
const existedBefore = !!(game.player(r.claims.memberId) || {}).email; // a guest record adopted below has no email yet
const adopted = [];
const guest = sso.guestFrom(req);
if (Number(r.claims.memberId) > 0) { const ad = game.adopt(sso.emailId(r.claims.email), r.claims.memberId); if (ad.moved) adopted.push('wallet-less history'); }
const pendingClears = guest ? game.adopt(guest.memberId, r.claims.memberId).pending : [];
if (guest) sso.endGuest(guest.gid);
const first = !existedBefore;
game.updPlayer(r.claims.memberId, x => { x.email = String(r.claims.email).toLowerCase(); x.username = r.claims.username || x.username || null; x.wallet = r.claims.wallet ? String(r.claims.wallet).toLowerCase() : x.wallet || null; x.lastSeen = Date.now(); });
if (first) notify('signin', { memberId: r.claims.memberId, username: r.claims.username, wallet: r.claims.wallet }).catch(() => {});
res.writeHead(302, { Location: '/play', 'Set-Cookie': sso.cookie(sid), 'Cache-Control': 'no-store' }); return res.end();
game.updPlayer(r.claims.memberId, x => { if (!x.sponsorRef && r.claims.sponsorRef) x.sponsorRef = String(r.claims.sponsorRef).toLowerCase(); if (r.claims.joinedRef && !x.joinedRef) x.joinedRef = r.claims.joinedRef; });
const meNow = { memberId: Number(r.claims.memberId), username: r.claims.username || null, wallet: r.claims.wallet ? String(r.claims.wallet).toLowerCase() : null };
for (const ch of pendingClears) { const g = ledger.chapterDrip(meNow, ch, true); if (g.pol) announceChapter(meNow, ch, g.pol); } // clears made as a guest pay now
if (first) notify('signin', { memberId: r.claims.memberId, username: r.claims.username, wallet: r.claims.wallet, via: guest ? 'a share link' : null }).catch(() => {});
res.writeHead(302, { Location: '/play' + (pendingClears.length ? '?collected=' + pendingClears.length : ''), 'Set-Cookie': [sso.cookie(sid)].concat(guest ? [sso.clearGuestCookie()] : []), 'Cache-Control': 'no-store' }); return res.end();
}
{ const mr = /^\/r\/([A-Za-z0-9_.-]{1,40})$/.exec(p); if (mr) {
const sharer = game.byUsername(mr[1]);
if (!sharer) { res.writeHead(302, { Location: '/', 'Cache-Control': 'no-store' }); return res.end(); }
const ck = ['dr.ref=' + encodeURIComponent(sharer.username.toLowerCase()) + '; Path=/; Max-Age=' + 30 * 86400 + '; SameSite=Lax' + (IS_PROD ? '; Secure' : '')];
if (CURTAIN) ck.push('dr.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : '')); // a player's link is a pass during the trial
store.update('share-hits', {}, h => { const k = sharer.username.toLowerCase(); h[k] = (h[k] || 0) + 1; return h; });
res.writeHead(302, { Location: '/play', 'Set-Cookie': ck, 'Cache-Control': 'no-store' }); return res.end();
} }
if (p === '/logout') { const s = sso.fromRequest(req); if (s) sso.endSession(s.sid); res.writeHead(302, { Location: '/', 'Set-Cookie': sso.clearCookie() }); return res.end(); }
// ---- IAP -> game: the refuel visit completed (server to server, signed) ----
@@ -209,7 +228,7 @@ const server = http.createServer(async (req, res) => {
}
if (p === '/api/admin/settings' && req.method === 'POST') {
const { body } = await readBody(req); const patch = {};
for (const k of ['usdPerCredit', 'creditsPerVisit', 'poolSharePct', 'usdPerPolFallback', 'dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'lowBalancePol']) if (body[k] != null && body[k] !== '') patch[k] = Number(body[k]);
for (const k of ['refSharePct', 'usdPerCredit', 'creditsPerVisit', 'poolSharePct', 'usdPerPolFallback', 'dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'lowBalancePol']) if (body[k] != null && body[k] !== '') patch[k] = Number(body[k]);
if (body.signups && ['testers', 'key', 'open', 'closed'].includes(body.signups)) patch.signups = body.signups;
if (body.trial === 'on' || body.trial === 'off') patch.trial = body.trial === 'on';
if (Array.isArray(body.testers)) patch.testers = body.testers.map(x => String(x).trim().toLowerCase()).filter(Boolean).slice(0, 500);
@@ -232,18 +251,41 @@ const server = http.createServer(async (req, res) => {
}
return json(res, 404, { error: 'no such admin route' });
}
if (!me) return json(res, 401, { error: 'Sign in through InstantAdPay first.', iap: IAP + '/api/my/driprunner' });
if (p === '/api/guest' && req.method === 'POST') {
if (me) return json(res, 200, { ok: true, already: true });
if (CURTAIN && !hasPass(req)) return json(res, 403, { error: 'Open the tester link or a player\u2019s share link first.' });
const g = sso.startGuest(refCookie(req)); return json(res, 200, { ok: true }, { 'Set-Cookie': sso.guestCookie(g.gid) });
}
const who = me || sso.guestFrom(req);
if (!who) return json(res, 401, { error: 'Sign in through InstantAdPay first.', iap: IAP + '/api/my/driprunner', guestOk: !CURTAIN || hasPass(req), signin: signinUrl(req) });
return memberApi(req, res, u, p, who);
}
res.writeHead(404, Object.assign({ 'Content-Type': 'text/plain' }, SEC)); res.end('Not found');
} catch (e) {
console.error(req.method, p, e && e.stack || e);
if (!res.headersSent) json(res, 500, { error: 'Something broke on our side. Try again.' });
}
});
function refCookie(req) { const m = /(?:^|;\s*)dr\.ref=([^;]+)/.exec(req.headers.cookie || ''); const r = m ? decodeURIComponent(m[1]) : ''; return /^[a-z0-9_.-]{1,40}$/.test(r) ? r : null; }
// where a guest signs in: through the sharer's InstantAdPay join link when they came from one (new people land under the sharer), else the plain hand-off
function signinUrl(req) { const r = refCookie(req); return r ? IAP + '/join/' + encodeURIComponent(r) + '?from=driprunner' : IAP + '/api/my/driprunner'; }
async function memberApi(req, res, u, p, me) {
try {
{
if (p === '/api/me' && req.method === 'GET') {
const pl = ledger.pool();
return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet }, player: game.view(me), balance: ledger.balance(me.memberId), pool: { available: pl.available, capLeft: pl.capLeft, dripPol: Number(ledger.settings().dripPol) }, iap: IAP, site: SITE, tips: await tips.list(ledger.settings()) });
const refs = me.guest ? [] : game.referralsOf(me);
return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet, guest: !!me.guest }, player: game.view(me), balance: ledger.balance(me.memberId), pool: { available: pl.available, capLeft: pl.capLeft, dripPol: Number(ledger.settings().dripPol) }, iap: IAP, site: SITE, tips: await tips.list(ledger.settings()),
signin: me.guest ? signinUrl(req) : null, share: (!me.guest && me.username) ? SITE + '/r/' + encodeURIComponent(me.username) : null, referrals: { count: refs.length, clicks: (store.read('share-hits', {})[String(me.username || '').toLowerCase()] || 0), earned: ledger.balance(me.memberId).refTotal, pct: Number(ledger.settings().refSharePct) || 0 } });
}
if (p === '/api/balance' && req.method === 'GET') return json(res, 200, ledger.balance(me.memberId));
if (p === '/api/run/start' && req.method === 'POST') { const { body } = await readBody(req); const r = game.start(me, body.W, body.H); return json(res, 200, { runId: r.id, seed: r.seed, W: r.W, H: r.H, speed: r.speed, chapter: r.chapter, goal: r.goal, armed: r.armed, ship: r.ship }); }
if (p === '/api/run/events' && req.method === 'POST') { const { body } = await readBody(req); const r = game.events(me, String(body.runId || ''), body.t, body.events, !!body.goal); if (r.cleared) { r.pool = ledger.pool().available; if (r.cleared.first) announceChapter(me, r.cleared.chapter, r.cleared.pol); } return json(res, r.error ? 400 : 200, r); }
if (p === '/api/run/events' && req.method === 'POST') { const { body } = await readBody(req); const r = game.events(me, String(body.runId || ''), body.t, body.events, !!body.goal); if (r.cleared) { r.pool = ledger.pool().available; if (r.cleared.first && !me.guest) announceChapter(me, r.cleared.chapter, r.cleared.pol); } return json(res, r.error ? 400 : 200, r); }
if (p === '/api/run/end' && req.method === 'POST') { const { body } = await readBody(req); return json(res, 200, game.end(me, String(body.runId || ''))); }
// refuel: hand the player to IAP for a verified visit; the run resumes when IAP confirms
if (p === '/api/refuel/start' && req.method === 'POST') {
const { body } = await readBody(req); const r = game.run(String(body.runId || ''));
if (me.guest) return json(res, 403, { error: 'Sign in with InstantAdPay to refuel. Your run and progress come with you.', signin: signinUrl(req) });
if (!r || r.memberId !== me.memberId || r.status !== 'live') return json(res, 400, { error: 'That run cannot be refuelled.' });
const nonce = crypto.randomBytes(12).toString('hex'); const ret = SITE + '/play?resume=' + r.id + '&n=' + nonce;
intents.set(nonce, { runId: r.id, memberId: me.memberId, username: me.username, wallet: me.wallet, email: me.email, ts: Date.now(), done: false, consumed: false });
@@ -263,11 +305,10 @@ const server = http.createServer(async (req, res) => {
if (p === '/api/hangar/buy' && req.method === 'POST') { const { body } = await readBody(req); const item = String(body.item || ''); const r = game.buy(me, item); if (!r.error) { r.player = game.view(me); r.balance = ledger.balance(me.memberId); announceUnlock(me, item, r.paid); } return json(res, r.error ? 400 : 200, r); }
return json(res, 404, { error: 'no such route' });
}
res.writeHead(404, Object.assign({ 'Content-Type': 'text/plain' }, SEC)); res.end('Not found');
} catch (e) {
console.error(req.method, p, e && e.stack || e);
if (!res.headersSent) json(res, 500, { error: 'Something broke on our side. Try again.' });
}
});
}
server.listen(PORT, () => console.log('Drip Runner on', PORT, '| curtain', !!CURTAIN, '| sso', sso.enabled(), '| faucet', faucetOn, faucet.dry() ? '(DRY RUN)' : '(LIVE)', '| outbound', outbound()));
if (faucetOn) { setInterval(() => faucet.tick(notify).catch(e => console.error('faucet', e.message)), 120000); setTimeout(() => faucet.tick(notify).catch(() => {}), 8000); }