From 9a3ba1e497a9e746ad3b6e6000441293876d53aa Mon Sep 17 00:00:00 2001 From: martbost Date: Thu, 1 Oct 2026 20:29:02 -0500 Subject: [PATCH] Badge and milestone cards post to the CTB Game Achievements topic (DR_TG_ACH_TOPIC); payout cards stay in the payments topic. /api/public/today for the shared 6 PM games summary Co-Authored-By: Claude Opus 5.5 --- server.js | 685 ++++++++++++++++++++------------------- tools/patch_ach_topic.py | 31 ++ 2 files changed, 378 insertions(+), 338 deletions(-) create mode 100644 tools/patch_ach_topic.py diff --git a/server.js b/server.js index 2e4e594..0efbfbf 100644 --- a/server.js +++ b/server.js @@ -1,338 +1,347 @@ -// 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 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('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); - 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} Drip Runner \u00b7 ' + nameOf(me) + ' unlocked the ' + ITEM_NAMES[item] + ' (' + paid + ')' }).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' : '') }).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.' }).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' }; -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 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; - // 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 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); - // 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; }); - const meNow = { memberId: Number(r.claims.memberId), username: r.claims.username || null, wallet: r.claims.wallet ? String(r.claims.wallet).toLowerCase() : null }; - for (const ch of pendingClears) { const g = ledger.chapterDrip(meNow, ch, true); if (g.pol) announceChapter(meNow, ch, g.pol); } // clears made as a guest pay now - if (first) notify('signin', { memberId: r.claims.memberId, username: r.claims.username, wallet: r.claims.wallet, via: guest ? 'a share link' : null }).catch(() => {}); - res.writeHead(302, { Location: '/play' + (pendingClears.length ? '?collected=' + pendingClears.length : ''), 'Set-Cookie': [sso.cookie(sid)].concat(guest ? [sso.clearGuestCookie()] : []), 'Cache-Control': 'no-store' }); return res.end(); - } - { const mr = /^\/r\/([A-Za-z0-9_.-]{1,40})$/.exec(p); if (mr) { - const sharer = game.byUsername(mr[1]); - if (!sharer) { res.writeHead(302, { Location: '/', 'Cache-Control': 'no-store' }); return res.end(); } - const ck = ['dr.ref=' + encodeURIComponent(sharer.username.toLowerCase()) + '; Path=/; Max-Age=' + 30 * 86400 + '; SameSite=Lax' + (IS_PROD ? '; Secure' : '')]; - if (CURTAIN) ck.push('dr.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : '')); // a player's link is a pass during the trial - store.update('share-hits', {}, h => { const k = sharer.username.toLowerCase(); h[k] = (h[k] || 0) + 1; return h; }); - res.writeHead(302, { Location: '/play', 'Set-Cookie': ck, 'Cache-Control': 'no-store' }); return res.end(); - } } - if (p === '/logout') { const s = sso.fromRequest(req); if (s) sso.endSession(s.sid); res.writeHead(302, { Location: '/', 'Set-Cookie': sso.clearCookie() }); return res.end(); } - - // ---- IAP -> game: the refuel visit completed (server to server, signed) ---- - 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 === '/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')); - 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) - 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 })), 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/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 (p === '/api/guest' && req.method === 'POST') { - if (me) return json(res, 200, { ok: true, already: true }); - if (CURTAIN && !hasPass(req)) return json(res, 403, { error: 'Open the tester link or a player\u2019s share link first.' }); - const g = sso.startGuest(refCookie(req)); return json(res, 200, { ok: true }, { 'Set-Cookie': sso.guestCookie(g.gid) }); - } - const who = me || sso.guestFrom(req); - if (!who) return json(res, 401, { error: 'Sign in through InstantAdPay first.', iap: IAP + '/api/my/driprunner', guestOk: !CURTAIN || hasPass(req), signin: signinUrl(req) }); - return memberApi(req, res, u, p, who); - } - res.writeHead(404, Object.assign({ 'Content-Type': 'text/plain' }, SEC)); res.end('Not found'); - } catch (e) { - console.error(req.method, p, e && e.stack || e); - if (!res.headersSent) json(res, 500, { error: 'Something broke on our side. Try again.' }); - } -}); -function refCookie(req) { const m = /(?:^|;\s*)dr\.ref=([^;]+)/.exec(req.headers.cookie || ''); const r = m ? decodeURIComponent(m[1]) : ''; return /^[a-z0-9_.-]{1,40}$/.test(r) ? r : null; } -// where a guest signs in: through the sharer's InstantAdPay join link when they came from one (new people land under the sharer), else the plain hand-off -function signinUrl(req) { const r = refCookie(req); return r ? IAP + '/join/' + encodeURIComponent(r) + '?from=driprunner' : IAP + '/api/my/driprunner'; } -async function memberApi(req, res, u, p, me) { - try { - { - if (p === '/api/me' && req.method === 'GET') { - const pl = ledger.pool(); - const refs = me.guest ? [] : game.referralsOf(me); - return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet, guest: !!me.guest }, player: game.view(me), balance: ledger.balance(me.memberId), pool: { available: pl.available, capLeft: pl.capLeft, dripPol: Number(ledger.settings().dripPol) }, iap: IAP, site: SITE, tips: await tips.list(ledger.settings()), - signin: me.guest ? signinUrl(req) : null, share: (!me.guest && me.username) ? SITE + '/r/' + encodeURIComponent(me.username) : null, referrals: { count: refs.length, clicks: (store.read('share-hits', {})[String(me.username || '').toLowerCase()] || 0), earned: ledger.balance(me.memberId).refTotal, pct: Number(ledger.settings().refSharePct) || 0 } }); - } - if (p === '/api/balance' && req.method === 'GET') return json(res, 200, ledger.balance(me.memberId)); - if (p === '/api/run/start' && req.method === 'POST') { const { body } = await readBody(req); const r = game.start(me, body.W, body.H); return json(res, 200, { runId: r.id, seed: r.seed, W: r.W, H: r.H, speed: r.speed, chapter: r.chapter, goal: r.goal, armed: r.armed, ship: r.ship }); } - if (p === '/api/run/events' && req.method === 'POST') { const { body } = await readBody(req); const r = game.events(me, String(body.runId || ''), body.t, body.events, !!body.goal); if (r.cleared) { r.pool = ledger.pool().available; if (r.cleared.first && !me.guest) announceChapter(me, r.cleared.chapter, r.cleared.pol); } return json(res, r.error ? 400 : 200, r); } - if (p === '/api/run/end' && req.method === 'POST') { const { body } = await readBody(req); return json(res, 200, game.end(me, String(body.runId || ''))); } - // refuel: hand the player to IAP for a verified visit; the run resumes when IAP confirms - if (p === '/api/refuel/start' && req.method === 'POST') { - const { body } = await readBody(req); const r = game.run(String(body.runId || '')); - if (me.guest) return json(res, 403, { error: 'Sign in with InstantAdPay to refuel. Your run and progress come with you.', signin: signinUrl(req) }); - if (!r || r.memberId !== me.memberId || r.status !== 'live') return json(res, 400, { error: 'That run cannot be refuelled.' }); - const nonce = crypto.randomBytes(12).toString('hex'); const ret = SITE + '/play?resume=' + r.id + '&n=' + nonce; - intents.set(nonce, { runId: r.id, memberId: me.memberId, username: me.username, wallet: me.wallet, email: me.email, ts: Date.now(), done: false, consumed: false }); - 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); } +// 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 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, 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' }; +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 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; + // 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 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); + // 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; }); + const meNow = { memberId: Number(r.claims.memberId), username: r.claims.username || null, wallet: r.claims.wallet ? String(r.claims.wallet).toLowerCase() : null }; + for (const ch of pendingClears) { const g = ledger.chapterDrip(meNow, ch, true); if (g.pol) announceChapter(meNow, ch, g.pol); } // clears made as a guest pay now + if (first) notify('signin', { memberId: r.claims.memberId, username: r.claims.username, wallet: r.claims.wallet, via: guest ? 'a share link' : null }).catch(() => {}); + res.writeHead(302, { Location: '/play' + (pendingClears.length ? '?collected=' + pendingClears.length : ''), 'Set-Cookie': [sso.cookie(sid)].concat(guest ? [sso.clearGuestCookie()] : []), 'Cache-Control': 'no-store' }); return res.end(); + } + { const mr = /^\/r\/([A-Za-z0-9_.-]{1,40})$/.exec(p); if (mr) { + const sharer = game.byUsername(mr[1]); + if (!sharer) { res.writeHead(302, { Location: '/', 'Cache-Control': 'no-store' }); return res.end(); } + const ck = ['dr.ref=' + encodeURIComponent(sharer.username.toLowerCase()) + '; Path=/; Max-Age=' + 30 * 86400 + '; SameSite=Lax' + (IS_PROD ? '; Secure' : '')]; + if (CURTAIN) ck.push('dr.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : '')); // a player's link is a pass during the trial + store.update('share-hits', {}, h => { const k = sharer.username.toLowerCase(); h[k] = (h[k] || 0) + 1; return h; }); + res.writeHead(302, { Location: '/play', 'Set-Cookie': ck, 'Cache-Control': 'no-store' }); return res.end(); + } } + if (p === '/logout') { const s = sso.fromRequest(req); if (s) sso.endSession(s.sid); res.writeHead(302, { Location: '/', 'Set-Cookie': sso.clearCookie() }); return res.end(); } + + // ---- IAP -> game: the refuel visit completed (server to server, signed) ---- + 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 === '/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')); + 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 })), 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/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 (p === '/api/guest' && req.method === 'POST') { + if (me) return json(res, 200, { ok: true, already: true }); + if (CURTAIN && !hasPass(req)) return json(res, 403, { error: 'Open the tester link or a player\u2019s share link first.' }); + const g = sso.startGuest(refCookie(req)); return json(res, 200, { ok: true }, { 'Set-Cookie': sso.guestCookie(g.gid) }); + } + const who = me || sso.guestFrom(req); + if (!who) return json(res, 401, { error: 'Sign in through InstantAdPay first.', iap: IAP + '/api/my/driprunner', guestOk: !CURTAIN || hasPass(req), signin: signinUrl(req) }); + return memberApi(req, res, u, p, who); + } + res.writeHead(404, Object.assign({ 'Content-Type': 'text/plain' }, SEC)); res.end('Not found'); + } catch (e) { + console.error(req.method, p, e && e.stack || e); + if (!res.headersSent) json(res, 500, { error: 'Something broke on our side. Try again.' }); + } +}); +function refCookie(req) { const m = /(?:^|;\s*)dr\.ref=([^;]+)/.exec(req.headers.cookie || ''); const r = m ? decodeURIComponent(m[1]) : ''; return /^[a-z0-9_.-]{1,40}$/.test(r) ? r : null; } +// where a guest signs in: through the sharer's InstantAdPay join link when they came from one (new people land under the sharer), else the plain hand-off +function signinUrl(req) { const r = refCookie(req); return r ? IAP + '/join/' + encodeURIComponent(r) + '?from=driprunner' : IAP + '/api/my/driprunner'; } +async function memberApi(req, res, u, p, me) { + try { + { + if (p === '/api/me' && req.method === 'GET') { + const pl = ledger.pool(); + const refs = me.guest ? [] : game.referralsOf(me); + return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet, guest: !!me.guest }, player: game.view(me), balance: ledger.balance(me.memberId), pool: { available: pl.available, capLeft: pl.capLeft, dripPol: Number(ledger.settings().dripPol) }, iap: IAP, site: SITE, tips: await tips.list(ledger.settings()), + signin: me.guest ? signinUrl(req) : null, share: (!me.guest && me.username) ? SITE + '/r/' + encodeURIComponent(me.username) : null, referrals: { count: refs.length, clicks: (store.read('share-hits', {})[String(me.username || '').toLowerCase()] || 0), earned: ledger.balance(me.memberId).refTotal, pct: Number(ledger.settings().refSharePct) || 0 } }); + } + if (p === '/api/balance' && req.method === 'GET') return json(res, 200, ledger.balance(me.memberId)); + if (p === '/api/run/start' && req.method === 'POST') { const { body } = await readBody(req); const r = game.start(me, body.W, body.H); return json(res, 200, { runId: r.id, seed: r.seed, W: r.W, H: r.H, speed: r.speed, chapter: r.chapter, goal: r.goal, armed: r.armed, ship: r.ship }); } + if (p === '/api/run/events' && req.method === 'POST') { const { body } = await readBody(req); const r = game.events(me, String(body.runId || ''), body.t, body.events, !!body.goal); if (r.cleared) { r.pool = ledger.pool().available; if (r.cleared.first && !me.guest) announceChapter(me, r.cleared.chapter, r.cleared.pol); } return json(res, r.error ? 400 : 200, r); } + if (p === '/api/run/end' && req.method === 'POST') { const { body } = await readBody(req); return json(res, 200, game.end(me, String(body.runId || ''))); } + // refuel: hand the player to IAP for a verified visit; the run resumes when IAP confirms + if (p === '/api/refuel/start' && req.method === 'POST') { + const { body } = await readBody(req); const r = game.run(String(body.runId || '')); + if (me.guest) return json(res, 403, { error: 'Sign in with InstantAdPay to refuel. Your run and progress come with you.', signin: signinUrl(req) }); + if (!r || r.memberId !== me.memberId || r.status !== 'live') return json(res, 400, { error: 'That run cannot be refuelled.' }); + const nonce = crypto.randomBytes(12).toString('hex'); const ret = SITE + '/play?resume=' + r.id + '&n=' + nonce; + intents.set(nonce, { runId: r.id, memberId: me.memberId, username: me.username, wallet: me.wallet, email: me.email, ts: Date.now(), done: false, consumed: false }); + 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); } diff --git a/tools/patch_ach_topic.py b/tools/patch_ach_topic.py new file mode 100644 index 0000000..81b98d8 --- /dev/null +++ b/tools/patch_ach_topic.py @@ -0,0 +1,31 @@ +# Unlock / chapter / refuel badge cards go to the Crypto Team Build "Game Achievements" topic (DR_TG_ACH_TOPIC); payout +# cards stay in DR_TG_PUBLIC_TOPIC (the payments topic). Plus /api/public/today for the shared 6 PM games summary. +p = 'D:/Projects/HighRisk/drip-runner/server.js' +s = open(p, encoding='utf-8').read() +R = [ + ("async function telegramPhoto(file, caption, general) {\n if (!outbound()) return false;\n 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;", + "async function telegramPhoto(file, caption, general, topicOverride) {\n if (!outbound()) return false;\n 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;"), + (" const ok = await telegramPhoto(file, cap);\n if (ok && String(process.env.DR_TG_PUBLIC_GENERAL || 'off') === 'on') await telegramPhoto(file, cap, true);", + " const ok = await telegramPhoto(file, cap, false, opts.topic);\n if (ok && String(process.env.DR_TG_PUBLIC_GENERAL || 'off') === 'on') await telegramPhoto(file, cap, true);"), + ("const ITEM_NAMES = { magnet:", + "// badges and milestones = the achievements topic (Marty, 2026-10-01); payout cards keep DR_TG_PUBLIC_TOPIC\nconst ACH = () => process.env.DR_TG_ACH_TOPIC || '';\nconst ITEM_NAMES = { magnet:"), + ("unlocked the ' + ITEM_NAMES[item] + ' (' + paid + ')' }).catch(() => {}); }", + "unlocked the ' + ITEM_NAMES[item] + ' (' + paid + ')', topic: ACH() }).catch(() => {}); }"), + ("'' + (pol ? ' \\u00b7 +' + fmt(pol) + ' POL' : '') }).catch(() => {}); }", + "'' + (pol ? ' \\u00b7 +' + fmt(pol) + ' POL' : ''), topic: ACH() }).catch(() => {}); }"), + ("Every refuel is a verified visit to a member\\u2019s page on InstantAdPay.' }).catch(() => {}); }", + "Every refuel is a verified visit to a member\\u2019s page on InstantAdPay.', topic: ACH() }).catch(() => {}); }"), + (" if (p === '/api/public/stats' && req.method === 'GET') {", + " // the last 24 hours for the shared 6 PM games summary in the achievements topic (counts only, no POL amounts)\n" + " if (p === '/api/public/today' && req.method === 'GET') {\n" + " const since = Date.now() - 24 * 3600000, t = v => typeof v === 'number' ? v : Date.parse(v) || 0;\n" + " const refuels = store.read('refuels', []).filter(x => t(x.ts) >= since), clears = store.read('drips', []).filter(x => t(x.ts) >= since);\n" + " const players = Object.values(store.read('players', {})).filter(x => x.memberId > 0);\n" + " 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 });\n" + " }\n" + " if (p === '/api/public/stats' && req.method === 'GET') {"), +] +for a, b in R: + if s.count(a) != 1: raise SystemExit('anchor %d: %s' % (s.count(a), a[:90])) + s = s.replace(a, b) +open(p, 'w', encoding='utf-8').write(s); print('drip runner ok')