diff --git a/lib/game.js b/lib/game.js index 31bef5d..6d5bbb1 100644 --- a/lib/game.js +++ b/lib/game.js @@ -94,8 +94,9 @@ function events(me, runId, t, list, wantGoal) { if (out.chapDrips < out.goal) { res.cleared = null; res.short = out.goal - out.chapDrips; return res; } const ch = out.chapter; const p = player(me.memberId); const first = !(p.cleared || {})[ch]; - const grant = ledger.chapterDrip(me, ch, first && !out.flagged); + const grant = me.guest ? { pol: 0, reason: 'guest' } : ledger.chapterDrip(me, ch, first && !out.flagged); if (first && out.flagged) grant.reason = 'flagged'; + if (me.guest && first && !out.flagged) updPlayer(me.memberId, x => { x.pending = Array.from(new Set([...(x.pending || []), ch])); }); // paid when they sign in updPlayer(me.memberId, x => { x.cleared[ch] = true; if (x.chapter <= ch) x.chapter = ch + 1; }); updRun(runId, x => { x.cleared.push(ch); x.chapter = ch + 1; x.chapDrips = 0; x.goal = spawn.goalFor(ch + 1); }); res.cleared = { chapter: ch, first, pol: grant.pol, reason: grant.reason, next: ch + 1, nextGoal: spawn.goalFor(ch + 1), playTime: Math.round(out.t) }; @@ -129,6 +130,35 @@ function buy(me, item) { } return { error: 'No such item.' }; } +// Move everything one id owns onto another (a guest who signs in, or a wallet-less member who links a wallet). +// Returns the chapters the old id cleared as a guest that the new id has never cleared: the caller pays those. +function adopt(fromId, toId) { + fromId = Number(fromId); toId = Number(toId); if (!fromId || fromId === toId) return { moved: false, pending: [] }; + const all = store.read('players', {}); const a = all[String(fromId)]; if (!a) return { moved: false, pending: [] }; + const b = all[String(toId)]; const pending = (a.pending || []).filter(ch => !(b && b.cleared && b.cleared[ch])); + store.update('players', {}, ps => { + const src = ps[String(fromId)]; const dst = ps[String(toId)]; + if (!dst) { ps[String(toId)] = Object.assign({}, src, { memberId: toId, pending: [] }); } + else { dst.bank += src.bank; dst.runs += src.runs; dst.best = Math.max(dst.best, src.best); dst.chapter = Math.max(dst.chapter, src.chapter); dst.cleared = Object.assign({}, src.cleared, dst.cleared); dst.items = Object.assign({}, src.items, dst.items); } + delete ps[String(fromId)]; return ps; + }); + for (const name of ['drips', 'spends', 'refuels', 'payouts']) store.update(name, [], rows => { for (const r of rows) if (r.memberId === fromId) r.memberId = toId; return rows; }); + store.update('accounts', {}, acc => { const x = acc[String(fromId)]; if (x) { const y = acc[String(toId)]; if (y) { y.unpaid = Math.round((y.unpaid + x.unpaid) * 10000) / 10000; y.earnedTotal = Math.round(((y.earnedTotal || 0) + (x.earnedTotal || 0)) * 10000) / 10000; y.spentTotal = Math.round(((y.spentTotal || 0) + (x.spentTotal || 0)) * 10000) / 10000; } else acc[String(toId)] = Object.assign({}, x, { memberId: toId }); delete acc[String(fromId)]; } return acc; }); + store.update('runs', {}, rs => { for (const k of Object.keys(rs)) if (rs[k].memberId === fromId) rs[k].memberId = toId; return rs; }); + store.update('posted', {}, ps => { if (ps[String(fromId)]) { ps[String(toId)] = Array.from(new Set([...(ps[String(toId)] || []), ...ps[String(fromId)]])); delete ps[String(fromId)]; } return ps; }); + return { moved: true, pending }; +} +// the players whose InstantAdPay sponsor is this member (their referrals in the game) +function referralsOf(me) { + const keys = [String(me.memberId), String(me.username || '').toLowerCase()].filter(Boolean); + return Object.values(store.read('players', {})).filter(p => p.memberId > 0 && p.sponsorRef && keys.includes(String(p.sponsorRef).toLowerCase())); +} +// the game player a sponsorRef points at (username, or on-chain member id) +function byRef(ref) { + const r = String(ref || '').trim().toLowerCase(); if (!r) return null; + return Object.values(store.read('players', {})).find(p => p.memberId > 0 && ((p.username && p.username.toLowerCase() === r) || String(p.memberId) === r)) || null; +} +function byUsername(u) { const r = String(u || '').trim().toLowerCase().replace(/^@/, ''); return r ? Object.values(store.read('players', {})).find(p => p.username && p.username.toLowerCase() === r) || null : null; } function recent(n) { return Object.values(runs()).sort((a, b) => b.startedAt - a.startedAt).slice(0, n || 50).map(r => Object.assign({}, r, { collected: r.collected.length })); } -module.exports = { player, updPlayer, view, run, start, events, end, refuelled, buy, recent, prune }; +module.exports = { player, updPlayer, view, run, start, events, end, refuelled, buy, recent, prune, adopt, referralsOf, byRef, byUsername }; diff --git a/lib/ledger.js b/lib/ledger.js index bc55064..dfa7ff2 100644 --- a/lib/ledger.js +++ b/lib/ledger.js @@ -24,6 +24,7 @@ const DEFAULTS = { lowBalancePol: 1, itemPol: { shield: 0.05, slow: 0.03 }, // hangar items paid from the POL balance (the sink) itemDrips: { magnet: 250, ship: 600 }, // hangar items paid in drips (never money) + refSharePct: 10, // the referrer's slice of each refuel's pool income (their referrals' refuels), paid into the referrer's game balance testers: [], // emails or member ids allowed through the hand-off while signups = 'testers' trial: true, // posts say 'coming soon, in testing' and 'would have earned' until Marty flips it signups: 'testers' // 'testers' | 'key' (tester list or the curtain pass) | 'open' | 'closed' @@ -58,6 +59,17 @@ async function refuel(me, info) { const row = { id: id(), nonce: info.nonce || null, memberId: Number(me.memberId), username: me.username || null, campaignId: info.campaignId || null, credits, usd: r4(usd), share: r4(share), usdPerPol: r4(rate), pol, via: info.via || 'callback', day: ctDay(), ts: Date.now() }; store.update('refuels', [], all => { all.push(row); return all; }); poolAdd('in', pol); + // the referral slice: a cut of THIS refuel's pool income, so it can never cost more than the refuel brought in + const ref = info.referrer; const pct = Number(s.refSharePct) || 0; + if (ref && ref.memberId > 0 && ref.memberId !== Number(me.memberId) && pct > 0) { + const slice = r4(pol * pct / 100); + if (slice > 0) { + poolAdd('out', slice); + updAccount(ref.memberId, a => { a.unpaid += slice; a.earnedTotal = r4((a.earnedTotal || 0) + slice); a.refTotal = r4((a.refTotal || 0) + slice); a.wallet = a.wallet || ref.wallet || null; a.username = a.username || ref.username || null; }); + store.update('refslices', [], all => { all.push({ id: id(), refuelId: row.id, memberId: ref.memberId, fromMemberId: Number(me.memberId), fromUsername: me.username || null, pol: slice, day: ctDay(), ts: Date.now() }); return all; }); + row.slice = { to: ref.memberId, pol: slice }; + } + } return row; } function refuelsToday() { const d = ctDay(); return store.read('refuels', []).filter(r => r.day === d); } @@ -125,9 +137,10 @@ function balance(memberId) { const hist = [] .concat(store.read('drips', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'drip', label: 'Chapter ' + d.chapter + ' · first clear', pol: d.pol }))) .concat(store.read('spends', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'spend', label: 'Hangar · ' + d.item, pol: -d.pol }))) + .concat(store.read('refslices', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'ref', label: 'Referral · ' + (d.fromUsername ? '@' + d.fromUsername : 'a player') + ' refuelled', pol: d.pol }))) .concat(store.read('payouts', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'payout', label: d.status === 'paid' ? 'Paid to your wallet' : d.status === 'failed' ? 'Payout failed: ' + (d.error || '') : 'Payout on its way', pol: d.pol, status: d.status, tx: d.tx || null }))) .sort((x, y) => y.t - x.t).slice(0, 40); - return { unpaid: r4(a.unpaid), paidTotal: r4(a.paidTotal || 0), spentTotal: r4(a.spentTotal || 0), earnedTotal: r4(a.earnedTotal || 0), threshold: Number(s.thresholdPol), history: hist, wallet: a.wallet || null }; + return { unpaid: r4(a.unpaid), paidTotal: r4(a.paidTotal || 0), spentTotal: r4(a.spentTotal || 0), earnedTotal: r4(a.earnedTotal || 0), refTotal: r4(a.refTotal || 0), refSharePct: Number(s.refSharePct) || 0, threshold: Number(s.thresholdPol), history: hist, wallet: a.wallet || null }; } module.exports = { DEFAULTS, settings, setSettings, ctDay, pool, refuel, refuelsToday, account, chapterDrip, spend, sweep, payable, mark, balance, usdPerPol, r4 }; diff --git a/lib/sso.js b/lib/sso.js index e130e80..8ecaa7d 100644 --- a/lib/sso.js +++ b/lib/sso.js @@ -16,7 +16,24 @@ const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/ const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64'); const sign = payload => b64u(crypto.createHmac('sha256', SECRET).update(payload).digest()); +const secure = () => process.env.NODE_ENV === 'production' ? '; Secure' : ''; function enabled() { return SECRET.length >= 32; } +// the temporary id of a member with no on-chain id yet (no wallet): negative, derived from the email +function emailId(email) { return -parseInt(crypto.createHash('sha256').update(String(email).toLowerCase()).digest('hex').slice(0, 11), 16); } +// guests (a share link, no sign-in yet): their own negative range, far below any email id +function guestFrom(req) { + const m = /(?:^|;\s*)dr\.gid=([a-f0-9]{32})/.exec(req.headers.cookie || ''); if (!m) return null; + const g = store.read('guests', {})[m[1]]; if (!g) return null; + return { gid: m[1], memberId: g.memberId, guest: true, username: null, wallet: null, email: null, ref: g.ref || null }; +} +function startGuest(ref) { + const gid = crypto.randomBytes(16).toString('hex'); const memberId = -(2 ** 45 + crypto.randomInt(2 ** 40)); + store.update('guests', {}, g => { const cut = Date.now() - 30 * 86400000; for (const k of Object.keys(g)) if (g[k].since < cut) delete g[k]; g[gid] = { memberId, since: Date.now(), ref: ref || null }; return g; }); + return { gid, memberId }; +} +function endGuest(gid) { store.update('guests', {}, g => { delete g[gid]; return g; }); } +function guestCookie(gid) { return 'dr.gid=' + gid + '; Path=/; Max-Age=' + 30 * 86400 + '; HttpOnly; SameSite=Lax' + secure(); } +function clearGuestCookie() { return 'dr.gid=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax' + secure(); } function mint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 5 * 60000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return b64u(payload) + '.' + sign(payload); @@ -39,7 +56,7 @@ function verify(token) { const c = r.claims; if (!c.email) return { error: 'That sign-in link is missing your account.' }; // a free member with no wallet has no on-chain id yet: key them on their email until they link one - if (!(Number(c.memberId) > 0)) c.memberId = -parseInt(crypto.createHash('sha256').update(String(c.email).toLowerCase()).digest('hex').slice(0, 11), 16); + if (!(Number(c.memberId) > 0)) c.memberId = emailId(c.email); for (const [n, exp] of used) if (exp < Date.now()) used.delete(n); if (used.has(c.nonce)) return { error: 'That sign-in link was already used.' }; used.set(c.nonce, c.exp); @@ -55,7 +72,6 @@ function startSession(claims) { }); return id; } -const secure = () => process.env.NODE_ENV === 'production' ? '; Secure' : ''; function cookie(id) { return 'dr.sid=' + id + '; Path=/; Max-Age=' + Math.floor(SESSION_TTL / 1000) + '; HttpOnly; SameSite=Lax' + secure(); } function clearCookie() { return 'dr.sid=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax' + secure(); } function fromRequest(req) { @@ -68,4 +84,4 @@ function fromRequest(req) { function endSession(sid) { store.update('sessions', {}, s => { delete s[sid]; return s; }); } function refresh(sid, claims) { store.update('sessions', {}, s => { if (s[sid]) { s[sid].wallet = claims.wallet ? String(claims.wallet).toLowerCase() : null; s[sid].username = claims.username || s[sid].username; } return s; }); } -module.exports = { enabled, mint, open, verify, startSession, cookie, clearCookie, fromRequest, endSession, refresh }; +module.exports = { enabled, mint, open, verify, startSession, cookie, clearCookie, fromRequest, endSession, refresh, emailId, guestFrom, startGuest, endGuest, guestCookie, clearGuestCookie }; diff --git a/lib/tips.js b/lib/tips.js index b79f334..bcb009c 100644 --- a/lib/tips.js +++ b/lib/tips.js @@ -27,6 +27,7 @@ async function list(settings) { 'Only the first clear of a chapter pays a drip (' + fmt(drip) + ' POL). Replays are for practice and for drips to spend in the hangar.', 'Your first $20 buyer on InstantAdPay pays you 50 percent. Your second opens level 2: 20 percent of everything their people buy.', 'InstantAdPay packages are bought with POL and pay your sponsor on the spot, on chain. Nothing to withdraw, nothing to wait for.', + 'Share your Drip Runner link from the lobby. When the people you bring in refuel, ' + (Number(settings.refSharePct) || 0) + ' percent of what each refuel adds to the pool goes to your game balance.', ]; if (p20) tips.push('A $20 InstantAdPay package is about ' + fmt(p20.pol) + ' POL today. Half of it goes to the sponsor, on chain, the moment it is bought.'); if (p5) tips.push('$5 on InstantAdPay is ' + fmt(p5.credits) + ' credits, about ' + fmt(p5.pol) + ' POL today. That runs ' + Math.floor(p5.credits / RATES.visitCost) + ' verified visits to your own page.'); diff --git a/public/admin.html b/public/admin.html index 279ece5..52ec065 100644 --- a/public/admin.html +++ b/public/admin.html @@ -26,6 +26,7 @@
+
diff --git a/public/admin.js b/public/admin.js index 960785a..d19c737 100644 --- a/public/admin.js +++ b/public/admin.js @@ -20,7 +20,7 @@ function load() { $('pool').innerHTML = stat('Available now', f4(p.available) + ' POL') + stat('In from refuels', f4(p.in)) + stat('Back from spends', f4(p.spends)) + stat('Out as drips', f4(p.out)) + stat('Seed float', f4(p.seed)) + stat('Granted today', f4(p.grantedToday) + ' / ' + f4(p.dailyCapPol)); var f = d.faucet; $('faucet').innerHTML = stat('Mode', f.enabled ? (f.dryRun ? 'DRY RUN' : 'LIVE') : 'off') + stat('Wallet', f.address ? f.address.slice(0, 8) + '…' + f.address.slice(-6) : '–') + stat('Balance', f.balance != null ? f4(f.balance) + ' POL' : '–') + stat('Last check', ct(f.checkedAt) || '–') + stat('Last tick', f.lastTick ? esc(JSON.stringify(f.lastTick)) : '–'); var s = d.settings, form = $('settings'); - ['dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { form.elements[k].value = s[k]; }); + ['refSharePct', 'dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { form.elements[k].value = s[k]; }); form.elements.item_shield.value = s.itemPol.shield; form.elements.item_slow.value = s.itemPol.slow; form.elements.item_magnet.value = s.itemDrips.magnet; form.elements.item_ship.value = s.itemDrips.ship; form.elements.testers.value = (s.testers || []).join('\n'); form.elements.trial.value = s.trial === false ? 'off' : 'on'; table('players', [['Member', function (r) { return '#' + r.memberId + (r.username ? ' @' + esc(r.username) : '') + '
' + esc(r.email || '') + ''; }], ['Wallet', function (r) { return r.wallet ? r.wallet.slice(0, 6) + '…' + r.wallet.slice(-4) : 'none'; }], ['Chapter', 'chapter', 1], ['Drips', 'bank', 1], ['Best', 'best', 1], ['Runs', 'runs', 1], ['Armed', function (r) { return Object.keys(r.items || {}).join(', '); }], ['Last seen', function (r) { return ct(r.lastSeen); }]], d.players); @@ -33,7 +33,7 @@ function load() { } $('settings').addEventListener('submit', function (e) { e.preventDefault(); var f = e.target.elements; var body = {}; - ['dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { body[k] = f[k].value; }); + ['refSharePct', 'dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { body[k] = f[k].value; }); body.itemPol = { shield: Number(f.item_shield.value), slow: Number(f.item_slow.value) }; body.itemDrips = { magnet: Number(f.item_magnet.value), ship: Number(f.item_ship.value) }; body.trial = f.trial.value; body.testers = f.testers.value.split(/\r?\n/).map(function (x) { return x.trim(); }).filter(Boolean); api('/api/admin/settings', body).then(function (r) { $('saveOut').textContent = r.ok ? 'Saved.' : (r.error || 'Failed'); load(); }); diff --git a/public/play.html b/public/play.html index d95f033..d485e4b 100644 --- a/public/play.html +++ b/public/play.html @@ -5,6 +5,10 @@ Drip Runner + + + +