// 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 badge = require('./lib/badge'); const srctrack = require('./lib/srctrack'); // paid-traffic sources (2026-10-03) const tips = require('./lib/tips'); // facts you learn as you play, priced from the live IAP catalog const starter = require('./lib/starter'); // member welcome offer + the member perk (2026-10-05) 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, topicOverride) { 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 ? (topicOverride || 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('Drip Runner', 'Drip Runner (coming soon \u00b7 now in testing)') : opts.caption; const foot = trial() ? 'Testers are playing a preview. When Drip Runner goes live, amounts like this pay out in POL to the wallet on your InstantAdPay account.' : 'Play from your InstantAdPay dashboard.'; const cap = head + '\n' + line2 + '\n' + foot; if (!file) return telegram(cap); const ok = await telegramPhoto(file, cap, false, opts.topic); if (ok && String(process.env.DR_TG_PUBLIC_GENERAL || 'off') === 'on') await telegramPhoto(file, cap, true); return ok; } // badges and milestones = the achievements topic (Marty, 2026-10-01); payout cards keep DR_TG_PUBLIC_TOPIC const ACH = () => process.env.DR_TG_ACH_TOPIC || ''; 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} Drip Runner \u00b7 ' + nameOf(me) + ' unlocked the ' + ITEM_NAMES[item] + ' (' + paid + ')', topic: ACH() }).catch(() => {}); } function announceChapter(me, ch, pol) { const id = badge.CHAPTER_BADGES[ch]; if (!id) return; announce(id, me, { caption: '\u{1F3C1} Drip Runner \u00b7 ' + nameOf(me) + ' cleared Chapter ' + ch + '' + (pol ? ' \u00b7 +' + fmt(pol) + ' POL' : ''), topic: ACH() }).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 Drip Runner \u00b7 ' + nameOf(me) + ' has refuelled ' + n + ' times. Every refuel is a verified visit to a member\u2019s page on InstantAdPay.', topic: ACH() }).catch(() => {}); } function announcePaid(p) { announce('paid', { memberId: p.memberId, username: p.username }, { key: 'paid:' + p.id, caption: '\u{1F4B8} Drip Runner \u00b7 ' + nameOf(p) + ' was paid ' + fmt(p.pol) + ' POL \u00b7 verify', 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} 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' }; // instantadpay.com: the in-game sign-in kit (script), its API (connect) and the signed-in nudge form (form-action), 2026-10-03 const CSP = "default-src 'self'; script-src 'self' " + IAP + "; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self' " + IAP + "; form-action 'self' " + IAP; const SEC = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'Content-Security-Policy': CSP }; // frames: see the request handler 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 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); } // ---- server ------------------------------------------------------------------------------------ const server = http.createServer(async (req, res) => { const u = new URL(req.url, 'http://x'); const p = u.pathname; // frames (2026-10-03): public pages show inside traffic exchanges; admin and the sign-in hand-offs never do. A framed // visit to the game itself lands on the landing page, whose buttons open the game in a new tab (cookies die in frames) if (/^\/(admin|auth|signin|logout)(\/|$)/.test(p) || p.startsWith('/api/admin')) res.setHeader('X-Frame-Options', 'DENY'); if (req.headers['sec-fetch-dest'] === 'iframe' && req.method === 'GET') { const fr = /^\/r\/([A-Za-z0-9_.-]{1,40})$/.exec(p); if (fr || p === '/play' || p === '/signin') { res.writeHead(302, { Location: '/' + (fr ? '?r=' + encodeURIComponent(fr[1]) : (u.search || '')), 'Cache-Control': 'no-store' }); return res.end(); } } // one home address (2026-10-01): pages on any other host we answer for (driprunner.saasy.top, www.) move to SITE_URL with the // path and query intact, so key links keep working and a refuel never returns to a different origin than the run started on. // The API, the IAP callback, health and the badge art answer on every host. { const host = String(req.headers.host || '').toLowerCase().split(':')[0]; const home = SITE.replace(/^https?:\/\//, '').toLowerCase(); if (IS_PROD && host && host !== home && req.method === 'GET' && !p.startsWith('/api/') && p !== '/health' && !p.startsWith('/badges/')) { res.writeHead(301, { Location: SITE + req.url, 'Cache-Control': 'no-store' }); return res.end(); } } 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

