Files
drip-runner/server.js
T

274 lines
27 KiB
JavaScript

// Drip Runner: a hop-and-collect game for InstantAdPay members, paid in POL, funded by the
// verified visits players make to refuel. Trial build (2026-09-30).
//
// Gates, all default-deny, all from the environment:
// CURTAIN=<secret> the tester page at / shows "Coming soon" to anyone without ?k=<secret>
// OUTBOUND=on required before anything leaves this server (Telegram to Marty). No mailer exists.
// DR_SSO_SECRET shared with InstantAdPay: hand-off tokens, refuel tokens, receipts, callbacks
// ADMIN_KEY the admin page and API
// IAP_URL https://instantadpay.com (where refuel visits happen)
// SITE_URL this app's public URL
// DR_WALLET_KEY / DR_RPC / DR_CHAIN_ID / DR_DRY_RUN the faucet (lib/faucet.js)
// DR_TG_TOKEN / DR_TG_CHAT Marty's private alerts (payouts, failures, low balance)
// Who may sign in is a setting (admin page): 'testers' (allowlist), 'open', 'closed'.
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const store = require('./lib/store');
const sso = require('./lib/sso');
const game = require('./lib/game');
const ledger = require('./lib/ledger');
const faucet = require('./lib/faucet');
const spawn = require('./lib/spawn');
const badge = require('./lib/badge');
const tips = require('./lib/tips'); // facts you learn as you play, priced from the live IAP catalog
const PORT = Number(process.env.PORT || 3000);
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const PUBLIC_DIR = path.join(__dirname, 'public');
const CURTAIN = String(process.env.CURTAIN || '').trim();
const ADMIN_KEY = String(process.env.ADMIN_KEY || '').trim();
const SITE = String(process.env.SITE_URL || 'https://driprunner.saasy.top').replace(/\/+$/, '');
const IAP = String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
const SECRET = String(process.env.DR_SSO_SECRET || '').trim();
const outbound = () => process.env.OUTBOUND === 'on';
const IS_PROD = process.env.NODE_ENV === 'production';
store.init(DATA_DIR);
badge.init({ publicDir: PUBLIC_DIR, dataDir: DATA_DIR });
const faucetOn = faucet.init();
// ---- Telegram to Marty (outward: gated) -------------------------------------------------------
async function telegram(text) {
if (!outbound()) return false;
const tok = process.env.DR_TG_TOKEN, chat = process.env.DR_TG_CHAT; if (!tok || !chat) return false;
try { const r = await fetch('https://api.telegram.org/bot' + tok + '/sendMessage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chat_id: chat, text, parse_mode: 'HTML', disable_web_page_preview: true }) }); return r.ok; } catch (e) { return false; }
}
const fmt = n => Number(n).toLocaleString('en-US', { maximumFractionDigits: 4 });
// ---- public badge posts (Marty, 2026-09-30): unlocks, chapter and refuel milestones, payouts, as photo cards ----
// DR_TG_PUBLIC_CHAT / DR_TG_PUBLIC_TOPIC = the room (PolHunter's), DR_TG_PUBLIC_GENERAL=on also posts the photo to the general channel.
async function telegramPhoto(file, caption, general) {
if (!outbound()) return false;
const tok = process.env.DR_TG_TOKEN, chat = process.env.DR_TG_PUBLIC_CHAT || process.env.DR_TG_CHAT, topic = process.env.DR_TG_PUBLIC_CHAT ? process.env.DR_TG_PUBLIC_TOPIC : null;
if (!tok || !chat || !file) return false;
try {
const fd = new FormData(); fd.append('chat_id', chat); fd.append('caption', caption); fd.append('parse_mode', 'HTML'); if (topic && !general) fd.append('message_thread_id', String(topic));
fd.append('photo', new Blob([fs.readFileSync(file)], { type: 'image/jpeg' }), 'badge.jpg');
const r = await fetch('https://api.telegram.org/bot' + tok + '/sendPhoto', { method: 'POST', body: fd }); return r.ok;
} catch (e) { return false; }
}
const nameOf = me => me.username ? '@' + me.username : '#' + me.memberId;
const trial = () => ledger.settings().trial !== false; // Marty, 2026-09-30: while testing, say so, and show what they WOULD have earned once live
function earningsLine(memberId) {
const a = ledger.account(memberId); const p = game.player(memberId) || {}; const refuels = store.read('refuels', []).filter(r => r.memberId === Number(memberId)).length;
return (trial() ? 'would have earned ' : 'earned ') + fmt(a.earnedTotal || 0) + ' POL so far \u00b7 ' + refuels + ' refuel' + (refuels === 1 ? '' : 's') + ' \u00b7 chapter ' + (p.chapter || 1);
}
// one post per (member, badge); a payout card is one per payout row
async function announce(id, me, opts) {
opts = opts || {}; const key = opts.key || id;
const posted = store.read('posted', {}); const mine = new Set(posted[String(me.memberId)] || []);
if (mine.has(key)) return false;
store.update('posted', {}, all => { all[String(me.memberId)] = [...mine, key]; return all; });
const line2 = opts.line2 || earningsLine(me.memberId);
const file = await badge.render(id, nameOf(me), line2, trial() ? 'COMING SOON \u00b7 NOW IN TESTING' : '');
const head = trial() ? opts.caption.replace('<b>Drip Runner</b>', '<b>Drip Runner</b> <i>(coming soon \u00b7 now in testing)</i>') : opts.caption;
const foot = trial() ? '<i>Testers are playing a preview. When Drip Runner goes live, amounts like this pay out in POL to the wallet on your InstantAdPay account.</i>' : '<i>Play from your InstantAdPay dashboard.</i>';
const cap = head + '\n' + line2 + '\n' + foot;
if (!file) return telegram(cap);
const ok = await telegramPhoto(file, cap);
if (ok && String(process.env.DR_TG_PUBLIC_GENERAL || 'off') === 'on') await telegramPhoto(file, cap, true);
return ok;
}
const ITEM_NAMES = { magnet: 'Drip Magnet', ship: 'Courier Mk II', shield: 'Shield Core', slow: 'Slow Field' };
function announceUnlock(me, item, paid) { if (!badge.BADGES[item]) return; announce(item, me, { caption: '\u{1F3AE} <b>Drip Runner</b> \u00b7 <b>' + nameOf(me) + '</b> unlocked the <b>' + ITEM_NAMES[item] + '</b> (' + paid + ')' }).catch(() => {}); }
function announceChapter(me, ch, pol) { const id = badge.CHAPTER_BADGES[ch]; if (!id) return; announce(id, me, { caption: '\u{1F3C1} <b>Drip Runner</b> \u00b7 <b>' + nameOf(me) + '</b> cleared <b>Chapter ' + ch + '</b>' + (pol ? ' \u00b7 <b>+' + fmt(pol) + ' POL</b>' : '') }).catch(() => {}); }
function announceRefuels(me) { const n = store.read('refuels', []).filter(r => r.memberId === Number(me.memberId)).length; const id = badge.REFUEL_BADGES[n]; if (!id) return; announce(id, me, { caption: '\u26FD <b>Drip Runner</b> \u00b7 <b>' + nameOf(me) + '</b> has refuelled <b>' + n + ' times</b>. Every refuel is a verified visit to a member\u2019s page on InstantAdPay.' }).catch(() => {}); }
function announcePaid(p) { announce('paid', { memberId: p.memberId, username: p.username }, { key: 'paid:' + p.id, caption: '\u{1F4B8} <b>Drip Runner</b> \u00b7 <b>' + nameOf(p) + '</b> was paid <b>' + fmt(p.pol) + ' POL</b> \u00b7 <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>', line2: 'paid ' + fmt(p.pol) + ' POL to their wallet \u00b7 ' + earningsLine(p.memberId).replace(/^earned [^\u00b7]+\u00b7 /, '') }).catch(() => {}); }
const explorer = () => Number(process.env.DR_CHAIN_ID) === 80002 ? 'https://amoy.polygonscan.com' : 'https://polygonscan.com';
async function notify(kind, p) {
const who = p && (p.username ? '@' + p.username : '#' + p.memberId);
if (kind === 'paid') { announcePaid(p); return telegram('\u{1F3AE} <b>Drip Runner</b> · paid ' + who + ' <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>'); }
if (kind === 'failed') return telegram('❌ <b>Drip Runner</b> · payout to ' + who + ' failed: ' + p.error);
if (kind === 'low') return telegram('⚠️ <b>Drip Runner wallet is low</b>: ' + fmt(p.balance) + ' POL in ' + p.address + ' (needs ' + fmt(p.threshold) + ').');
if (kind === 'refused') return telegram('\u{1F6AB} <b>Drip Runner</b> \u00b7 ' + who + ' (' + p.email + ') tried to sign in but is not on the tester list. Add them under Admin > Settings > Testers: ' + SITE + '/admin');
if (kind === 'signin') return telegram('\u{1F44B} <b>Drip Runner</b> · first sign-in: ' + who + ' (' + (p.wallet ? 'wallet on file' : 'NO wallet yet') + ')');
if (kind === 'refuel') return telegram('⛽ <b>Drip Runner</b> · ' + who + ' refuelled on campaign #' + p.campaignId + ': +' + fmt(p.pol) + ' POL to the pool (' + p.credits + ' credits, $' + p.share + ' share)');
return false;
}
// ---- helpers ---------------------------------------------------------------------------------
const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.webp': 'image/webp', '.mp4': 'video/mp4' };
const CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; form-action 'self'";
const SEC = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'X-Frame-Options': 'DENY', 'Content-Security-Policy': CSP };
function json(res, code, body, extra) { res.writeHead(code, Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, SEC, extra || {})); res.end(JSON.stringify(body)); }
function sendFile(res, file, extra) {
fs.readFile(file, (err, buf) => {
if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
res.writeHead(200, Object.assign({ 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store' }, SEC, extra || {}));
res.end(buf);
});
}
function page(res, code, title, body, extra) {
res.writeHead(code, Object.assign({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }, SEC, extra || {}));
res.end('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>' + title + '</title><link rel="stylesheet" href="/site.css"></head><body class="plain"><main class="card"><h1>' + title + '</h1>' + body + '</main></body></html>');
}
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
function readBody(req) {
return new Promise(resolve => { let d = ''; req.on('data', c => { d += c; if (d.length > 200000) req.destroy(); }); req.on('end', () => { let j = {}; try { j = JSON.parse(d || '{}'); } catch (e) {} resolve({ raw: d, body: j }); }); });
}
const CURTAIN_PAGE = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>Coming soon</title><style>*{margin:0;padding:0;box-sizing:border-box}html,body{height:100%}body{display:flex;align-items:center;justify-content:center;padding:24px;background:#050912;color:#e6edf3;font:16px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif}.card{max-width:420px;text-align:center}h1{font-size:clamp(28px,7vw,44px);font-weight:700;margin-bottom:14px}p{color:#8b949e}</style></head><body><div class="card"><h1>Coming soon</h1><p>This site is still being built.</p></div></body></html>';
function curtained(req, res, u) {
if (!CURTAIN) return false;
if (u.searchParams.get('k') === CURTAIN) { u.searchParams.delete('k'); res.writeHead(302, { 'Set-Cookie': 'dr.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : ''), Location: u.pathname + (u.searchParams.toString() ? '?' + u.searchParams : ''), 'Cache-Control': 'no-store' }); res.end(); return true; }
const m = /(?:^|;\s*)dr\.pass=([^;]+)/.exec(req.headers.cookie || '');
if (m && decodeURIComponent(m[1]) === CURTAIN) return false;
res.writeHead(503, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' }); res.end(req.method === 'HEAD' ? '' : CURTAIN_PAGE); return true;
}
function admin(req, u) { const k = req.headers['x-admin-key'] || u.searchParams.get('key'); return !!(ADMIN_KEY && k && k.length === ADMIN_KEY.length && crypto.timingSafeEqual(Buffer.from(k), Buffer.from(ADMIN_KEY))); }
// who may come through the hand-off
// 'key' (Marty, 2026-09-30: "let anyone I send the link to with the key test"): the hand-off is accepted when the
// browser carries the curtain pass, i.e. the person opened the tester link with the key first. The list still works too.
function hasPass(req) { const m = /(?:^|;\s*)dr\.pass=([^;]+)/.exec(req.headers.cookie || ''); return !!(CURTAIN && m && decodeURIComponent(m[1]) === CURTAIN); }
function allowed(claims, req) {
const s = ledger.settings(); const mode = String(process.env.DR_SIGNUPS || s.signups || 'testers');
if (mode === 'open') return true; if (mode === 'closed') return false;
const list = (s.testers || []).map(x => String(x).trim().toLowerCase()).filter(Boolean);
if (list.includes(String(claims.email || '').toLowerCase()) || list.includes(String(claims.memberId)) || (claims.username && list.includes(String(claims.username).toLowerCase()))) return true; // email, member id or IAP username
return mode === 'key' && req && hasPass(req);
}
// the IAP -> game callback is signed over the timestamp and the raw body with the shared secret
function callbackOk(req, raw) {
const ts = String(req.headers['x-dr-ts'] || ''), sig = String(req.headers['x-dr-sig'] || '');
if (!SECRET || !ts || !sig || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return false;
const want = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex');
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
}
const intents = { get: n => store.read('refuel-intents', {})[n] || null, set: (n, v) => store.update('refuel-intents', {}, all => { const cut = Date.now() - 86400000; for (const k of Object.keys(all)) if (all[k].ts < cut) delete all[k]; all[n] = v; return all; }), upd: (n, fn) => store.update('refuel-intents', {}, all => { if (all[n]) fn(all[n]); return all; })[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));
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);
}
// ---- server ------------------------------------------------------------------------------------
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://x'); const p = u.pathname;
try {
if (p === '/health') return json(res, 200, { ok: true, outbound: outbound(), curtain: !!CURTAIN, sso: sso.enabled(), faucet: faucetOn, dryRun: faucet.dry(), chain: Number(process.env.DR_CHAIN_ID) || null, signups: String(process.env.DR_SIGNUPS || ledger.settings().signups) });
// ---- sign-in by hand-off (passes the curtain: the member already came through IAP) ----
if (p === '/auth') {
const r = sso.verify(u.searchParams.get('t'));
if (r.error) return page(res, 400, 'Sign-in did not work', '<p>' + esc(r.error) + '</p><p><a class="btn" href="' + IAP + '/api/my/driprunner">Try again from InstantAdPay</a></p>');
if (!allowed(r.claims, req)) { console.log('hand-off refused: not a tester', r.claims.memberId, r.claims.username || '', String(r.claims.email || '').replace(/^(.).*(@.*)$/, '$1***$2')); notify('refused', { memberId: r.claims.memberId, username: r.claims.username, email: r.claims.email }).catch(() => {}); }
if (!allowed(r.claims, req)) { const keyMode = String(process.env.DR_SIGNUPS || ledger.settings().signups) === 'key'; return page(res, 403, keyMode ? 'Open the tester link first' : 'Not on the tester list yet', keyMode ? '<p>Drip Runner is in a closed trial. Open the tester link Marty sent you (the one with the key) in this same browser, then tap Open Drip Runner again. Your InstantAdPay account is ' + esc(r.claims.username ? '@' + r.claims.username : '#' + r.claims.memberId) + '.</p>' : '<p>Drip Runner is in a closed trial. Your InstantAdPay account (' + esc(r.claims.username ? '@' + r.claims.username : '#' + r.claims.memberId) + ') is not on the tester list. Ask Marty to add you.</p>'); }
const existing = sso.fromRequest(req);
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);
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();
}
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) ----
if (p === '/api/refuel/callback' && req.method === 'POST') {
const { raw, body } = await readBody(req);
if (!callbackOk(req, raw)) return json(res, 401, { error: 'bad signature' });
const it = intents.get(String(body.nonce || ''));
if (!it) return json(res, 404, { error: 'unknown refuel' });
if (Number(body.memberId) !== it.memberId) return json(res, 400, { error: 'member mismatch' });
const out = await creditRefuel(it, String(body.nonce), { campaignId: body.campaignId, credits: body.credits, via: 'callback' });
return json(res, 200, { ok: true, pol: out.pol });
}
// ---- static + pages ----
if (p === '/' || p === '/index.html') { if (curtained(req, res, u)) return; return sendFile(res, path.join(PUBLIC_DIR, 'index.html')); }
if (p === '/play') return sendFile(res, path.join(PUBLIC_DIR, 'play.html'));
if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html')); // the page asks for the key; every /api/admin call checks it
if (p === '/spawn.js') return sendFile(res, path.join(__dirname, 'lib', 'spawn.js'));
if (/^\/[a-z0-9._-]+\.(css|js|png|jpg|svg|ico|webp|mp4)$/i.test(p) && !p.includes('..')) return sendFile(res, path.join(PUBLIC_DIR, p.slice(1)));
// ---- member API ----
if (p.startsWith('/api/')) {
const me = sso.fromRequest(req);
if (p.startsWith('/api/admin/')) {
if (!admin(req, u)) return json(res, 403, { error: 'admin key' });
if (p === '/api/admin/state' && req.method === 'GET') {
const accounts = store.read('accounts', {}); const players = store.read('players', {});
return json(res, 200, { settings: ledger.settings(), pool: ledger.pool(), usdPerPol: await ledger.usdPerPol(), faucet: faucet.state(),
refuels: store.read('refuels', []).slice(-100).reverse(), drips: store.read('drips', []).slice(-100).reverse(), spends: store.read('spends', []).slice(-100).reverse(), payouts: store.read('payouts', []).slice(-100).reverse(),
accounts: Object.values(accounts), players: Object.values(players).map(x => ({ memberId: x.memberId, username: x.username, email: x.email, wallet: x.wallet, chapter: x.chapter, bank: x.bank, best: x.best, runs: x.runs, lastSeen: x.lastSeen, items: x.items })), runs: game.recent(60), site: SITE, iap: IAP, curtain: CURTAIN ? SITE + '/?k=' + CURTAIN : SITE });
}
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]);
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);
if (body.itemPol && typeof body.itemPol === 'object') patch.itemPol = Object.assign({}, ledger.settings().itemPol, body.itemPol);
if (body.itemDrips && typeof body.itemDrips === 'object') patch.itemDrips = Object.assign({}, ledger.settings().itemDrips, body.itemDrips);
return json(res, 200, { ok: true, settings: ledger.setSettings(patch) });
}
if (p === '/api/admin/faucet/tick' && req.method === 'POST') return json(res, 200, await faucet.tick(notify));
if (p === '/api/admin/announce' && req.method === 'POST') { // post (or re-post with force) a badge for a member: {memberId, id}
const { body } = await readBody(req); const pl = game.player(Number(body.memberId)); if (!pl) return json(res, 404, { error: 'no such player' });
const me = { memberId: pl.memberId, username: pl.username }; const id = String(body.id || '');
if (body.force) store.update('posted', {}, all => { all[String(pl.memberId)] = (all[String(pl.memberId)] || []).filter(k => k !== id); return all; });
const ch = Object.keys(badge.CHAPTER_BADGES).find(k => badge.CHAPTER_BADGES[k] === id);
if (ch) { announceChapter(me, Number(ch), 0); return json(res, 200, { ok: true, kind: 'chapter' }); }
if (ITEM_NAMES[id]) { announceUnlock(me, id, 'hangar'); return json(res, 200, { ok: true, kind: 'unlock' }); }
return json(res, 400, { error: 'unknown badge id' });
}
if (p === '/api/admin/handoff' && req.method === 'POST') { // a test token for a synthetic member (local checks only)
const { body } = await readBody(req); return json(res, 200, { url: SITE + '/auth?t=' + sso.mint({ memberId: Number(body.memberId) || 999001, email: body.email || 'tester@example.com', wallet: body.wallet || null, username: body.username || 'tester' }) });
}
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/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()) });
}
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/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 (!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 });
const tok = sso.mint({ kind: 'refuel', memberId: me.memberId, email: me.email, username: me.username, nonce, ret }, 15 * 60000);
return json(res, 200, { url: IAP + '/refuel?t=' + tok, nonce });
}
if (p === '/api/refuel/resume' && req.method === 'POST') {
const { body } = await readBody(req); const nonce = String(body.nonce || ''); let it = intents.get(nonce);
if (!it || it.memberId !== me.memberId || it.runId !== String(body.runId || '')) return json(res, 400, { error: 'That refuel does not match this run.' });
if (it.consumed) return json(res, 400, { error: 'That refuel was already used.' });
// the browser may carry IAP's signed receipt: it counts even when the server callback was slow
if (!it.done && body.receipt) { const rc = sso.open(body.receipt); if (rc.ok && rc.claims.kind === 'refuel-receipt' && rc.claims.nonce === nonce) it = await creditRefuel(it, nonce, { campaignId: rc.claims.campaignId, credits: rc.claims.credits, via: 'receipt' }); }
if (!it.done) return json(res, 200, { ok: false, reason: body.none ? 'none' : 'unverified' });
intents.upd(nonce, x => { x.consumed = true; }); game.refuelled(me, it.runId); announceRefuels(me);
return json(res, 200, { ok: true, pool: ledger.pool().available });
}
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); }