// 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= the tester page at / shows "Coming soon" to anyone without ?k= // 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 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); 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 }); 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') return telegram('\u{1F3AE} Drip Runner · paid ' + who + ' ' + fmt(p.pol) + ' POL · verify'); if (kind === 'failed') return telegram('❌ Drip Runner · payout to ' + who + ' failed: ' + p.error); if (kind === 'low') return telegram('⚠️ Drip Runner wallet is low: ' + fmt(p.balance) + ' POL in ' + p.address + ' (needs ' + fmt(p.threshold) + ').'); if (kind === 'refused') return telegram('\u{1F6AB} Drip Runner \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} Drip Runner · first sign-in: ' + who + ' (' + (p.wallet ? 'wallet on file' : 'NO wallet yet') + ')'); if (kind === 'refuel') return telegram('⛽ Drip Runner · ' + 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('' + title + '

' + title + '

' + body + '
'); } const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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 = 'Coming soon

Coming soon

This site is still being built.

'; 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', '

' + esc(r.error) + '

Try again from InstantAdPay

'); 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 ? '

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) + '.

' : '

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.

'); } 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 (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/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 }); } 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; 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); return json(res, 200, { ok: true, pool: ledger.pool().available }); } if (p === '/api/hangar/buy' && req.method === 'POST') { const { body } = await readBody(req); const r = game.buy(me, String(body.item || '')); if (!r.error) { r.player = game.view(me); r.balance = ledger.balance(me.memberId); } 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); }