'); 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); // 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(); }); 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; }); starter.grantPerk(r.claims.memberId); // a member (memberId > 0) gets one free hangar upgrade, once per account (2026-10-05) 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 { const t = srctrack.fromRequest(req); if (t) { srctrack.bump(t.src, 'signins', r.claims.memberId); game.updPlayer(r.claims.memberId, x => { if (!x.src) x.src = t.src; }); if (r.claims.joinedAt && Date.now() - Number(r.claims.joinedAt) < 30 * 60000) { srctrack.bump(t.src, 'signups', r.claims.memberId); srctrack.postback(t, r.claims.memberId).catch(() => {}); } } } 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(); } // a member's share card (2026-10-04, Neville/cryptoassets: his link previewed as the blank First Chapter badge): the badge with // the sharer's name on the plate, rendered once and cached by lib/badge.js { const mc = /^\/r\/([A-Za-z0-9_.-]{1,40})\/card\.jpg$/.exec(p); if (mc) { const sharer = game.byUsername(mc[1]); if (!sharer) return sendFile(res, path.join(PUBLIC_DIR, 'og-driprunner.jpg')); const f = await badge.render('ch1', '@' + sharer.username, 'invites you to play Drip Runner', 'PLAY FREE \u00b7 EARN POL'); if (!f) return sendFile(res, path.join(PUBLIC_DIR, 'og-driprunner.jpg')); res.writeHead(200, Object.assign({ 'Content-Type': 'image/jpeg', 'Cache-Control': 'public, max-age=86400' }, SEC)); return fs.createReadStream(f).pipe(res); } } { const mr = /^\/r\/([A-Za-z0-9_.-]{1,40})$/.exec(p); // link-preview robots (Telegram, Facebook, X, WhatsApp...) get the sharer's own card; people get the game, as before if (mr && /TelegramBot|facebookexternalhit|Facebot|Twitterbot|WhatsApp|Slackbot|Discordbot|LinkedInBot|SkypeUriPreview|redditbot|Iframely|Embedly|vkShare|Pinterest|Googlebot|bingbot/i.test(String(req.headers['user-agent'] || ''))) { const sh = game.byUsername(mr[1]); const nm = sh ? sh.username : null; const card = SITE + '/r/' + encodeURIComponent(mr[1]) + '/card.jpg'; const t = nm ? '@' + nm + ' invited you to Drip Runner' : 'Drip Runner: hop the network, get paid in POL'; const d = 'A fast little runner game in the InstantAdPay network. Play free, clear chapters and collect POL rewards.'; res.writeHead(200, Object.assign({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }, SEC)); return res.end('' + esc(t) + 'Play Drip Runner'); } } { const mr = /^\/r\/([A-Za-z0-9_.-]{1,40})$/.exec(p); if (mr) { const sharer = game.byUsername(mr[1]); // not a Drip Runner player (yet), but maybe an InstantAdPay member: the landing keeps the name as ?ref (2026-10-05), and // InstantAdPay decides whether it is a real sponsor when the visitor signs up if (!sharer) { res.writeHead(302, { Location: '/?ref=' + encodeURIComponent(mr[1].toLowerCase()), 'Cache-Control': 'no-store' }); return res.end(); } const ck = [refCookieHeader(sharer.username.toLowerCase())]; 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) ---- 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 ---- // a paid-traffic landing (?src=adsterra&cid=): remember it (dr.src) and count the visit (2026-10-03) let srcHdr = null; if (req.method === 'GET' && ['/', '/index.html', '/play', '/signin'].includes(p)) { const ck = []; const t = srctrack.fromQuery(u); if (t) { ck.push(srctrack.cookieHeader(t, IS_PROD)); srctrack.bump(t.src, 'visits'); } // ?ref= on the landing, the game or sign-in (2026-10-05, the IAP viral-link pattern): the same sponsor cookie as /r/, // last touch wins. ?r= too on the landing only (the framed /r/ lands on /?r=); on /play, r is the refuel receipt. const rq = queryRef(u, p === '/' || p === '/index.html'); if (rq) ck.push(refCookieHeader(rq)); if (ck.length) srcHdr = { 'Set-Cookie': ck }; } if (p === '/' || p === '/index.html') { if (curtained(req, res, u)) return; return sendFile(res, path.join(PUBLIC_DIR, 'index.html'), srcHdr); } if (p === '/testers') { if (curtained(req, res, u)) return; return sendFile(res, path.join(PUBLIC_DIR, 'testers.html')); } // the pre-launch briefing if (p === '/play') return sendFile(res, path.join(PUBLIC_DIR, 'play.html'), srcHdr); if (p === '/signin') return sendFile(res, path.join(PUBLIC_DIR, 'signin.html'), srcHdr); // in-game sign-in (InstantAdPay kit) 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 (/^\/(badges\/)?[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)), p.startsWith('/badges/') ? { 'Cache-Control': 'public, max-age=86400', 'Access-Control-Allow-Origin': '*' } : undefined); // badge art is also shown on InstantAdPay and in link previews // ---- member API ---- if (p.startsWith('/api/')) { // the landing page's live numbers (public, no personal data) // the last 24 hours for the shared 6 PM games summary in the achievements topic (counts only, no POL amounts) if (p === '/api/public/today' && req.method === 'GET') { const since = Date.now() - 24 * 3600000, t = v => typeof v === 'number' ? v : Date.parse(v) || 0; const refuels = store.read('refuels', []).filter(x => t(x.ts) >= since), clears = store.read('drips', []).filter(x => t(x.ts) >= since); const players = Object.values(store.read('players', {})).filter(x => x.memberId > 0); return json(res, 200, { refuels: refuels.length, clears: clears.length, runners: new Set([...refuels, ...clears].map(x => x.memberId)).size, newRunners: players.filter(x => t(x.since) >= since).length }); } if (p === '/api/public/stats' && req.method === 'GET') { const players = Object.values(store.read('players', {})).filter(x => x.memberId > 0).length; const paid = store.read('payouts', []).filter(x => x.status === 'paid'); return json(res, 200, { players, refuels: store.read('refuels', []).length, chapterDrips: store.read('drips', []).length, polPaid: Math.round(paid.reduce((n, x) => n + x.pol, 0) * 10000) / 10000, payouts: paid.length, dripPol: Number(ledger.settings().dripPol), thresholdPol: Number(ledger.settings().thresholdPol), refSharePct: Number(ledger.settings().refSharePct) || 0 }); } // IAP's Games page asks for a player's line on the card: signed with the shared secret, read only (2026-10-01) if (p === '/api/partner/player' && req.method === 'GET') { const m = Number(u.searchParams.get('m')), ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || ''); if (!SECRET || !m || !ts || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return json(res, 401, { error: 'bad request' }); const want = crypto.createHmac('sha256', SECRET).update('player:' + m + ':' + ts).digest('hex'); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' }); const pl = game.player(m); if (!pl) return json(res, 200, { played: false }); const b = ledger.balance(m); return json(res, 200, { played: true, chapter: pl.chapter, best: pl.best, unpaid: b.unpaid, paidTotal: b.paidTotal, earnedTotal: b.earnedTotal }); } 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, perkAt: x.perkAt || null, freeUpgrades: Number(x.freeUpgrades) || 0 })), 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 ['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); 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/srcstats' && req.method === 'GET') return json(res, 200, srctrack.summary(Number(u.searchParams.get('days')) || 30)); 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', joinedAt: body.joinedAt || null }) }); } return json(res, 404, { error: 'no such admin route' }); } 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)); { const t = srctrack.fromRequest(req); if (t) srctrack.bump(t.src, 'guests', g.memberId); } 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 with your InstantAdPay account first.', iap: '/signin', 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.' }); } }); // the sponsor cookie (read by signin.js and handed to the InstantAdPay sign-in kit as ref; not HttpOnly on purpose) function refCookieHeader(ref) { return 'dr.ref=' + encodeURIComponent(ref) + '; Path=/; Max-Age=' + 30 * 86400 + '; SameSite=Lax' + (IS_PROD ? '; Secure' : ''); } function queryRef(u, allowR) { const r = String(u.searchParams.get('ref') || (allowR ? u.searchParams.get('r') : '') || '').trim().replace(/^@/, ''); return /^[A-Za-z0-9_.-]{1,40}$/.test(r) ? r.toLowerCase() : null; } 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) { return '/signin'; } // in-game sign-in (2026-10-03); the kit carries the dr.ref sponsor itself async function memberApi(req, res, u, p, me) { try { { if (p === '/api/me' && req.method === 'GET') { const pl = ledger.pool(); 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 }, perk: me.guest ? null : starter.takeNotice(me.memberId) }); // the member perk's one-time message (2026-10-05) } 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 t = srctrack.fromRequest(req); if (t) srctrack.bump(t.src, 'runs', me.memberId); } 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 }); } // a chapter clear may carry the member welcome offer: after a win only, once a Central day, signed-in non-members (lib/starter.js) 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); const so = await starter.offerFor(me); if (so) r.starterOffer = so; } 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 }); 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' }); } } 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); }