Compare commits

..

20 Commits

Author SHA1 Message Date
martbost 63e8012b16 Payout sender: local nonce + nonce clash = retry + dropped tx back to due + 403 rotates (Turkey Drop's week prizes collided 2026-11-09, 'replacement fee too low')
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:59:16 -06:00
martbost f002222b25 polgrant: say when the free game allowance is used up (Marty 2026-11-03). InstantAdPay's answer carries lifetimeHit, freeLifetime and waiting; the note reads 'You have used your free 2 POL in the games. Get the Game Pass to keep earning.' plus the POL held for a progress reward, instead of 'pays out over the next days'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:18:04 -06:00
martbost b69086aaac Tiers (Marty 2026-11-02, every game must fund itself): guests earn nothing (a guest's chapters, drips and best follow them at sign-in, the POL does not; no more collected= payout on /auth), a free InstantAdPay account earns freeSharePct (25, admin) of the chapter drip with the note "Game Pass holders earn the full amount.", Game Pass holders earn the full drip plus the shield perk, GAMEPASS off = everyone full. /api/me carries tier, freeSharePct and yourDrip; landing, lobby, clear card, tester briefing and share preview say play free, sign in to earn a taste, Game Pass for the full table. Tests: guest 0 at sign-in, free 25%, pass 100%, gp off full, settings key.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 17:01:10 -06:00
martbost 4d8dde2ad2 Stop the private duplicate of every payout line: the card already goes to the shared payments topic (Marty, 2026-11-02)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 08:27:27 -06:00
martbost b70ecf6f75 Pay game POL to any signature-linked wallet, on chain or not (2026-10-27)
InstantAdPay now pushes a member's signature-linked wallet whether or not it is activated (memberId 0 when not on chain).
- POST /api/iap/wallet accepts memberId 0/missing: the wallet fills the email-keyed player (sso.emailId) and its account;
  a player with no account row yet gets one holding the wallet. Signature check, fill-empty-only (different wallet 409),
  same wallet no-op and 404 for an unknown player are unchanged; a real memberId still adopts the email history first.
- /auth: a hand-off wallet fills an EMPTY account wallet so POL earned so far pays on the next sweep (never replaces one).
- game.adopt carries the wallet when the target account has none.
- /api/me: me.hasWallet (own wallet on file, also when it arrived by the push after the session began).
- play.js: no-wallet players see "Link your wallet to receive this POL" (IAP /my#wallet, new tab) on the chapter-clear
  result, the lobby member line and the balance card (which also lost a line that always overwrote the waiting-POL note);
  players with a wallet see the same text as before. play.js?v=20261027lw.
- test/run.js: memberId 0 push -> 200 changed:true -> sweep pays it; /auth memberId 0 wallet; 409; activation later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 09:18:09 -05:00
martbost eb2cb822ac Signed POST /api/iap/wallet: InstantAdPay pushes a member's activated wallet into the game (fills an empty wallet through the same setWallet path /auth uses; same wallet again is a no-op, a different one is refused), so POL earned before a wallet was linked pays out without a fresh hand-off (2026-10-25, solanaclick 1.5 POL stuck in Gem Kingdom)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 05:09:11 -05:00
martbost cc3db3833f Game Pass bridge (GAMEPASS=on): chapter first clears via InstantAdPay polgrant (wallet-less members by email), shield at run start perk, lobby line + clear note, tests
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 06:50:39 -05:00
Marty Bostick c9515e16eb Discord relay: wrap button links in <> so Discord shows no preview cards under every post
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 15:16:42 +00:00
Marty Bostick fe61842525 Mirror Telegram group posts into the Crypto Team Build Discord
Discord relaunch 2026-10-09: the shared discord-relay.cjs fans every post that goes to the
community group out to the matching Discord channel (achievements topic -> #achievements,
payments topic -> #payment-proofs) through DISCORD_WEBHOOK_* webhooks. Telegram HTML is
converted to Discord markdown, buttons become links, cards post as images. DMs and alert
chats are not mirrored. Fire-and-forget; off when the env is unset.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 13:57:38 +00:00
martbost 1bace54bc2 Faucet: treat connection-level failures (socket hang up, EPIPE, fetch failed, ...) as transient: leave the drip due and rotate RPC instead of marking it failed (PolHunter #7, 2026-10-09)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 04:30:10 -05:00
martbost 7c2d6b7467 Signed /api/iap/unpaid feed for InstantAdPay's wallet-link nudges; balance screen and a one-time toast tell a player with POL waiting and no wallet how to get paid
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-07 10:35:15 -05:00
martbost 3aa5698c8a Network line: game is part of the InstantAdPay network, the Polygon wing of the Crypto Team Build Network (linked to cryptoteambuild.com, new tab)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:42:19 -05:00
martbost 11d6f46950 Invite friends card in the lobby + ?ref attribution on every entry page
Marty: members could not find their referral link. A signed-in player now sees an
"Invite friends" card right under Play: their /r/<username> link (previews with their
own card), Copy (clipboard API, select+copy fallback, prompt last) with a Copied!
confirmation, and Share where the phone has a share sheet. Link stats and the how-it-works
line moved into the card. No username yet: the card says how to get one.

Attribution: ?ref=<name> on /, /play and /signin (and ?r= on the landing, where framed
/r/<name> lands) now sets the same dr.ref sponsor cookie as /r/<name>, last touch wins.
/r/<name> for a name the game does not know keeps it as /?ref=<name> instead of
dropping it. signin.js also reads ?ref straight from the URL. Tests cover each path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:25:22 -05:00
martbost 09692de8c6 Member welcome offer + member perk: after a chapter clear, a signed-in non-member (IAP memberId 0) sees a dismissible "Become an InstantAdPay member" card once per Central day (bonus from IAP /api/starter/public, cached 10 min, skipped when off); a member's first hand-off grants one free hangar upgrade (token on the player, next purchase costs nothing, no POL moved), with a one-time lobby message
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:24:20 -05:00
martbost 4fa68b2745 Share links preview as the sharer's own card (badge with their name) for Telegram/Facebook/X; the game page previews as the Drip Runner banner, not the blank badge
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 10:18:49 -05:00
martbost 75ba7ba388 Traffic exchanges: public pages may be framed (admin/sign-in still refuse); a framed game or share link shows the landing, whose buttons open play in a new tab with the referral
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 19:14:15 -05:00
martbost 08e70d6a16 Refuel income: a reported 0 credits (house-ad visit) stays 0, never falls back to the visit price
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 15:48:08 -05:00
martbost 60f1148efa Paid-traffic source tracking: ?utm_source/src + clickid -> dr.src cookie, per-source visits/guests/runs/sign-ins/new accounts, BeMob postback on a new account (DR_POSTBACK_URL), /api/admin/srcstats
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 11:30:22 -05:00
martbost 305bd435fa Cross-promo: More games strip from InstantAdPay's shared list (2026-10-03)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 10:23:46 -05:00
martbost 19b4bf8fbb Hidden means hidden on every element: .btn{display:block} beat the hidden attribute, so signed-in players still saw 'Sign in to keep progress'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 10:09:33 -05:00
24 changed files with 1579 additions and 611 deletions
+1
View File
@@ -1,5 +1,6 @@
node_modules/
data/
data-test/
data-test-starter/
*.log
.env
+86
View File
@@ -0,0 +1,86 @@
// discord-relay.cjs — mirror a Telegram group post into the Crypto Team Build Discord (relaunch 2026-10-09).
// Drop-in for every app that posts with the shared CTB Rewards bot. Call mirror() right where the app calls
// Telegram; it is fire-and-forget, never throws, and does nothing unless the DISCORD_WEBHOOK_* env is set.
// mirror({ chatId, threadId, text, photo, buttons })
// chatId the Telegram chat the post goes to. Only the community group is mirrored; DMs / alert chats are skipped.
// threadId forum topic: achievements (661565) -> #achievements, payments (632242) -> #payment-proofs,
// no topic (General) -> #achievements. Override with DISCORD_TOPIC_ACH / DISCORD_TOPIC_PAY.
// text Telegram HTML (converted to Discord markdown; user text is escaped so names with _ don't italicise)
// photo Buffer (uploaded) or a public image URL (embedded), optional
// buttons Telegram inline_keyboard (url buttons become links under the text), optional
// Env: DISCORD_WEBHOOK_ACHIEVEMENTS, DISCORD_WEBHOOK_PAYMENT_PROOFS, DISCORD_WEBHOOK_PROMOS, DISCORD_WEBHOOK_ANNOUNCEMENTS,
// DISCORD_WEBHOOK_OPS; DISCORD_TG_GROUP (default -1001258691510); DISCORD_RELAY=off to disable.
// The same post twice within 15 minutes (e.g. a badge sent to a topic AND to General) is mirrored once.
'use strict';
const crypto = require('node:crypto');
const GROUP = () => String(process.env.DISCORD_TG_GROUP || '-1001258691510');
const TOPIC_ACH = () => String(process.env.DISCORD_TOPIC_ACH || '661565');
const TOPIC_PAY = () => String(process.env.DISCORD_TOPIC_PAY || '632242');
const HOOKS = { achievements: 'DISCORD_WEBHOOK_ACHIEVEMENTS', 'payment-proofs': 'DISCORD_WEBHOOK_PAYMENT_PROOFS', promos: 'DISCORD_WEBHOOK_PROMOS', announcements: 'DISCORD_WEBHOOK_ANNOUNCEMENTS', ops: 'DISCORD_WEBHOOK_OPS' };
function hookFor(feed) { const v = String(process.env[HOOKS[feed]] || ''); return v.startsWith('https://discord.com/api/webhooks/') ? v : ''; }
function feedFor(threadId) { const t = String(threadId == null ? '' : threadId); if (t === TOPIC_PAY()) return 'payment-proofs'; if (t === TOPIC_ACH()) return 'achievements'; return 'achievements'; }
// ---- Telegram HTML -> Discord markdown ----
const ENT = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", '&apos;': "'", '&nbsp;': ' ' };
const unesc = s => s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, m => ENT[m] || m);
const escMd = s => s.replace(/([\\*_~`|])/g, '\\$1').replace(/^(\s*)([>#-])/gm, '$1\\$2');
const WRAP = { b: '**', strong: '**', i: '*', em: '*', u: '__', ins: '__', s: '~~', strike: '~~', del: '~~', code: '`', 'tg-spoiler': '||', spoiler: '||' };
function htmlToMd(html) {
const re = /<\/?([a-zA-Z-]+)(?:\s+[^>]*)?\/?>/g; const stack = []; let out = '', last = 0, inCode = 0, m;
const emit = t => { if (!t) return; const u = unesc(t); out += inCode ? u : escMd(u); };
const close = mk => { const ws = (/\s+$/.exec(out) || [''])[0]; out = out.slice(0, out.length - ws.length) + mk + ws; };
while ((m = re.exec(html))) {
emit(html.slice(last, m.index)); last = re.lastIndex; const raw = m[0], tag = m[1].toLowerCase();
if (tag === 'br') { out += '\n'; continue; }
if (!raw.startsWith('</')) {
if (tag === 'a') { const h = /href=(?:"([^"]*)"|'([^']*)')/i.exec(raw); stack.push({ tag, href: h ? (h[1] || h[2]) : '', start: out.length }); }
else if (tag === 'pre') { out += '```\n'; inCode++; stack.push({ tag, start: out.length }); }
else if (WRAP[tag]) { if (tag === 'code') inCode++; out += WRAP[tag]; stack.push({ tag, start: out.length }); }
} else {
let i = stack.length - 1; while (i >= 0 && stack[i].tag !== tag) i--; if (i < 0) continue;
const o = stack[i]; stack.length = i;
if (tag === 'a') { const inner = out.slice(o.start); out = out.slice(0, o.start) + (o.href ? '[' + inner + '](' + o.href + ')' : inner); }
else if (tag === 'pre') { out += '\n```'; inCode--; }
else if (WRAP[tag]) { if (tag === 'code') inCode--; close(WRAP[tag]); }
}
}
emit(html.slice(last)); return out.replace(/\n{3,}/g, '\n\n').trim();
}
// ---- sending: one queue per webhook, 1.2 s apart, 429 honoured ----
const queues = new Map(); const seen = new Map();
const sleep = ms => new Promise(r => setTimeout(r, ms));
function content(text, buttons) {
let c = htmlToMd(String(text || ''));
const links = []; try { for (const row of (buttons && buttons.inline_keyboard) || []) for (const b of row) if (b && b.url) links.push('[' + String(b.text || 'Open').replace(/[\[\]]/g, '') + '](<' + b.url + '>)'); } catch (e) {}
if (links.length) c += '\n\n' + links.join(' · ');
return c.length > 1990 ? c.slice(0, 1989) + '…' : c;
}
async function post(url, msg, attempt) {
const payload = { content: content(msg.text, msg.buttons), allowed_mentions: { parse: [] } };
let body, headers = {};
if (msg.photo && typeof msg.photo !== 'string') {
payload.attachments = [{ id: 0, filename: 'card.jpg' }];
const fd = new FormData(); fd.append('payload_json', JSON.stringify(payload)); fd.append('files[0]', new Blob([msg.photo]), 'card.jpg'); body = fd;
} else {
if (typeof msg.photo === 'string' && msg.photo) payload.embeds = [{ image: { url: msg.photo } }]; else payload.flags = 1 << 2;
body = JSON.stringify(payload); headers['Content-Type'] = 'application/json';
}
const r = await fetch(url + '?wait=true', { method: 'POST', headers, body, signal: AbortSignal.timeout(20000) });
if (r.status === 429 && (attempt || 0) < 2) { const j = await r.json().catch(() => ({})); await sleep((Number(j.retry_after) || 2) * 1000 + 250); return post(url, msg, (attempt || 0) + 1); }
if (!r.ok) console.error('[discord-relay] post failed http=' + r.status + ' ' + (await r.text().catch(() => '')).slice(0, 160));
}
function mirror(msg) {
try {
if (String(process.env.DISCORD_RELAY || 'on').toLowerCase() === 'off') return;
if (!msg || String(msg.chatId || '') !== GROUP()) return;
const feed = msg.feed || feedFor(msg.threadId); const url = hookFor(feed); if (!url) return;
const key = crypto.createHash('sha1').update(feed + '\n' + String(msg.text || '') + '\n' + (Buffer.isBuffer(msg.photo) ? msg.photo.length : String(msg.photo || ''))).digest('hex');
const now = Date.now(); for (const [k, t] of seen) if (now - t > 15 * 60000) seen.delete(k);
if (seen.has(key)) return; seen.set(key, now);
const prev = queues.get(url) || Promise.resolve();
queues.set(url, prev.then(() => post(url, msg, 0)).catch(e => console.error('[discord-relay]', e && e.message)).then(() => sleep(1200)));
} catch (e) { console.error('[discord-relay]', e && e.message); }
}
module.exports = { mirror, htmlToMd, feedFor };
+13 -4
View File
@@ -18,8 +18,15 @@ const dry = () => String(process.env.DR_DRY_RUN || 'on').toLowerCase() !== 'off'
function enabled() { return !!(process.env.DR_WALLET_KEY && process.env.DR_RPC); }
function init() { if (!enabled()) return false; rpcs = String(process.env.DR_RPC).split(',').map(s => s.trim()).filter(Boolean); rpcAt = 0; connect(); return true; }
function connect() { provider = new ethers.JsonRpcProvider(rpcs[rpcAt % rpcs.length], Number(process.env.DR_CHAIN_ID) || undefined); wallet = new ethers.Wallet(process.env.DR_WALLET_KEY.trim(), provider); }
const TRANSIENT = /server response 5\d\d|timeout|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|429|rate limit|missing response|could not detect network|bad response|SERVER_ERROR|NETWORK_ERROR/i;
const TRANSIENT = /socket hang up|ECONNABORTED|EPIPE|EHOSTUNREACH|ENETUNREACH|network error|fetch failed|UND_ERR|other side closed|server response 5\d\d|timeout|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|429|rate limit|missing response|could not detect network|bad response|SERVER_ERROR|NETWORK_ERROR|403|Forbidden|401|Unauthorized/i; // + connection-level failures (PolHunter #7, 2026-10-09)
function rotate(reason) { if (rpcs.length > 1) { rpcAt = (rpcAt + 1) % rpcs.length; connect(); console.warn('faucet: RPC rotated after', reason.slice(0, 80)); } }
// Nonce (2026-11-09, after Turkey Drop's week prizes collided with "replacement fee too low"): publicnode is a load-balanced pool, so
// asking it for the next nonce right after a confirmed send can return the SAME nonce again. Sends read the nonce once per tick, keep
// the highest one ever used in faucet-state.nextNonce, and count up locally. A nonce clash is a retry (row back to due), never a failure.
const NONCE_ERR = /replacement fee too low|replacement transaction underpriced|nonce too low|nonce has already been used|already known|NONCE_EXPIRED|REPLACEMENT_UNDERPRICED/i;
async function nextNonce() { const n = await provider.getTransactionCount(wallet.address, 'pending'); return Math.max(n, Number(store.read('faucet-state', {}).nextNonce) || 0); }
const keepNonce = n => store.update('faucet-state', {}, x => Object.assign(x, { nextNonce: Math.max(n, Number(x.nextNonce) || 0) }));
const DROP_MS = 10 * 60000; // a "sent" row whose tx no node knows after this long was dropped: back to due (its nonce slot is reused, so it can never pay twice)
function address() { return wallet ? wallet.address : null; }
async function balance() { if (!provider || !wallet) return null; return Number(ethers.formatEther(await provider.getBalance(wallet.address))); }
function state() { return Object.assign({ dryRun: dry(), address: address(), enabled: enabled() }, store.read('faucet-state', {})); }
@@ -36,7 +43,7 @@ async function tick(notify) {
ticking = true; let paid = 0, would = 0;
try {
for (const p of store.read('payouts', []).filter(x => x.status === 'sent' && x.tx)) {
try { const rc = await provider.getTransactionReceipt(p.tx); if (rc && (await settle(p, rc, notify))) paid++; } catch (e) {}
try { const rc = await provider.getTransactionReceipt(p.tx); if (rc) { if (await settle(p, rc, notify)) paid++; } else if (Date.now() - (p.sentAt || p.ts || 0) > DROP_MS && !(await provider.getTransaction(p.tx))) ledger.mark(p.id, { status: 'due', tx: null, error: 'dropped ' + String(p.tx).slice(0, 12) + ', resending' }); } catch (e) { if (TRANSIENT.test(String(e.message || e))) { rotate(String(e.message || e)); break; } } // a node refusing us (403) must not freeze the check
}
const due = ledger.payable();
let bal = null; try { bal = await balance(); } catch (e) {}
@@ -46,17 +53,19 @@ async function tick(notify) {
store.update('faucet-state', {}, x => Object.assign(x, { balance: bal, checkedAt: Date.now(), lastTick: { due: due.length, would } }));
return { paid: 0, dryRun: true, due: due.length, would, balance: bal };
}
let nonce = null; if (due.length) { try { nonce = await nextNonce(); } catch (e) { if (TRANSIENT.test(String(e.message || e))) rotate(String(e.message || e)); return { paid }; } }
for (const p of due) {
if (bal != null && bal < p.pol + 0.005) { await lowOnce(notify, bal, p.pol); break; }
try {
const tx = await wallet.sendTransaction({ to: p.wallet, value: ethers.parseEther(String(p.pol)) });
ledger.mark(p.id, { status: 'sent', tx: tx.hash });
const tx = await wallet.sendTransaction({ to: p.wallet, value: ethers.parseEther(String(p.pol)), nonce });
ledger.mark(p.id, { status: 'sent', tx: tx.hash, sentAt: Date.now() }); nonce++; keepNonce(nonce);
let rc = null;
try { rc = await tx.wait(1, 90000); } catch (e) { if (e && e.code === 'TIMEOUT') continue; throw e; }
if (await settle(Object.assign({}, p, { tx: tx.hash }), rc, notify)) { paid++; if (bal != null) bal -= p.pol; }
} catch (e) {
const msg = String(e.message || e);
if (/insufficient funds/i.test(msg)) { ledger.mark(p.id, { status: 'due', error: null }); break; }
if (NONCE_ERR.test(msg) || NONCE_ERR.test(String(e && e.code))) { ledger.mark(p.id, { status: 'due', error: 'nonce clash, retrying' }); try { keepNonce(await provider.getTransactionCount(wallet.address, 'latest')); } catch (x) {} break; }
const cur = store.read('payouts', []).find(x => x.id === p.id);
if (cur && cur.status === 'sent' && cur.tx) continue;
if (TRANSIENT.test(msg)) { ledger.mark(p.id, { status: 'due', error: 'node: ' + msg.slice(0, 120) }); rotate(msg); break; }
+17 -9
View File
@@ -27,7 +27,7 @@ function updPlayer(memberId, fn) {
function view(me) {
const p = player(me.memberId) || updPlayer(me.memberId, () => {});
const s = ledger.settings();
return { bank: p.bank, chapter: p.chapter, cleared: p.cleared, items: p.items, best: p.runs ? p.best : 0, runs: p.runs,
return { bank: p.bank, chapter: p.chapter, cleared: p.cleared, items: p.items, best: p.runs ? p.best : 0, runs: p.runs, freeUpgrades: Number(p.freeUpgrades) || 0,
goal: spawn.goalFor(p.chapter), prices: { pol: s.itemPol, drips: s.itemDrips }, dripPol: Number(s.dripPol) };
}
@@ -44,8 +44,10 @@ function start(me, W, H) {
const p = updPlayer(me.memberId, x => { x.runs++; });
// any live run this member left open is closed; a player has one run at a time
store.update('runs', {}, all => { for (const k of Object.keys(all)) if (all[k].memberId === Number(me.memberId) && all[k].status === 'live') all[k].status = 'abandoned'; return all; });
const armed = { magnet: !!p.items.magnet, shield: !!p.items.shield, slow: !!p.items.slow };
updPlayer(me.memberId, x => { delete x.items.magnet; delete x.items.shield; delete x.items.slow; }); // one-run items are consumed now
// Game Pass perk (GAMEPASS=on, the member's pass active): a shield at the start of every run; a bought Shield Core is kept for a later run
const passShield = ledger.passActive(me);
const armed = { magnet: !!p.items.magnet, shield: !!p.items.shield || passShield, slow: !!p.items.slow, passShield };
updPlayer(me.memberId, x => { delete x.items.magnet; if (!passShield) delete x.items.shield; delete x.items.slow; }); // one-run items are consumed now
const r = { id: crypto.randomBytes(8).toString('hex'), memberId: Number(me.memberId), seed: crypto.randomInt(1, 2 ** 31), W, H,
speed: spawn.speedFor(p.chapter), chapter: p.chapter, goal: spawn.goalFor(p.chapter), startedAt: Date.now(), t: 0, drips: 0, chapDrips: 0,
collected: [], bad: 0, refuels: 0, status: 'live', armed, ship: p.items.ship ? 2 : 1, flagged: false, cleared: [] };
@@ -66,7 +68,7 @@ function dripInfo(r, i, t) {
}
// the client's batch of claims for a live run
function events(me, runId, t, list, wantGoal) {
async function events(me, runId, t, list, wantGoal) { // async since the Game Pass: with GAMEPASS=on InstantAdPay is asked before a member is paid (ledger.chapterDripGated)
const r = run(runId);
if (!r || r.memberId !== Number(me.memberId)) return { error: 'That run is not yours or no longer exists.' };
if (r.status !== 'live') return { error: 'That run is over.', over: true };
@@ -94,12 +96,12 @@ function events(me, runId, t, list, wantGoal) {
if (out.chapDrips < out.goal) { res.cleared = null; res.short = out.goal - out.chapDrips; return res; }
const ch = out.chapter; const p = player(me.memberId);
const first = !(p.cleared || {})[ch];
const grant = me.guest ? { pol: 0, reason: 'guest' } : ledger.chapterDrip(me, ch, first && !out.flagged);
// a guest earns nothing (Marty 2026-11-02): the clear counts as progress and follows them when they sign in, the POL does not
const grant = me.guest ? { pol: 0, reason: 'guest' } : await ledger.chapterDripGated(me, ch, first && !out.flagged);
if (first && out.flagged) grant.reason = 'flagged';
if (me.guest && first && !out.flagged) updPlayer(me.memberId, x => { x.pending = Array.from(new Set([...(x.pending || []), ch])); }); // paid when they sign in
updPlayer(me.memberId, x => { x.cleared[ch] = true; if (x.chapter <= ch) x.chapter = ch + 1; });
updRun(runId, x => { x.cleared.push(ch); x.chapter = ch + 1; x.chapDrips = 0; x.goal = spawn.goalFor(ch + 1); });
res.cleared = { chapter: ch, first, pol: grant.pol, reason: grant.reason, next: ch + 1, nextGoal: spawn.goalFor(ch + 1), playTime: Math.round(out.t) };
res.cleared = { chapter: ch, first, pol: grant.pol, reason: grant.reason, note: grant.note || null, next: ch + 1, nextGoal: spawn.goalFor(ch + 1), playTime: Math.round(out.t) }; // note = the Game Pass truth
}
return res;
}
@@ -112,18 +114,23 @@ function end(me, runId) {
function refuelled(me, runId) { return updRun(runId, x => { x.refuels++; }); }
// hangar
// a free upgrade token (the member perk, lib/starter.js) pays for the next purchase whatever it is: no drips, no POL moved
function useFree(me, item) { updPlayer(me.memberId, x => { x.freeUpgrades = Math.max(0, (Number(x.freeUpgrades) || 0) - 1); x.items[item] = true; }); return { ok: true, free: true, paid: 'free upgrade' }; }
function buy(me, item) {
const s = ledger.settings(); const p = player(me.memberId) || updPlayer(me.memberId, () => {});
const free = Number(p.freeUpgrades) > 0;
if (s.itemDrips[item] != null) {
const cost = Number(s.itemDrips[item]);
if (item === 'ship' && p.items.ship) return { error: 'You already own the Courier Mk II.' };
if (p.items[item] && item !== 'ship') return { error: 'That one is already armed for your next run.' };
if (free) return useFree(me, item);
if (p.bank < cost) return { error: 'Not enough drips. You have ' + p.bank + ', it costs ' + cost + '.' };
updPlayer(me.memberId, x => { x.bank -= cost; x.items[item] = true; });
return { ok: true, paid: cost + ' drips' };
}
if (s.itemPol[item] != null) {
if (p.items[item]) return { error: 'That one is already armed for your next run.' };
if (free) return useFree(me, item);
const r = ledger.spend(me, item, Number(s.itemPol[item])); if (r.error) return r;
updPlayer(me.memberId, x => { x.items[item] = true; });
return { ok: true, paid: r.pol + ' POL' };
@@ -131,7 +138,8 @@ function buy(me, item) {
return { error: 'No such item.' };
}
// Move everything one id owns onto another (a guest who signs in, or a wallet-less member who links a wallet).
// Returns the chapters the old id cleared as a guest that the new id has never cleared: the caller pays those.
// Returns the chapters the old id cleared as a guest that the new id has never cleared. Since 2026-11-02 nobody pays those
// (guests earn nothing; the progress carries, the POL does not); the list is informational.
function adopt(fromId, toId) {
fromId = Number(fromId); toId = Number(toId); if (!fromId || fromId === toId) return { moved: false, pending: [] };
const all = store.read('players', {}); const a = all[String(fromId)]; if (!a) return { moved: false, pending: [] };
@@ -143,7 +151,7 @@ function adopt(fromId, toId) {
delete ps[String(fromId)]; return ps;
});
for (const name of ['drips', 'spends', 'refuels', 'payouts']) store.update(name, [], rows => { for (const r of rows) if (r.memberId === fromId) r.memberId = toId; return rows; });
store.update('accounts', {}, acc => { const x = acc[String(fromId)]; if (x) { const y = acc[String(toId)]; if (y) { y.unpaid = Math.round((y.unpaid + x.unpaid) * 10000) / 10000; y.earnedTotal = Math.round(((y.earnedTotal || 0) + (x.earnedTotal || 0)) * 10000) / 10000; y.spentTotal = Math.round(((y.spentTotal || 0) + (x.spentTotal || 0)) * 10000) / 10000; } else acc[String(toId)] = Object.assign({}, x, { memberId: toId }); delete acc[String(fromId)]; } return acc; });
store.update('accounts', {}, acc => { const x = acc[String(fromId)]; if (x) { const y = acc[String(toId)]; if (y) { y.unpaid = Math.round((y.unpaid + x.unpaid) * 10000) / 10000; y.earnedTotal = Math.round(((y.earnedTotal || 0) + (x.earnedTotal || 0)) * 10000) / 10000; y.spentTotal = Math.round(((y.spentTotal || 0) + (x.spentTotal || 0)) * 10000) / 10000; if (!y.wallet && x.wallet) y.wallet = x.wallet; } else acc[String(toId)] = Object.assign({}, x, { memberId: toId }); delete acc[String(fromId)]; } return acc; });
store.update('runs', {}, rs => { for (const k of Object.keys(rs)) if (rs[k].memberId === fromId) rs[k].memberId = toId; return rs; });
store.update('posted', {}, ps => { if (ps[String(fromId)]) { ps[String(toId)] = Array.from(new Set([...(ps[String(toId)] || []), ...ps[String(fromId)]])); delete ps[String(fromId)]; } return ps; });
return { moved: true, pending };
+78 -7
View File
@@ -25,7 +25,11 @@ const DEFAULTS = {
itemPol: { shield: 0.05, slow: 0.03 }, // hangar items paid from the POL balance (the sink)
itemDrips: { magnet: 250, ship: 600 }, // hangar items paid in drips (never money)
refSharePct: 10, // the referrer's slice of each refuel's pool income (their referrals' refuels), paid into the referrer's game balance
testers: [], // emails or member ids allowed through the hand-off while signups = 'testers'
// the free tier (Marty 2026-11-02, every game must fund itself): a free InstantAdPay account earns freeSharePct of the chapter
// drip; Game Pass holders earn the full table (the Pass is the purchase that funds the game); guests earn nothing. With
// GAMEPASS off there is no pass to buy, so everyone counts as a pass holder
freeSharePct: 25,
testers: [], // emails or member ids allowed through the hand-off while signups = 'testers'
trial: true, // posts say 'coming soon, in testing' and 'would have earned' until Marty flips it
signups: 'testers' // 'testers' | 'key' (tester list or the curtain pass) | 'open' | 'closed'
};
@@ -51,7 +55,8 @@ function poolAdd(field, pol) { store.update('pool', {}, p => { p[field] = r4((p[
// ---- refuels: the income --------------------------------------------------------------------
async function refuel(me, info) {
const s = settings();
const credits = Math.max(0, Number(info.credits) || Number(s.creditsPerVisit) || 3);
// IAP reports 0 for a house-ad visit (nobody paid): keep it 0, never fall back to the visit price (2026-10-03)
const credits = Math.max(0, (info.credits != null && info.credits !== '' && isFinite(Number(info.credits))) ? Number(info.credits) : (Number(s.creditsPerVisit) || 3));
const usd = credits * Number(s.usdPerCredit);
const share = usd * Number(s.poolSharePct) / 100;
const rate = await usdPerPol();
@@ -78,10 +83,12 @@ function refuelsToday() { const d = ctDay(); return store.read('refuels', []).fi
function account(memberId) { return Object.assign({ memberId: Number(memberId), unpaid: 0, paidTotal: 0, spentTotal: 0, earnedTotal: 0 }, store.read('accounts', {})[String(memberId)] || {}); }
function updAccount(memberId, fn) { return store.update('accounts', {}, all => { const a = Object.assign({ memberId: Number(memberId), unpaid: 0, paidTotal: 0, spentTotal: 0, earnedTotal: 0 }, all[String(memberId)] || {}); fn(a); a.unpaid = r4(a.unpaid); all[String(memberId)] = a; return all; })[String(memberId)]; }
// a first-time chapter clear. eligible=false means a replay or a flagged run: cleared, unpaid.
// a first-time chapter clear. eligible=false means a replay or a flagged run: cleared, unpaid. A guest earns nothing (2026-11-02).
function chapterDrip(me, chapter, eligible) {
const s = settings(); const pol = r4(Number(s.dripPol));
if (me && me.guest) return { pol: 0, reason: 'guest' };
const full = fullTier(me), pol = dripFor(me);
if (!eligible) return { pol: 0, reason: 'replay' };
if (!(pol > 0)) return { pol: 0, reason: 'none' };
const p = pool();
if (p.capLeft < pol) return { pol: 0, reason: 'cap' };
if (p.available < pol) return { pol: 0, reason: 'pool' };
@@ -89,7 +96,7 @@ function chapterDrip(me, chapter, eligible) {
store.update('drips', [], all => { all.push(row); return all; });
poolAdd('out', pol);
updAccount(me.memberId, a => { a.unpaid += pol; a.earnedTotal = r4((a.earnedTotal || 0) + pol); a.wallet = me.wallet || a.wallet || null; a.username = me.username || a.username || null; });
return { pol, reason: 'paid', id: row.id };
return freeNoted(full, { pol, reason: 'paid', id: row.id });
}
// the sink: a hangar item paid from the member's unpaid POL balance goes back to the pool
@@ -104,6 +111,70 @@ function spend(me, item, pol) {
return { ok: true, pol };
}
// ---- Game Pass (GAMEPASS=on, docs/GAME-PASS.md 3a): InstantAdPay's account-wide caps decide what a member is paid; the
// local cap and pool above stay as a backstop and are never raised. The only POL Drip Runner pays is a chapter's first clear,
// once per member, so every reward here is 'progress': what today's cap does not allow is deferred on IAP and folded into a
// later answer. A member with no wallet has a negative local id (sso.emailId): IAP gets memberId 0 and the email instead.
const gp = require('./polgrant');
const kindOf = key => 'progress'; // refs: chapter:<n>
const iapId = me => Number(me.memberId) > 0 ? Number(me.memberId) : 0;
const passActive = me => !!(gp.on() && me && !me.guest && gp.passOf(iapId(me), me.email).active);
// the tiers (Marty 2026-11-02): guests earn nothing; a free InstantAdPay account earns freeSharePct of the table; Game Pass
// holders earn the full table. With GAMEPASS off there is no pass to buy, so every signed-in player is on the full tier.
const fullTier = me => !gp.on() || passActive(me);
const tierOf = me => (!me || me.guest) ? 'guest' : fullTier(me) ? 'full' : 'free';
function freeShare() { const v = Number(settings().freeSharePct); return Number.isFinite(v) ? Math.max(0, Math.min(100, v)) : Number(DEFAULTS.freeSharePct); }
// what one first clear pays this player: the table for the full tier, freeSharePct of it for a free account (4 decimals)
function dripFor(me) { const full = r4(Number(settings().dripPol)); return fullTier(me) ? full : r4(full * freeShare() / 100); }
const FREE_NOTE = 'Game Pass holders earn the full amount.';
// a reward that was scaled to the free share carries the note the client already shows (deferred / recorded notes stay in front).
// full = the tier at quote time: a grant answer re-records the pass flag, so the tier is read once, before IAP is asked
function freeNoted(full, res) { if (res && !full && (res.pol > 0 || res.reason === 'deferred' || res.reason === 'iap')) res.note = (res.note ? res.note + ' ' : '') + FREE_NOTE; return res; }
// the same checks as chapterDrip() up to (not including) the ledger write -> { pol, key, chapter } or { pol: 0, reason }
function quote(me, chapter, eligible) {
const pol = dripFor(me);
if (!eligible) return { pol: 0, reason: 'replay' };
if (!(pol > 0)) return { pol: 0, reason: 'none' };
const p = pool(); if (p.capLeft < pol) return { pol: 0, reason: 'cap' }; if (p.available < pol) return { pol: 0, reason: 'pool' };
return { pol, key: 'chapter:' + chapter, chapter };
}
// IAP answered: the ledger gets exactly what was allowed (0 included, so the chapter counts as handled); `carried` (inside
// allowed) is what IAP paid from an earlier deferral; the account tracks what IAP still owes.
function settleGrant(me, q, r, gkind) {
const allowed = r4(r.allowed), extra = r.carried > 0 ? r4(r.carried) : r4(Math.max(0, allowed - q.pol));
const row = { id: id(), memberId: Number(me.memberId), username: me.username || null, wallet: me.wallet || null, pol: allowed, chapter: q.chapter, day: ctDay(), ts: Date.now(), status: 'granted', gp: { kind: gkind, ref: q.key, nominal: q.pol, deferred: r4(r.deferred || 0), pass: !!r.pass } };
store.update('drips', [], all => { if (!all.some(d => d.memberId === row.memberId && d.gp && d.gp.ref === q.key)) all.push(row); return all; });
if (allowed > 0) poolAdd('out', allowed);
updAccount(me.memberId, a => { a.unpaid += allowed; a.earnedTotal = r4((a.earnedTotal || 0) + allowed); a.wallet = me.wallet || a.wallet || null; a.username = me.username || a.username || null; a.email = me.email || a.email || null; a.gpOwed = r4(Math.max(0, (a.gpOwed || 0) + (Number(r.deferred) || 0) - extra)); });
return { pol: allowed, reason: allowed > 0 ? 'paid' : (gkind === 'daily' ? 'capday' : 'deferred'), nominal: q.pol, deferred: r4(r.deferred || 0), pass: !!r.pass, note: gp.note(r, gkind, q.pol), id: row.id };
}
// chapterDrip() with IAP in front of it. Switch off: the plain chapterDrip, unchanged. A guest earns nothing, on either path
// (2026-11-02). Fail closed: no answer from IAP = nothing paid now, the ref queued and retried (polgrant.js), the player told
// it is recorded. A free account's quote is already the scaled amount (dripFor), so IAP's caps see the taste, not the table.
async function chapterDripGated(me, chapter, eligible) {
if (me && me.guest) return { pol: 0, reason: 'guest' };
if (!gp.on() || !gp.whoOf(iapId(me), me.email)) return chapterDrip(me, chapter, eligible);
const full = fullTier(me), q = quote(me, chapter, eligible); if (q.reason) return q;
if (gp.queued(iapId(me), me.email, q.key)) return freeNoted(full, { pol: 0, reason: 'iap', nominal: q.pol });
const gkind = kindOf(q.key), r = await gp.grant({ memberId: iapId(me), email: me.email, kind: gkind, pol: q.pol, ref: q.key });
if (r.retry) { gp.enqueue({ memberId: iapId(me), email: me.email, ref: q.key, kind: gkind, pol: q.pol, me: { memberId: Number(me.memberId), username: me.username || null, wallet: me.wallet || null, email: me.email || null }, q, full }); return freeNoted(full, { pol: 0, reason: 'iap', nominal: q.pol, note: gp.note(r, gkind, q.pol) }); }
return freeNoted(full, settleGrant(me, q, r, gkind));
}
const payQueued = (item, r) => freeNoted(item.full !== false, settleGrant(item.me, item.q, r, item.kind)); // a queued ref finally answered (full = the tier when it was quoted)
// once a Central day per account IAP still owes: a zero-POL progress call collects the carry-forward (IAP folds it into `allowed`)
async function carrySweep() {
if (!gp.on()) return 0; const today = ctDay(), accts = store.read('accounts', {}); let got = 0;
for (const k of Object.keys(accts)) {
const a = accts[k]; if (!(a.gpOwed > 0) || a.gpCarryDay === today) continue;
const me = { memberId: a.memberId, email: a.email || null, username: a.username, wallet: a.wallet };
if (!gp.whoOf(iapId(me), me.email)) continue;
const r = await gp.grant({ memberId: iapId(me), email: me.email, kind: 'progress', pol: 0, ref: 'carry:' + today }); if (r.retry) continue;
updAccount(a.memberId, x => { x.gpCarryDay = today; });
if (r.allowed > 0) { settleGrant(me, { pol: 0, key: 'carry:' + today, chapter: 0 }, r, 'progress'); got += r.allowed; }
}
return got;
}
// ---- payouts ----------------------------------------------------------------------------------
// a member whose unpaid balance reached the threshold gets one payout row for the whole amount;
// the balance moves to the row so drips earned meanwhile start a fresh count
@@ -135,7 +206,7 @@ function mark(pid, patch) {
function balance(memberId) {
const a = account(memberId); const s = settings();
const hist = []
.concat(store.read('drips', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'drip', label: 'Chapter ' + d.chapter + ' · first clear', pol: d.pol })))
.concat(store.read('drips', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'drip', label: !d.chapter ? 'Carried-over reward paid' : 'Chapter ' + d.chapter + ' · first clear' + (d.gp && d.gp.deferred > 0 ? ' (' + d.gp.deferred + ' POL paying out over the next days)' : ''), pol: d.pol })))
.concat(store.read('spends', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'spend', label: 'Hangar · ' + d.item, pol: -d.pol })))
.concat(store.read('refslices', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'ref', label: 'Referral · ' + (d.fromUsername ? '@' + d.fromUsername : 'a player') + ' refuelled', pol: d.pol })))
.concat(store.read('payouts', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'payout', label: d.status === 'paid' ? 'Paid to your wallet' : d.status === 'failed' ? 'Payout failed: ' + (d.error || '') : 'Payout on its way', pol: d.pol, status: d.status, tx: d.tx || null })))
@@ -143,4 +214,4 @@ function balance(memberId) {
return { unpaid: r4(a.unpaid), paidTotal: r4(a.paidTotal || 0), spentTotal: r4(a.spentTotal || 0), earnedTotal: r4(a.earnedTotal || 0), refTotal: r4(a.refTotal || 0), refSharePct: Number(s.refSharePct) || 0, threshold: Number(s.thresholdPol), history: hist, wallet: a.wallet || null };
}
module.exports = { DEFAULTS, settings, setSettings, ctDay, pool, refuel, refuelsToday, account, chapterDrip, spend, sweep, payable, mark, balance, usdPerPol, r4 };
module.exports = { DEFAULTS, settings, setSettings, ctDay, pool, refuel, refuelsToday, account, chapterDrip, chapterDripGated, quote, settleGrant, kindOf, passActive, fullTier, tierOf, freeShare, dripFor, FREE_NOTE, iapId, payQueued, carrySweep, gp, spend, sweep, payable, mark, balance, usdPerPol, r4 };
+166
View File
@@ -0,0 +1,166 @@
// polgrant.js: the Game Pass bridge to InstantAdPay (GAME-PASS.md section 3a + its "Built" clarifications). The SAME file lives
// in every network game; change it in one place and copy it to the others.
//
// IAP is the single source of truth for the pass and for the account-wide daily caps. Before any POL grant to a signed-in
// player the game asks `grant({ memberId, email, kind, pol, ref })` and pays only what comes back as `allowed`.
// - kind 'daily' = a repeatable reward (a find, a patrol, a gem): what the cap does not allow is DROPPED, never deferred
// - kind 'progress' = a one-time reward (a boss, a sector, a chapter): what the cap does not allow is DEFERRED on IAP and
// paid on a later day inside `allowed` (the answer says `carried`), so nothing is ever lost
// - the same ref twice gets the same answer (IAP is idempotent on ref, `repeat: true`), so a retry can never double-pay
// - FAIL CLOSED: when IAP cannot be reached (network, 5xx, bad JSON, bad auth) the answer is { allowed: 0, retry: true }
// and the game queues the ref: retried every 5 minutes for up to 48 hours, then the admin chat is told once
// - a player who has not linked a wallet has memberId 0 in every hand-off token: send the email too, IAP resolves the account
// (the pass and the caps are per ACCOUNT); `who` below is the member id when > 0, else the lowercased email
//
// Feature switch: GAMEPASS=on|off (default off: every game keeps its current behaviour, so deploying before launch is safe).
// Env: IAP_URL (default https://instantadpay.com). Auth = the game's own shared sign-in secret (its *_SSO_SECRET):
// POST: JSON body with `game: <slug>`, headers X-Game-Ts (ms) and X-Game-Sig = hex HMAC-SHA256(secret, ts + "\n" + rawBody)
// GET /api/partner/player?game=&m=&e=&ts=&sig= with sig = hex HMAC-SHA256(secret, 'player:' + who + ':' + ts)
// GET /api/partner/tournament/pending?game=&ts=&sig= with who = 'tournament'
// The hand-off token carries the flag as claims.gamePass = { active, until }; grant and player answers refresh it.
'use strict';
const crypto = require('crypto');
const PASS_URL = 'https://instantadpay.com/my#games?pass=1';
const RETRY_MS = 5 * 60000, GIVE_UP_MS = 48 * 3600000, PASS_TTL = 10 * 60000;
let cfg = { game: '', secret: '', iap: 'https://instantadpay.com', store: null, notify: null, fetch: null, log: console, queueKey: 'polgrantq', passKey: 'gamepass' };
// use({ game, secret, iap, store: { read, write, update }, notify(kind, payload), fetch? })
function use(o) { cfg = Object.assign(cfg, o || {}); cfg.iap = String(cfg.iap || process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''); return cfg; }
const on = () => String(process.env.GAMEPASS || 'off').trim().toLowerCase() === 'on';
const ctDay = t => new Date(t || Date.now()).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const r4 = n => Math.round(Number(n) * 10000) / 10000;
const doFetch = (u, o) => (cfg.fetch || globalThis.fetch)(u, o);
const ready = () => !!(cfg.store && cfg.secret && String(cfg.secret).length >= 32);
// the account key IAP and this module agree on: the member id when linked, else the email ('' = nobody signed in)
const whoOf = (memberId, email) => Number(memberId) > 0 ? String(Number(memberId)) : String(email || '').trim().toLowerCase();
const hmac = s => crypto.createHmac('sha256', String(cfg.secret)).update(s).digest('hex');
async function post(path, body) {
const raw = JSON.stringify(Object.assign({ game: cfg.game }, body)), ts = String(Date.now());
const r = await doFetch(cfg.iap + path, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game': cfg.game, 'X-Game-Ts': ts, 'X-Game-Sig': hmac(ts + '\n' + raw) }, body: raw, signal: AbortSignal.timeout(6000) });
const text = await r.text(); let json = null; try { json = JSON.parse(text); } catch (e) {}
return { status: r.status, json };
}
async function get(path, who, params) {
const ts = String(Date.now()); const q = new URLSearchParams(Object.assign({ game: cfg.game }, params || {}, { ts, sig: hmac('player:' + who + ':' + ts) }));
const r = await doFetch(cfg.iap + path + '?' + q.toString(), { signal: AbortSignal.timeout(6000) });
const text = await r.text(); let json = null; try { json = JSON.parse(text); } catch (e) {}
return { status: r.status, json };
}
// the one call that matters -> { allowed, deferred, carried, pass, day, capHit, enforced, repeat, lifetimeHit, freeLifetime, waiting, retry: false }
// or { allowed: 0, retry: true, error }. Never throws.
async function grant({ memberId, email, game, kind, pol, ref }) {
const body = { memberId: Number(memberId) || 0, email: String(email || '').trim().toLowerCase() || undefined, game: game || cfg.game, kind: kind === 'daily' ? 'daily' : 'progress', pol: r4(Math.max(0, Number(pol) || 0)), ref: String(ref || '') };
if (!whoOf(body.memberId, body.email) || !body.ref) return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: false, error: 'bad request' };
if (!ready()) return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: true, error: 'polgrant not configured' };
try {
const { status, json } = await post('/api/partner/polgrant', body);
if (status !== 200 || !json || typeof json.allowed !== 'number') return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: true, error: 'http ' + status + (json && json.error ? ': ' + json.error : '') };
const out = { allowed: r4(Math.max(0, json.allowed)), deferred: r4(Math.max(0, Number(json.deferred) || 0)), carried: r4(Math.max(0, Number(json.carried) || 0)), pass: !!(json.pass && (json.pass === true || json.pass.active)), day: json.day || ctDay(), capHit: json.capHit || null, enforced: json.enforced !== false, repeat: !!json.repeat, suspended: !!json.suspended, lifetimeHit: !!json.lifetimeHit, freeLifetime: Number(json.freeLifetime) || 0, waiting: r4(Math.max(0, Number(json.waiting) || 0)), retry: false };
rememberPass(body.memberId, body.email, json.pass, json.passUntil || (json.pass && json.pass.until));
return out;
} catch (e) { return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: true, error: String(e && e.message || e).slice(0, 120) }; }
}
// the game decided not to pay after all (rare): tell IAP so that ref's own share comes back. Best effort.
async function voidGrant({ memberId, email, game, ref }) {
if (!ready() || !whoOf(memberId, email) || !ref) return { ok: false };
try { const { status } = await post('/api/partner/polgrant/void', { memberId: Number(memberId) || 0, email: String(email || '').toLowerCase() || undefined, game: game || cfg.game, ref: String(ref) }); return { ok: status === 200 }; } catch (e) { return { ok: false, error: String(e && e.message || e) }; }
}
// ---- the pass flag: from the sign-in hand-off (claims.gamePass), every grant answer, or a signed GET to IAP ----------------
function passOf(memberId, email) {
const who = whoOf(memberId, email), all = cfg.store && who ? cfg.store.read(cfg.passKey, {}) : {}, p = all[who] || null;
if (!p) return { active: false, until: null, at: 0 };
const active = !!p.active && (!p.until || p.until > Date.now());
return { active, until: p.until || null, at: p.at || 0 };
}
// pass = true/false or { active, until }; until = ms when known
function rememberPass(memberId, email, pass, until) {
const who = whoOf(memberId, email); if (!cfg.store || !who || pass == null) return;
const active = pass === true || !!(pass && pass.active); const u = Number(until || (pass && pass.until)) || null;
cfg.store.update(cfg.passKey, {}, all => { const cur = all[who] || {}; all[who] = { active, until: active ? (u || cur.until || null) : null, at: Date.now() }; return all; });
}
// refresh from IAP when the cached answer is stale; fail-soft (display only, the grant answers are the truth for money)
async function fetchPass(memberId, email) {
const who = whoOf(memberId, email), cur = passOf(memberId, email); if (!ready() || !who) return cur;
if (Date.now() - cur.at < PASS_TTL) return cur;
try {
const { status, json } = await get('/api/partner/player', who, { m: Number(memberId) || 0, e: String(email || '').toLowerCase() });
if (status !== 200 || !json) throw new Error('http ' + status);
if (json.pass != null) rememberPass(memberId, email, json.pass, json.pass && json.pass.until);
return passOf(memberId, email);
} catch (e) { return cur; }
}
// what the lobby shows: { on, active, until, untilText, url }
function view(memberId, email) {
const p = whoOf(memberId, email) ? passOf(memberId, email) : { active: false, until: null };
return { on: on(), active: p.active, until: p.until, untilText: p.until ? new Date(p.until).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric' }) : null, url: PASS_URL };
}
// ---- the player-facing truth for a grant answer ------------------------------------------------------------------------
function note(resp, kind, nominal) {
nominal = r4(nominal);
if (!resp) return null;
if (resp.retry) return 'Your reward is recorded and pays as soon as InstantAdPay confirms it.';
// the free allowance is used up (Marty 2026-11-03): only the Game Pass pays from here, so say so, and what is waiting for them
if (resp.lifetimeHit && !resp.pass) {
const cap = resp.freeLifetime ? r4(resp.freeLifetime) + ' POL' : 'POL';
const wait = kind === 'progress' && resp.waiting > 0 ? ' Your ' + r4(resp.waiting) + ' POL earned since is saved and pays out with the Pass.' : '';
return 'You have used your free ' + cap + ' in the games. Get the Game Pass to keep earning.' + wait;
}
if (kind === 'progress' && resp.deferred > 0) return resp.deferred + ' POL is yours; it pays out over the next days (daily cap).';
if (kind === 'daily' && resp.allowed + 1e-9 < nominal) return resp.pass ? 'Daily cap reached for today.' : 'Daily cap reached for today. Get the Pass for a higher cap.';
return null;
}
// ---- the retry queue (fail closed, never lost): persisted, every 5 minutes, 48 hours, then the admin chat ----------------
function enqueue(item) {
if (!cfg.store) return null;
const row = Object.assign({}, item, { memberId: Number(item.memberId) || 0, email: String(item.email || '').toLowerCase(), ref: String(item.ref), at: item.at || Date.now(), tries: 0, nextAt: Date.now() + RETRY_MS, stuck: false });
row.who = whoOf(row.memberId, row.email);
cfg.store.update(cfg.queueKey, [], q => { if (!q.some(x => (x.who || whoOf(x.memberId, x.email)) === row.who && x.ref === row.ref)) q.push(row); return q; });
return row;
}
const queue = () => cfg.store ? cfg.store.read(cfg.queueKey, []) : [];
const same = (x, memberId, email, ref) => (x.who || whoOf(x.memberId, x.email)) === whoOf(memberId, email) && x.ref === String(ref);
const queued = (memberId, email, ref) => queue().some(x => same(x, memberId, email, ref)); // waiting on IAP: do not ask again
const dequeue = (memberId, email, ref) => cfg.store && cfg.store.update(cfg.queueKey, [], q => q.filter(x => !same(x, memberId, email, ref)));
// pay(item, resp) settles the answer in the game's own ledger. Returns { tried, paid, stuck }.
async function retry(pay, now) {
now = now || Date.now(); const out = { tried: 0, paid: 0, stuck: 0 };
if (!cfg.store || !on()) return out;
for (const item of queue()) {
if (item.stuck || item.nextAt > now) continue;
out.tried++;
const r = await grant({ memberId: item.memberId, email: item.email, kind: item.kind, pol: item.pol, ref: item.ref });
if (r.retry) {
const stuck = now - item.at >= GIVE_UP_MS;
cfg.store.update(cfg.queueKey, [], q => { const x = q.find(y => same(y, item.memberId, item.email, item.ref)); if (x) { x.tries = (x.tries || 0) + 1; x.nextAt = now + RETRY_MS; x.lastError = r.error || null; if (stuck) x.stuck = true; } return q; });
if (stuck) { out.stuck++; if (cfg.notify) { try { await cfg.notify('gpstuck', { memberId: item.memberId, email: item.email, ref: item.ref, pol: item.pol, kind: item.kind, since: item.at, error: r.error || null }); } catch (e) {} } }
continue;
}
dequeue(item.memberId, item.email, item.ref);
try { await pay(item, r); out.paid++; } catch (e) { if (cfg.log) cfg.log.error('polgrant pay', item.ref, e && e.message); }
}
return out;
}
let timer = null;
function startRetry(pay, everyMs) { if (timer) return timer; timer = setInterval(() => { retry(pay).catch(e => cfg.log && cfg.log.error('polgrant retry', e && e.message)); }, everyMs || RETRY_MS); if (timer.unref) timer.unref(); return timer; }
function stopRetry() { if (timer) clearInterval(timer); timer = null; }
// ---- the weekly Pass Tournament prize seam (3a item 8): IAP records the winners, a game's faucet pays them ------------------
// -> { ok, rows: [{ id?, week, place, email, memberId, wallet, pol }] } or { ok: false, retry: true, error }
async function tournamentPending() {
if (!ready()) return { ok: false, retry: true, error: 'polgrant not configured', rows: [] };
try { const { status, json } = await get('/api/partner/tournament/pending', 'tournament', {}); if (status !== 200 || !json) return { ok: false, retry: true, error: 'http ' + status, rows: [] }; return { ok: true, rows: Array.isArray(json.rows) ? json.rows : Array.isArray(json) ? json : [] }; }
catch (e) { return { ok: false, retry: true, error: String(e && e.message || e).slice(0, 120), rows: [] }; }
}
// the row leaves IAP's unpaid list once the game reports the tx (sends id when the row has one, and week + place always)
async function tournamentPaid(row, tx) {
if (!ready()) return { ok: false, error: 'polgrant not configured' };
try { const { status, json } = await post('/api/partner/tournament/paid', { id: row.id, week: row.week, place: row.place, memberId: row.memberId, email: row.email, tx }); return { ok: status === 200 && !(json && json.error), status, error: json && json.error }; }
catch (e) { return { ok: false, error: String(e && e.message || e).slice(0, 120) }; }
}
module.exports = { use, on, whoOf, grant, voidGrant, passOf, rememberPass, fetchPass, view, note, enqueue, queue, queued, dequeue, retry, startRetry, stopRetry, tournamentPending, tournamentPaid, PASS_URL, RETRY_MS, GIVE_UP_MS, ctDay, r4, _cfg: () => cfg };
+54
View File
@@ -0,0 +1,54 @@
// Paid-traffic source tracking (Marty, 2026-10-03: AdsTerra/BeMob test into Drip Runner). A landing URL carries
// ?src=<source>&cid=<tracker click id>; we keep them in a first-party cookie (dr.src, 30 days, last paid touch wins)
// and count, per Central day and source: landing visits, guests started, runs started (and distinct players), sign-ins
// and NEW InstantAdPay accounts. A new account fires the tracker postback once (DR_POSTBACK_URL, {cid} {txid} tokens).
const crypto = require('crypto');
const store = require('./store');
const COOKIE = 'dr.src';
const clean = (v, n) => String(v || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, n);
const ctDay = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
function fromQuery(u) { // -> { src, cid } or null
const src = clean(u.searchParams.get('src') || u.searchParams.get('utm_source'), 30);
if (!src) return null;
const cid = String(u.searchParams.get('cid') || u.searchParams.get('clickid') || '').replace(/[^A-Za-z0-9_.-]/g, '').slice(0, 80);
return { src, cid };
}
function cookieHeader(t, isProd) { return COOKIE + '=' + encodeURIComponent(t.src + '|' + (t.cid || '') + '|' + Date.now()) + '; Path=/; Max-Age=' + 30 * 86400 + '; SameSite=Lax' + (isProd ? '; Secure' : ''); }
function fromRequest(req) {
const m = /(?:^|;\s*)dr\.src=([^;]+)/.exec(req.headers.cookie || ''); if (!m) return null;
const [src, cid, ts] = decodeURIComponent(m[1]).split('|');
return clean(src, 30) ? { src: clean(src, 30), cid: String(cid || '').replace(/[^A-Za-z0-9_.-]/g, '').slice(0, 80), ts: Number(ts) || 0 } : null;
}
function bump(src, field, id) {
const day = ctDay();
store.update('srcstats', {}, all => {
const d = all[day] = all[day] || {}; const r = d[src] = d[src] || { visits: 0, guests: 0, runs: 0, players: [], signins: 0, signups: 0 };
r[field] = (r[field] || 0) + 1;
if (id != null && !r.players.includes(String(id)) && r.players.length < 5000) r.players.push(String(id));
const days = Object.keys(all).sort(); while (days.length > 90) delete all[days.shift()];
return all;
});
}
function summary(days) {
const all = store.read('srcstats', {}); const keys = Object.keys(all).sort().slice(-(days || 30));
const rows = []; const tot = {};
for (const day of keys) for (const [src, r] of Object.entries(all[day])) {
rows.push({ day, src, visits: r.visits || 0, guests: r.guests || 0, runs: r.runs || 0, players: (r.players || []).length, signins: r.signins || 0, signups: r.signups || 0 });
const t = tot[src] = tot[src] || { src, visits: 0, guests: 0, runs: 0, signins: 0, signups: 0 };
for (const k of ['visits', 'guests', 'runs', 'signins', 'signups']) t[k] += r[k] || 0;
}
return { rows: rows.reverse(), totals: Object.values(tot) };
}
// the tracker conversion: once per click id, only for a NEW InstantAdPay account
async function postback(t, memberId) {
const tpl = String(process.env.DR_POSTBACK_URL || '').trim();
if (!tpl || !t || !t.cid) return false;
const done = store.read('postbacks', {}); if (done[t.cid]) return false;
const txid = crypto.createHash('sha256').update(String(memberId)).digest('hex').slice(0, 16);
const url = tpl.replace(/\{cid\}/g, encodeURIComponent(t.cid)).replace(/\{txid\}/g, txid).replace(/\{src\}/g, encodeURIComponent(t.src));
store.update('postbacks', {}, d => { d[t.cid] = { at: Date.now(), src: t.src, member: String(memberId) }; return d; });
try { const r = await fetch(url, { signal: AbortSignal.timeout(8000) }); console.log('postback', t.src, r.status); return r.ok; }
catch (e) { console.warn('postback failed', t.src, e.message); return false; }
}
module.exports = { fromQuery, fromRequest, cookieHeader, bump, summary, postback, COOKIE };
+60
View File
@@ -0,0 +1,60 @@
// Member welcome offer (Marty, 2026-10-05): turn players into InstantAdPay members through the $5 package.
//
// After a chapter clear, a signed-in player with no InstantAdPay member id yet (the hand-off carried memberId 0, so they
// play on the negative email id) gets one card a Central day: "Become an InstantAdPay member". Never a guest, never
// during a run. InstantAdPay owns the purchase and its bonus credits; the bonus number comes from its public endpoint
// (cached ten minutes) and the offer stays off while InstantAdPay says it is off. If the endpoint cannot be read the
// card still shows, without a number.
//
// The perk here: the first time a member (memberId > 0) comes through the hand-off, one free hangar upgrade. It is a
// token on the player (freeUpgrades) that makes the next hangar purchase cost nothing, drips or POL. A free POL item
// moves no POL: nothing leaves the pool and nothing is paid out, so Marty's "no POL the game did not earn" rule holds.
//
// Player record fields: starterShown (the Central day the card last showed), perkAt (ms, granted once, never again),
// freeUpgrades (tokens left), perkNotice (the one-time lobby message is still to be shown).
'use strict';
const game = require('./game');
const ledger = require('./ledger');
const IAP = () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
const PERK = 'a free hangar upgrade';
const NOTICE = 'Member perk: a free hangar upgrade. Thanks for joining InstantAdPay!';
let cache = { at: 0, v: null };
// InstantAdPay's public offer numbers: { on, bonus } or null when unreadable (a failure is remembered for a minute)
async function publicOffer() {
if (Date.now() - cache.at < 10 * 60000) return cache.v;
try {
const r = await fetch(IAP() + '/api/starter/public', { signal: AbortSignal.timeout(5000) }); if (!r.ok) throw new Error('http ' + r.status);
const j = await r.json(); const b = Number(j.bonus);
cache = { at: Date.now(), v: { on: j.on !== false, bonus: isFinite(b) && b > 0 ? Math.round(b) : null } };
} catch (e) { cache = { at: Date.now() - 9 * 60000, v: null }; }
return cache.v;
}
// the card for this clear, or null. Counts as shown the moment it is handed out.
async function offerFor(me) {
if (!me || me.guest || Number(me.memberId) > 0) return null;
const p = game.player(me.memberId); const today = ledger.ctDay();
if (!p || p.starterShown === today) return null;
const pub = await publicOffer();
if (pub && pub.on === false) return null;
let fresh = false; game.updPlayer(me.memberId, x => { if (x.starterShown !== today) { x.starterShown = today; fresh = true; } });
if (!fresh) return null;
return { bonus: pub ? pub.bonus : null, perk: PERK, url: IAP() + '/my?from=driprunner#buy' };
}
// the hand-off: a member's first visit as a member gets the free upgrade, once per account
function grantPerk(memberId) {
if (!(Number(memberId) > 0)) return false; let granted = false;
game.updPlayer(memberId, x => { if (!x.perkAt) { x.perkAt = Date.now(); x.freeUpgrades = (Number(x.freeUpgrades) || 0) + 1; x.perkNotice = true; granted = true; } });
return granted;
}
// the one-time lobby message: handed out once, then cleared
function takeNotice(memberId) {
const p = game.player(memberId); if (!p || !p.perkNotice) return null;
game.updPlayer(memberId, x => { delete x.perkNotice; });
return NOTICE;
}
module.exports = { publicOffer, offerFor, grantPerk, takeNotice, PERK };
+1 -1
View File
@@ -7,7 +7,7 @@
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js",
"test": "node test/run.js"
"test": "node test/gamepass.js && node test/run.js"
},
"engines": { "node": ">=20" },
"dependencies": { "ethers": "^6.13.0" }
+2 -1
View File
@@ -23,6 +23,7 @@
<form id="settings" class="card" style="max-width:none">
<div class="row">
<div><label>Drip per first clear (POL)</label><input name="dripPol" type="number" step="0.001" min="0"></div>
<div><label>Free account share of the drip (%, Game Pass = 100)</label><input name="freeSharePct" type="number" step="1" min="0" max="100"></div>
<div><label>Daily cap on drips (POL)</label><input name="dailyCapPol" type="number" step="0.01" min="0"></div>
<div><label>Payout threshold (POL)</label><input name="thresholdPol" type="number" step="0.01" min="0"></div>
<div><label>Seed float (POL, on purpose)</label><input name="seedPol" type="number" step="0.01" min="0"></div>
@@ -51,6 +52,6 @@
<h2>Payouts</h2><div class="scroll"><table id="payouts"></table></div>
<h2>Recent runs</h2><div class="scroll"><table id="runs"></table></div>
</div>
<script src="/admin.js"></script>
<script src="/admin.js?v=20261102"></script>
</body>
</html>
+2 -2
View File
@@ -20,7 +20,7 @@ function load() {
$('pool').innerHTML = stat('Available now', f4(p.available) + ' POL') + stat('In from refuels', f4(p.in)) + stat('Back from spends', f4(p.spends)) + stat('Out as drips', f4(p.out)) + stat('Seed float', f4(p.seed)) + stat('Granted today', f4(p.grantedToday) + ' / ' + f4(p.dailyCapPol));
var f = d.faucet; $('faucet').innerHTML = stat('Mode', f.enabled ? (f.dryRun ? 'DRY RUN' : 'LIVE') : 'off') + stat('Wallet', f.address ? f.address.slice(0, 8) + '…' + f.address.slice(-6) : '–') + stat('Balance', f.balance != null ? f4(f.balance) + ' POL' : '–') + stat('Last check', ct(f.checkedAt) || '–') + stat('Last tick', f.lastTick ? esc(JSON.stringify(f.lastTick)) : '–');
var s = d.settings, form = $('settings');
['refSharePct', 'dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { form.elements[k].value = s[k]; });
['refSharePct', 'dripPol', 'freeSharePct', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { form.elements[k].value = s[k]; });
form.elements.item_shield.value = s.itemPol.shield; form.elements.item_slow.value = s.itemPol.slow; form.elements.item_magnet.value = s.itemDrips.magnet; form.elements.item_ship.value = s.itemDrips.ship;
form.elements.testers.value = (s.testers || []).join('\n'); form.elements.trial.value = s.trial === false ? 'off' : 'on';
table('players', [['Member', function (r) { return '#' + r.memberId + (r.username ? ' @' + esc(r.username) : '') + '<br><span class="muted">' + esc(r.email || '') + '</span>'; }], ['Wallet', function (r) { return r.wallet ? r.wallet.slice(0, 6) + '…' + r.wallet.slice(-4) : '<span style="color:var(--sig)">none</span>'; }], ['Chapter', 'chapter', 1], ['Drips', 'bank', 1], ['Best', 'best', 1], ['Runs', 'runs', 1], ['Armed', function (r) { return Object.keys(r.items || {}).join(', '); }], ['Last seen', function (r) { return ct(r.lastSeen); }]], d.players);
@@ -33,7 +33,7 @@ function load() {
}
$('settings').addEventListener('submit', function (e) {
e.preventDefault(); var f = e.target.elements; var body = {};
['refSharePct', 'dripPol', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { body[k] = f[k].value; });
['refSharePct', 'dripPol', 'freeSharePct', 'dailyCapPol', 'thresholdPol', 'seedPol', 'poolSharePct', 'creditsPerVisit', 'usdPerCredit', 'usdPerPolFallback', 'lowBalancePol', 'signups'].forEach(function (k) { body[k] = f[k].value; });
body.itemPol = { shield: Number(f.item_shield.value), slow: Number(f.item_slow.value) }; body.itemDrips = { magnet: Number(f.item_magnet.value), ship: Number(f.item_ship.value) };
body.trial = f.trial.value; body.testers = f.testers.value.split(/\r?\n/).map(function (x) { return x.trim(); }).filter(Boolean);
api('/api/admin/settings', body).then(function (r) { $('saveOut').textContent = r.ok ? 'Saved.' : (r.error || 'Failed'); load(); });
+4 -4
View File
@@ -6,7 +6,7 @@
<title>Drip Runner · hop the network, get paid in POL</title>
<meta name="description" content="A fast runner game for InstantAdPay members. Clear chapters, refuel on member pages, collect POL in your wallet.">
<meta property="og:title" content="Drip Runner: hop the network, get paid in POL">
<meta property="og:description" content="Earn free POL: fly your courier through the network, clear chapters, and get paid straight to your wallet.">
<meta property="og:description" content="Play free. Fly your courier through the network, clear chapters, and sign in with InstantAdPay to earn POL on every first clear. The Game Pass pays the full reward, straight to your wallet.">
<meta property="og:image" content="https://driprunner.app/og-driprunner.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
@@ -45,7 +45,7 @@
<div>
<p class="logo" style="font-size:22px">Drip<span>Runner</span></p>
<h1>Hop the network.<br><em>Get paid in POL.</em></h1>
<p class="lead">A fast little runner game for InstantAdPay members. Grab gold drips, dodge the bots, clear chapters. Your first clear of every chapter drips POL into your game balance, and it pays out to the wallet on your InstantAdPay account.</p>
<p class="lead">A fast little runner game for InstantAdPay members. Grab gold drips, dodge the bots, clear chapters. Play free as a guest for the score; sign in with a free InstantAdPay account and your first clear of every chapter drips a taste of POL into your game balance; Game Pass holders earn the full drip. It pays out to the wallet on your InstantAdPay account.</p>
<div class="cta">
<a class="btn" href="/signin">Play with InstantAdPay</a>
<a class="btn ghost" href="/play">Try a run first</a>
@@ -69,7 +69,7 @@
<h2>How it plays</h2>
<div class="cols">
<div class="card"><span class="step">1</span><h3>Tap to hop</h3><p>The courier drops when you let go and hops when you tap. Gold drips are your score and top up your fuel. Magenta bots end the run, and from chapter 2 you thread orange firewalls.</p></div>
<div class="card"><span class="step">2</span><h3>Clear chapters</h3><p>Each chapter has a drip goal for one run. Clear it and you move up. The first clear of every chapter pays a POL drip into your game balance.</p></div>
<div class="card"><span class="step">2</span><h3>Clear chapters</h3><p>Each chapter has a drip goal for one run. Clear it and you move up. Signed in, the first clear of every chapter pays a POL drip into your game balance: a free InstantAdPay account earns a taste of it, Game Pass holders earn the full drip. Guest runs earn no POL, but your progress follows you when you sign in.</p></div>
<div class="card"><span class="step">3</span><h3>Refuel, don't restart</h3><p>Out of fuel or hit by a bot? Refuel with a short visit to a member's page or a member video. Your run picks up exactly where it stopped.</p></div>
</div>
@@ -93,7 +93,7 @@
<a class="btn" href="/signin">Play with InstantAdPay</a>
<a class="btn ghost" href="/play">Try a run first</a>
</div>
<p class="fine">Drip Runner pays small amounts of POL for play that the game can verify. Amounts depend on the pool, which is funded by the ad visits players make, and can change. Nothing here is a promise of income. One account per person. Part of the Crypto Team Build Network, alongside InstantAdPay and PolHunter.</p>
<p class="fine">Drip Runner pays small amounts of POL for play that the game can verify. Amounts depend on the pool, which is funded by the ad visits players make, and can change. Nothing here is a promise of income. One account per person. Drip Runner is part of the InstantAdPay network, the Polygon wing of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</p>
</div>
<script src="/landing.js"></script>
</body>
+25 -12
View File
@@ -1,12 +1,25 @@
(function () {
'use strict';
var $ = function (id) { return document.getElementById(id); };
var n = function (v, d) { return Number(v || 0).toLocaleString('en-US', { maximumFractionDigits: d || 0 }); };
fetch('/api/public/stats').then(function (r) { return r.json(); }).then(function (s) {
$('sPlayers').textContent = n(s.players); $('sRefuels').textContent = n(s.refuels); $('sDrips').textContent = n(s.chapterDrips); $('sPaid').textContent = n(s.polPaid, 3);
if (s.thresholdPol) $('sThreshold').textContent = n(s.thresholdPol, 2);
if (s.refSharePct) $('sRef').textContent = s.refSharePct + ' percent';
document.querySelectorAll('.sRefPct').forEach(function (e) { if (s.refSharePct) e.textContent = s.refSharePct + ' percent'; });
document.querySelectorAll('.sThresh').forEach(function (e) { if (s.thresholdPol) e.textContent = n(s.thresholdPol, 2); });
}).catch(function () { $('stats').hidden = true; });
})();
(function () {
'use strict';
var $ = function (id) { return document.getElementById(id); };
var n = function (v, d) { return Number(v || 0).toLocaleString('en-US', { maximumFractionDigits: d || 0 }); };
fetch('/api/public/stats').then(function (r) { return r.json(); }).then(function (s) {
$('sPlayers').textContent = n(s.players); $('sRefuels').textContent = n(s.refuels); $('sDrips').textContent = n(s.chapterDrips); $('sPaid').textContent = n(s.polPaid, 3);
if (s.thresholdPol) $('sThreshold').textContent = n(s.thresholdPol, 2);
if (s.refSharePct) $('sRef').textContent = s.refSharePct + ' percent';
document.querySelectorAll('.sRefPct').forEach(function (e) { if (s.refSharePct) e.textContent = s.refSharePct + ' percent'; });
document.querySelectorAll('.sThresh').forEach(function (e) { if (s.thresholdPol) e.textContent = n(s.thresholdPol, 2); });
}).catch(function () { $('stats').hidden = true; });
})();
// shown inside someone else's frame (traffic exchanges, rotators; 2026-10-03): the game keeps progress and the sharer's
// referral in cookies that browsers drop inside a frame, so play and sign-in open in a new tab, carrying the share link
(function () {
var framed = false; try { framed = window.top !== window.self; } catch (e) { framed = true; }
if (!framed) return;
var q = new URLSearchParams(location.search), r = String(q.get('r') || q.get('ref') || '').replace(/[^A-Za-z0-9_.-]/g, '').slice(0, 40);
document.querySelectorAll('a[href]').forEach(function (a) {
if (a.getAttribute('href').charAt(0) === '#') return;
if (r && /^\/(play|signin)$/.test(a.pathname) && a.host === location.host) a.href = '/r/' + encodeURIComponent(r);
a.target = '_blank'; a.rel = 'noopener';
});
})();
+210 -169
View File
@@ -1,169 +1,210 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover,user-scalable=no">
<meta name="robots" content="noindex,nofollow">
<title>Drip Runner</title>
<meta property="og:title" content="Drip Runner: hop the network, get paid in POL">
<meta property="og:description" content="A fast little runner game for InstantAdPay members. Clear chapters, refuel on sponsor pages, collect POL.">
<meta property="og:image" content="https://driprunner.app/badges/ch1.jpg">
<meta name="twitter:card" content="summary_large_image">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Orbitron:wght@600;800;900&family=Manrope:wght@400;600;800&family=JetBrains+Mono:wght@500;700&display=swap">
<style>
:root{color-scheme:dark;--page:#050912;--ink:#EEF3FA;--ink2:#AFC0D8;--muted:#6E82A3;--cyan:#22D3EE;--cyan2:#8FF0FF;--gold:#FFC24B;--gold2:#FFE9A8;--bot:#FF3B7A;--sig:#FF6A1A;--ok:#34D399;--violet:#8B5CF6;--panel:#0E172D;--panel2:#141F3A;--line:#24365F;
--display:"Orbitron","Segoe UI",system-ui,sans-serif;--body:"Manrope","Segoe UI",system-ui,sans-serif;--mono:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{height:100%}
body{margin:0;background:var(--page);color:var(--ink);font:15px/1.5 var(--body);overflow:hidden;background-image:radial-gradient(ellipse 60% 50% at 50% 0%,rgba(34,211,238,.10),transparent 60%),radial-gradient(ellipse 40% 40% at 90% 100%,rgba(255,106,26,.08),transparent 60%)}
.frame{position:fixed;inset:0;display:grid;place-items:center}
.phone{position:relative;width:100%;height:100%;background:#050912;overflow:hidden}
@media (min-width:700px) and (min-height:700px){.frame{padding:16px}.phone{max-width:430px;max-height:900px;border:3px solid #1A2540;border-radius:40px;box-shadow:0 40px 90px -30px rgba(0,0,0,.95),0 0 80px -20px rgba(34,211,238,.25)}}
canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none}
.hud{position:absolute;left:0;right:0;top:0;padding:calc(12px + env(safe-area-inset-top,0px)) 14px 0;display:grid;grid-template-columns:1fr auto 1fr;align-items:start;gap:10px;pointer-events:none;z-index:4;opacity:0;transition:opacity .3s}
.hud.on{opacity:1}
.hud .st{font:700 20px var(--display);letter-spacing:.04em;line-height:1;font-variant-numeric:tabular-nums}
.hud .st small{display:block;font:700 9px var(--body);letter-spacing:.16em;text-transform:uppercase;color:var(--muted);margin-bottom:3px}
.hud .st.gold{color:var(--gold);text-shadow:0 0 14px rgba(255,194,75,.6)}.hud .st.cy{color:var(--cyan2);text-align:center;text-shadow:0 0 14px rgba(34,211,238,.6)}.hud .st.r{text-align:right;color:var(--ink2)}
.fuel{grid-column:1/-1;margin-top:6px;height:8px;border-radius:4px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.12);overflow:hidden}
.fuel i{display:block;height:100%;width:100%;border-radius:4px;background:linear-gradient(90deg,var(--sig),var(--gold) 40%,var(--cyan));box-shadow:0 0 12px rgba(34,211,238,.5);transition:width .15s linear}
.fuel.low i{background:linear-gradient(90deg,var(--bot),var(--sig));animation:blink .5s steps(2) infinite}
@keyframes blink{50%{opacity:.35}}
.goal{grid-column:1/-1;font:600 11px var(--body);color:var(--ink2);display:flex;justify-content:space-between;margin-top:2px}.goal b{color:var(--gold)}
.pill{position:absolute;left:50%;transform:translateX(-50%);top:50%;z-index:5;pointer-events:none;font:800 22px var(--display);letter-spacing:.1em;text-transform:uppercase;color:#fff;text-shadow:0 0 20px var(--cyan);opacity:0;transition:opacity .2s;white-space:nowrap}
.pill.on{opacity:1;animation:pop .9s ease-out}
@keyframes pop{0%{transform:translate(-50%,10px) scale(.7)}30%{transform:translate(-50%,0) scale(1.1)}100%{transform:translate(-50%,-30px) scale(1)}}
.mute{position:absolute;right:12px;bottom:calc(12px + env(safe-area-inset-bottom,0px));z-index:6;width:38px;height:38px;border-radius:50%;border:1px solid var(--line);background:rgba(14,23,45,.7);color:var(--ink2);font:700 13px var(--mono);display:grid;place-items:center;cursor:pointer}
.ov{position:absolute;inset:0;z-index:8;display:flex;flex-direction:column;justify-content:center;padding:calc(20px + env(safe-area-inset-top,0px)) 18px calc(20px + env(safe-area-inset-bottom,0px));background:rgba(5,9,18,.55);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px)}
.ov[hidden]{display:none!important}
/* 2026-10-01 (Hugh, iPhone Safari): the lobby is taller than a phone with the browser bar showing, and .phone clips overflow, so the last button sat under the toolbar. Overlays scroll, keep a bottom gap, and center only when they fit. */
.ov{overflow-y:auto;-webkit-overflow-scrolling:touch;overscroll-behavior:contain;touch-action:pan-y;justify-content:safe center}
.ov.lobby{justify-content:space-between;padding-bottom:calc(28px + env(safe-area-inset-bottom,0px))}
@media (max-height:760px){.logo{margin-top:3vh}}
.ov.lobby{justify-content:space-between;background:linear-gradient(180deg,rgba(5,9,18,.15),rgba(5,9,18,.75) 60%,#050912)}
.logo{font:900 42px/1 var(--display);letter-spacing:.06em;text-transform:uppercase;text-align:center;margin-top:10vh;background:linear-gradient(180deg,#fff 0%,var(--cyan2) 45%,var(--cyan) 60%,#0EA5C9 100%);-webkit-background-clip:text;background-clip:text;color:transparent;filter:drop-shadow(0 0 22px rgba(34,211,238,.55));animation:hum 3s ease-in-out infinite}
.logo span{display:block;background:linear-gradient(180deg,var(--gold2),var(--gold) 55%,#E08A00);-webkit-background-clip:text;background-clip:text;color:transparent;filter:drop-shadow(0 0 22px rgba(255,194,75,.5))}
@keyframes hum{50%{filter:drop-shadow(0 0 34px rgba(34,211,238,.8))}}
.tag{text-align:center;color:var(--ink2);font-size:13px;margin-top:10px}
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:14px 0 10px}
.stat{background:linear-gradient(180deg,rgba(20,31,58,.9),rgba(14,23,45,.9));border:1px solid var(--line);border-radius:12px;padding:10px 8px;text-align:center;position:relative;overflow:hidden}
.stat small{display:block;font:700 9px var(--body);letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}.stat b{font:800 20px var(--display);font-variant-numeric:tabular-nums}
.stat b.gold{color:var(--gold)}.stat b.cy{color:var(--cyan2)}.stat b.ok{color:var(--ok)}
.pool{font:600 11px var(--mono);color:var(--muted);text-align:center;margin-bottom:6px}.pool b{color:var(--ink2)}
.btn{display:block;width:100%;margin-top:10px;padding:14px 12px;border-radius:12px;border:0;cursor:pointer;font:800 16px var(--display);letter-spacing:.12em;text-transform:uppercase;color:#07101F;position:relative;background:linear-gradient(180deg,var(--cyan2),var(--cyan) 55%,#0EA5C9);box-shadow:0 0 0 1px rgba(255,255,255,.25) inset,0 8px 28px -8px rgba(34,211,238,.8)}
.btn:active{transform:translateY(1px)}
.btn.sig{background:linear-gradient(180deg,#FFB088,var(--sig) 55%,#D44E00);color:#fff;box-shadow:0 0 0 1px rgba(255,255,255,.2) inset,0 8px 28px -8px rgba(255,106,26,.8)}
.btn.gold{background:linear-gradient(180deg,var(--gold2),var(--gold) 55%,#E08A00);box-shadow:0 0 0 1px rgba(255,255,255,.25) inset,0 8px 28px -8px rgba(255,194,75,.8)}
.btn.ghost{background:rgba(14,23,45,.7);border:1px solid var(--line);color:var(--ink2);font-size:13px;padding:11px;box-shadow:none}
.btn[disabled]{opacity:.45;pointer-events:none}
.row2{display:grid;grid-template-columns:1fr 1fr;gap:10px}.row2 .btn{margin-top:10px}
.member{margin-top:12px;text-align:center;font:600 11px var(--mono);color:var(--muted)}.member i{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--ok);box-shadow:0 0 8px var(--ok);margin-right:6px;vertical-align:1px}.member i.no{background:var(--sig);box-shadow:0 0 8px var(--sig)}
.card{background:linear-gradient(180deg,rgba(20,31,58,.96),rgba(14,23,45,.98));border:1px solid var(--line);border-radius:18px;padding:22px 18px;text-align:center;box-shadow:0 30px 70px -20px rgba(0,0,0,.9),0 0 60px -20px rgba(34,211,238,.35);position:relative;overflow:hidden}
.card:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:linear-gradient(90deg,transparent,var(--cyan),var(--gold),transparent)}
.card .eyebrow{font:700 10px var(--body);letter-spacing:.2em;text-transform:uppercase;color:var(--cyan)}
.card h2{font:900 26px/1.05 var(--display);letter-spacing:.05em;text-transform:uppercase;margin:8px 0 4px;text-wrap:balance}
.card .big{font:900 46px/1 var(--display);margin:12px 0 2px;font-variant-numeric:tabular-nums;background:linear-gradient(180deg,var(--gold2),var(--gold) 60%,#E08A00);-webkit-background-clip:text;background-clip:text;color:transparent;filter:drop-shadow(0 0 18px rgba(255,194,75,.5))}
.card .big small{font:700 13px var(--mono);color:var(--ink2);margin-left:6px;-webkit-text-fill-color:var(--ink2)}
.card .big.dim{opacity:.3}
.card p{font-size:13px;color:var(--ink2);margin:6px 0 0}
.chip{display:inline-block;font:700 10px var(--mono);letter-spacing:.06em;text-transform:uppercase;padding:3px 8px;border-radius:5px;border:1px solid var(--line);color:var(--ink2);margin-top:10px}
.chip.ok{color:var(--ok);border-color:rgba(52,211,153,.4);background:rgba(52,211,153,.08)}.chip.sig{color:var(--sig);border-color:rgba(255,106,26,.4);background:rgba(255,106,26,.08)}.chip.gold{color:var(--gold);border-color:rgba(255,194,75,.4);background:rgba(255,194,75,.08)}
.sheet{background:linear-gradient(180deg,rgba(20,31,58,.97),rgba(14,23,45,.98));border:1px solid var(--line);border-radius:18px;padding:16px 14px;max-height:100%;display:flex;flex-direction:column;gap:8px;overflow:auto}
.sheet h3{font:900 18px var(--display);letter-spacing:.1em;text-transform:uppercase;margin:2px 2px 4px;display:flex;justify-content:space-between;align-items:center}.sheet h3 .bal{font:700 11px var(--mono);color:var(--gold)}
.item{display:grid;grid-template-columns:46px 1fr auto;gap:10px;align-items:center;background:rgba(5,9,18,.5);border:1px solid var(--line);border-radius:12px;padding:8px 10px;text-align:left}
.item.owned{border-color:rgba(52,211,153,.45)}
.item .ic{width:46px;height:46px;border-radius:11px;background:radial-gradient(circle at 30% 30%,#2A4A7A,#0E1730);display:grid;place-items:center}
.item .ic i{display:block;width:28px;height:13px;border-radius:7px;background:#F3F6FB;box-shadow:0 0 12px var(--cyan)}
.item .ic.gold i{background:var(--gold);width:16px;height:16px;border-radius:50%;box-shadow:0 0 12px var(--gold)}
.item .ic.sig i{background:var(--sig);width:18px;height:18px;border-radius:5px;transform:rotate(45deg);box-shadow:0 0 12px var(--sig)}
.item .ic.vi i{background:var(--violet);width:18px;height:18px;border-radius:50% 50% 4px 4px;box-shadow:0 0 12px var(--violet)}
.item b{font-size:13px;display:block}.item small{color:var(--muted);font-size:11px;display:block}
.buy{font:800 11px var(--mono);white-space:nowrap;padding:8px 10px;border-radius:9px;border:1px solid rgba(255,194,75,.45);background:rgba(255,194,75,.1);color:var(--gold);cursor:pointer}
.buy.pol{border-color:rgba(52,211,153,.45);background:rgba(52,211,153,.1);color:var(--ok)}
.buy.own{border-color:rgba(52,211,153,.45);background:rgba(52,211,153,.1);color:var(--ok);pointer-events:none}
.buy.no{opacity:.4;pointer-events:none}
.led{display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--ink2);padding:7px 2px;border-top:1px solid var(--line)}.led:first-child{border-top:0}.led .m{font:700 12px var(--mono);color:var(--gold);white-space:nowrap}.led .m.ok{color:var(--ok)}.led .m.neg{color:var(--sig)}.led a{color:var(--cyan2)}
.prog{height:8px;background:rgba(255,255,255,.08);border-radius:4px;overflow:hidden;margin-top:8px}.prog i{display:block;height:100%;background:linear-gradient(90deg,var(--cyan),var(--gold));box-shadow:0 0 10px rgba(255,194,75,.5)}
.tip{margin:12px 0 0;padding:10px 12px;border-radius:10px;background:rgba(34,211,238,.07);border:1px solid rgba(34,211,238,.25);font-size:12px;line-height:1.45;color:var(--ink2);text-align:left}.tip b{display:block;font:700 9px var(--body);letter-spacing:.16em;text-transform:uppercase;color:var(--cyan);margin-bottom:3px}
.shrHow{margin:6px 0 8px;font-size:11px;line-height:1.45;color:var(--ink2)}.shrHow a{color:inherit}
.shr{margin-top:10px;padding:10px 12px;border-radius:10px;border:1px solid var(--line);background:rgba(14,23,45,.6);font-size:11px;color:var(--muted);text-align:center}.shr b{color:var(--gold)}.shr .btn{margin-top:8px}
.toast{position:absolute;left:50%;bottom:calc(70px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);z-index:20;background:var(--panel2);border:1px solid var(--line);color:var(--ink);font-size:12px;padding:8px 12px;border-radius:10px;opacity:0;transition:opacity .2s;pointer-events:none;max-width:92%;text-align:center}
.toast.on{opacity:1}
.tapdesk{position:absolute;bottom:calc(14px + env(safe-area-inset-bottom,0px));left:14px;z-index:5;font:600 10px var(--body);letter-spacing:.14em;text-transform:uppercase;color:var(--muted);pointer-events:none}
</style>
</head>
<body>
<div class="frame"><div class="phone" id="phone">
<canvas id="game"></canvas>
<div class="hud" id="hud">
<div class="st gold"><small>Drips</small><span id="hDrips">0</span></div>
<div class="st cy"><small>Chapter</small><span id="hChap">1</span></div>
<div class="st r"><small>Best</small><span id="hBest">0</span></div>
<div class="fuel" id="fuel"><i id="fuelBar"></i></div>
<div class="goal"><span>Chapter goal</span><span><b id="hGoalN">0</b> / <span id="hGoal">20</span> drips</span></div>
</div>
<div class="pill" id="pill"></div>
<div class="tapdesk" id="tapdesk" hidden>tap · click · space</div>
<button class="mute" id="mute" type="button" title="Sound">♪</button>
<div class="toast" id="toast"></div>
<div class="ov lobby" id="ovLobby" hidden>
<div><div class="logo">Drip<span>Runner</span></div><div class="tag">Hop the network. Bank the drips. Get paid in POL.</div></div>
<div>
<div class="stats">
<div class="stat"><small>Chapter</small><b class="cy" id="lChap">1</b></div>
<div class="stat"><small>Drips</small><b class="gold" id="lDrips">0</b></div>
<div class="stat"><small>Balance</small><b class="ok" id="lPol">0.000</b></div>
</div>
<div class="pool" id="lPool"></div>
<div class="tip" id="lTip" hidden></div>
<button class="btn" id="bPlay" type="button">Play</button>
<div class="row2"><button class="btn ghost" id="bHangar" type="button">Hangar</button><button class="btn ghost" id="bBalance" type="button">Balance</button></div>
<a class="btn gold" id="bLevel" href="https://instantadpay.com/my#buy" style="text-decoration:none;text-align:center;font-size:13px;padding:11px">Level up on InstantAdPay</a>
<a class="btn" id="bSignin" href="#" hidden style="text-decoration:none;text-align:center">Sign in to keep progress</a>
<div class="shr" id="lShare" hidden><div id="lShareStat"></div><p class="shrHow" id="lShareHow"></p><button class="btn ghost" id="bShare" type="button">Share your link</button></div>
<div class="member" id="lMember"><i></i>connecting…</div>
<div class="member" style="margin-top:6px"><a id="lIap" href="https://instantadpay.com/my" style="color:var(--muted)">InstantAdPay dashboard</a> · <a href="/" style="color:var(--muted)">tester briefing</a></div>
</div>
</div>
<div class="ov" id="ovLoad"><div class="card"><div class="eyebrow">Drip Runner</div><h2 id="loadTitle">Connecting…</h2><p id="loadText">Checking your InstantAdPay sign-in.</p><button class="btn" id="loadGuest" type="button" hidden>Play now</button><a class="btn" id="loadBtn" href="/" hidden>Tester page</a></div></div>
<div class="ov" id="ovClear" hidden><div class="card">
<div class="eyebrow" id="cEyebrow">Chapter cleared</div><h2 id="cTitle">Banked 20 drips</h2>
<div class="big" id="cBig">+0.010<small>POL</small></div><p id="cText"></p><span class="chip ok" id="cChip"></span>
<div class="tip" id="cTip" hidden></div>
<button class="btn gold" id="bNext" type="button">Next chapter</button>
<div class="row2"><button class="btn ghost" id="bShareClear" type="button" hidden>Share this</button><a class="btn ghost" id="bClearSignin" href="#" hidden style="text-decoration:none;text-align:center">Sign in to collect</a></div><button class="btn ghost" id="bLobby1" type="button">Back to lobby</button>
</div></div>
<div class="ov" id="ovOver" hidden><div class="card">
<div class="eyebrow" id="oEyebrow">Out of fuel</div><h2 id="oTitle">Run over</h2><p id="oText"></p>
<button class="btn sig" id="bRefuel" type="button">Refuel · sponsor page</button><span class="chip sig" id="oChip">sponsor page or video on InstantAdPay · pays your fuel</span>
<div class="tip" id="oTip" hidden></div>
<div class="row2"><button class="btn ghost" id="bRestart" type="button">Restart</button><button class="btn ghost" id="bLobby2" type="button">Lobby</button></div>
</div></div>
<div class="ov" id="ovHangar" hidden><div class="sheet">
<h3>Hangar <span class="bal" id="hgBal"></span></h3>
<div class="item" id="itMagnet"><div class="ic gold"><i></i></div><div><b>Drip magnet</b><small>pulls drips toward you, whole next run</small></div><button class="buy" data-buy="magnet" type="button"></button></div>
<div class="item" id="itShip"><div class="ic"><i></i></div><div><b>Courier Mk II</b><small>lighter hull, tighter hops, gold trail</small></div><button class="buy" data-buy="ship" type="button"></button></div>
<div class="item" id="itShield"><div class="ic sig"><i></i></div><div><b>Shield core</b><small>survive one hit next run · paid from your POL balance</small></div><button class="buy pol" data-buy="shield" type="button"></button></div>
<div class="item" id="itSlow"><div class="ic vi"><i></i></div><div><b>Slow field</b><small>bots crawl for the first 15 s · paid from your POL balance</small></div><button class="buy pol" data-buy="slow" type="button"></button></div>
<p style="font-size:11px;color:var(--muted);margin:4px 2px 0">POL spent here goes back into the pool that pays everyone's chapter drips.</p>
<button class="btn ghost" id="bLobby3" type="button">Back</button>
</div></div>
<div class="ov" id="ovBal" hidden><div class="sheet">
<h3>Balance</h3>
<div class="card" style="padding:14px;text-align:left"><div class="eyebrow">Game balance</div><div class="big" style="font-size:36px;margin:4px 0 0"><span id="bPol">0.000</span><small>POL</small></div><p id="bNote"></p><div class="prog"><i id="bProg" style="width:0%"></i></div></div>
<div id="ledger"></div>
<p style="font-size:11px;color:var(--muted);margin:4px 2px 0" id="bWallet"></p>
<button class="btn ghost" id="bLobby4" type="button">Back</button>
</div></div>
</div></div>
<script src="https://instantadpay.com/assets/game-signin.js?v=20261003a" async></script>
<script src="/spawn.js"></script>
<script src="/play.js"></script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover,user-scalable=no">
<meta name="robots" content="noindex,nofollow">
<title>Drip Runner</title>
<meta property="og:title" content="Drip Runner: hop the network, get paid in POL">
<meta property="og:description" content="A fast little runner game for InstantAdPay members. Clear chapters, refuel on sponsor pages, collect POL.">
<meta property="og:image" content="https://driprunner.app/og-driprunner.jpg">
<meta name="twitter:card" content="summary_large_image">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Orbitron:wght@600;800;900&family=Manrope:wght@400;600;800&family=JetBrains+Mono:wght@500;700&display=swap">
<style>
:root{color-scheme:dark;--page:#050912;--ink:#EEF3FA;--ink2:#AFC0D8;--muted:#6E82A3;--cyan:#22D3EE;--cyan2:#8FF0FF;--gold:#FFC24B;--gold2:#FFE9A8;--bot:#FF3B7A;--sig:#FF6A1A;--ok:#34D399;--violet:#8B5CF6;--panel:#0E172D;--panel2:#141F3A;--line:#24365F;
--display:"Orbitron","Segoe UI",system-ui,sans-serif;--body:"Manrope","Segoe UI",system-ui,sans-serif;--mono:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{height:100%}
body{margin:0;background:var(--page);color:var(--ink);font:15px/1.5 var(--body);overflow:hidden;background-image:radial-gradient(ellipse 60% 50% at 50% 0%,rgba(34,211,238,.10),transparent 60%),radial-gradient(ellipse 40% 40% at 90% 100%,rgba(255,106,26,.08),transparent 60%)}
.frame{position:fixed;inset:0;display:grid;place-items:center}
.phone{position:relative;width:100%;height:100%;background:#050912;overflow:hidden}
@media (min-width:700px) and (min-height:700px){.frame{padding:16px}.phone{max-width:430px;max-height:900px;border:3px solid #1A2540;border-radius:40px;box-shadow:0 40px 90px -30px rgba(0,0,0,.95),0 0 80px -20px rgba(34,211,238,.25)}}
canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none}
.hud{position:absolute;left:0;right:0;top:0;padding:calc(12px + env(safe-area-inset-top,0px)) 14px 0;display:grid;grid-template-columns:1fr auto 1fr;align-items:start;gap:10px;pointer-events:none;z-index:4;opacity:0;transition:opacity .3s}
.hud.on{opacity:1}
.hud .st{font:700 20px var(--display);letter-spacing:.04em;line-height:1;font-variant-numeric:tabular-nums}
.hud .st small{display:block;font:700 9px var(--body);letter-spacing:.16em;text-transform:uppercase;color:var(--muted);margin-bottom:3px}
.hud .st.gold{color:var(--gold);text-shadow:0 0 14px rgba(255,194,75,.6)}.hud .st.cy{color:var(--cyan2);text-align:center;text-shadow:0 0 14px rgba(34,211,238,.6)}.hud .st.r{text-align:right;color:var(--ink2)}
.fuel{grid-column:1/-1;margin-top:6px;height:8px;border-radius:4px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.12);overflow:hidden}
.fuel i{display:block;height:100%;width:100%;border-radius:4px;background:linear-gradient(90deg,var(--sig),var(--gold) 40%,var(--cyan));box-shadow:0 0 12px rgba(34,211,238,.5);transition:width .15s linear}
.fuel.low i{background:linear-gradient(90deg,var(--bot),var(--sig));animation:blink .5s steps(2) infinite}
@keyframes blink{50%{opacity:.35}}
.goal{grid-column:1/-1;font:600 11px var(--body);color:var(--ink2);display:flex;justify-content:space-between;margin-top:2px}.goal b{color:var(--gold)}
.pill{position:absolute;left:50%;transform:translateX(-50%);top:50%;z-index:5;pointer-events:none;font:800 22px var(--display);letter-spacing:.1em;text-transform:uppercase;color:#fff;text-shadow:0 0 20px var(--cyan);opacity:0;transition:opacity .2s;white-space:nowrap}
.pill.on{opacity:1;animation:pop .9s ease-out}
@keyframes pop{0%{transform:translate(-50%,10px) scale(.7)}30%{transform:translate(-50%,0) scale(1.1)}100%{transform:translate(-50%,-30px) scale(1)}}
.mute{position:absolute;right:12px;bottom:calc(12px + env(safe-area-inset-bottom,0px));z-index:6;width:38px;height:38px;border-radius:50%;border:1px solid var(--line);background:rgba(14,23,45,.7);color:var(--ink2);font:700 13px var(--mono);display:grid;place-items:center;cursor:pointer}
.ov{position:absolute;inset:0;z-index:8;display:flex;flex-direction:column;justify-content:center;padding:calc(20px + env(safe-area-inset-top,0px)) 18px calc(20px + env(safe-area-inset-bottom,0px));background:rgba(5,9,18,.55);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px)}
.moreGames{margin-top:16px;--gs-ink:var(--ink);--gs-muted:var(--ink2);--gs-card:var(--panel2);--gs-line:var(--line);--gs-hot:var(--gold);--gs-font:var(--body)}
[hidden]{display:none!important} /* every element, not just overlays: .btn{display:block} was beating the hidden attribute, so signed-in players still saw "Sign in to keep progress" (Marty, 2026-10-03) */
/* 2026-10-01 (Hugh, iPhone Safari): the lobby is taller than a phone with the browser bar showing, and .phone clips overflow, so the last button sat under the toolbar. Overlays scroll, keep a bottom gap, and center only when they fit. */
.ov{overflow-y:auto;-webkit-overflow-scrolling:touch;overscroll-behavior:contain;touch-action:pan-y;justify-content:safe center}
.ov.lobby{justify-content:space-between;padding-bottom:calc(28px + env(safe-area-inset-bottom,0px))}
@media (max-height:760px){.logo{margin-top:3vh}}
.ov.lobby{justify-content:space-between;background:linear-gradient(180deg,rgba(5,9,18,.15),rgba(5,9,18,.75) 60%,#050912)}
.logo{font:900 42px/1 var(--display);letter-spacing:.06em;text-transform:uppercase;text-align:center;margin-top:10vh;background:linear-gradient(180deg,#fff 0%,var(--cyan2) 45%,var(--cyan) 60%,#0EA5C9 100%);-webkit-background-clip:text;background-clip:text;color:transparent;filter:drop-shadow(0 0 22px rgba(34,211,238,.55));animation:hum 3s ease-in-out infinite}
.logo span{display:block;background:linear-gradient(180deg,var(--gold2),var(--gold) 55%,#E08A00);-webkit-background-clip:text;background-clip:text;color:transparent;filter:drop-shadow(0 0 22px rgba(255,194,75,.5))}
@keyframes hum{50%{filter:drop-shadow(0 0 34px rgba(34,211,238,.8))}}
.tag{text-align:center;color:var(--ink2);font-size:13px;margin-top:10px}
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:14px 0 10px}
.stat{background:linear-gradient(180deg,rgba(20,31,58,.9),rgba(14,23,45,.9));border:1px solid var(--line);border-radius:12px;padding:10px 8px;text-align:center;position:relative;overflow:hidden}
.stat small{display:block;font:700 9px var(--body);letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}.stat b{font:800 20px var(--display);font-variant-numeric:tabular-nums}
.stat b.gold{color:var(--gold)}.stat b.cy{color:var(--cyan2)}.stat b.ok{color:var(--ok)}
.pool{font:600 11px var(--mono);color:var(--muted);text-align:center;margin-bottom:6px}.pool b{color:var(--ink2)}
.btn{display:block;width:100%;margin-top:10px;padding:14px 12px;border-radius:12px;border:0;cursor:pointer;font:800 16px var(--display);letter-spacing:.12em;text-transform:uppercase;color:#07101F;position:relative;background:linear-gradient(180deg,var(--cyan2),var(--cyan) 55%,#0EA5C9);box-shadow:0 0 0 1px rgba(255,255,255,.25) inset,0 8px 28px -8px rgba(34,211,238,.8)}
.btn:active{transform:translateY(1px)}
.btn.sig{background:linear-gradient(180deg,#FFB088,var(--sig) 55%,#D44E00);color:#fff;box-shadow:0 0 0 1px rgba(255,255,255,.2) inset,0 8px 28px -8px rgba(255,106,26,.8)}
.btn.gold{background:linear-gradient(180deg,var(--gold2),var(--gold) 55%,#E08A00);box-shadow:0 0 0 1px rgba(255,255,255,.25) inset,0 8px 28px -8px rgba(255,194,75,.8)}
.btn.ghost{background:rgba(14,23,45,.7);border:1px solid var(--line);color:var(--ink2);font-size:13px;padding:11px;box-shadow:none}
.btn[disabled]{opacity:.45;pointer-events:none}
.row2{display:grid;grid-template-columns:1fr 1fr;gap:10px}.row2 .btn{margin-top:10px}
.member{margin-top:12px;text-align:center;font:600 11px var(--mono);color:var(--muted)}.member i{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--ok);box-shadow:0 0 8px var(--ok);margin-right:6px;vertical-align:1px}.member i.no{background:var(--sig);box-shadow:0 0 8px var(--sig)}
.card{background:linear-gradient(180deg,rgba(20,31,58,.96),rgba(14,23,45,.98));border:1px solid var(--line);border-radius:18px;padding:22px 18px;text-align:center;box-shadow:0 30px 70px -20px rgba(0,0,0,.9),0 0 60px -20px rgba(34,211,238,.35);position:relative;overflow:hidden}
.card:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:linear-gradient(90deg,transparent,var(--cyan),var(--gold),transparent)}
.card .eyebrow{font:700 10px var(--body);letter-spacing:.2em;text-transform:uppercase;color:var(--cyan)}
.card h2{font:900 26px/1.05 var(--display);letter-spacing:.05em;text-transform:uppercase;margin:8px 0 4px;text-wrap:balance}
.card .big{font:900 46px/1 var(--display);margin:12px 0 2px;font-variant-numeric:tabular-nums;background:linear-gradient(180deg,var(--gold2),var(--gold) 60%,#E08A00);-webkit-background-clip:text;background-clip:text;color:transparent;filter:drop-shadow(0 0 18px rgba(255,194,75,.5))}
.card .big small{font:700 13px var(--mono);color:var(--ink2);margin-left:6px;-webkit-text-fill-color:var(--ink2)}
.card .big.dim{opacity:.3}
.card p{font-size:13px;color:var(--ink2);margin:6px 0 0}
.chip{display:inline-block;font:700 10px var(--mono);letter-spacing:.06em;text-transform:uppercase;padding:3px 8px;border-radius:5px;border:1px solid var(--line);color:var(--ink2);margin-top:10px}
.chip.ok{color:var(--ok);border-color:rgba(52,211,153,.4);background:rgba(52,211,153,.08)}.chip.sig{color:var(--sig);border-color:rgba(255,106,26,.4);background:rgba(255,106,26,.08)}.chip.gold{color:var(--gold);border-color:rgba(255,194,75,.4);background:rgba(255,194,75,.08)}
.sheet{background:linear-gradient(180deg,rgba(20,31,58,.97),rgba(14,23,45,.98));border:1px solid var(--line);border-radius:18px;padding:16px 14px;max-height:100%;display:flex;flex-direction:column;gap:8px;overflow:auto}
.sheet h3{font:900 18px var(--display);letter-spacing:.1em;text-transform:uppercase;margin:2px 2px 4px;display:flex;justify-content:space-between;align-items:center}.sheet h3 .bal{font:700 11px var(--mono);color:var(--gold)}
.item{display:grid;grid-template-columns:46px 1fr auto;gap:10px;align-items:center;background:rgba(5,9,18,.5);border:1px solid var(--line);border-radius:12px;padding:8px 10px;text-align:left}
.item.owned{border-color:rgba(52,211,153,.45)}
.item .ic{width:46px;height:46px;border-radius:11px;background:radial-gradient(circle at 30% 30%,#2A4A7A,#0E1730);display:grid;place-items:center}
.item .ic i{display:block;width:28px;height:13px;border-radius:7px;background:#F3F6FB;box-shadow:0 0 12px var(--cyan)}
.item .ic.gold i{background:var(--gold);width:16px;height:16px;border-radius:50%;box-shadow:0 0 12px var(--gold)}
.item .ic.sig i{background:var(--sig);width:18px;height:18px;border-radius:5px;transform:rotate(45deg);box-shadow:0 0 12px var(--sig)}
.item .ic.vi i{background:var(--violet);width:18px;height:18px;border-radius:50% 50% 4px 4px;box-shadow:0 0 12px var(--violet)}
.item b{font-size:13px;display:block}.item small{color:var(--muted);font-size:11px;display:block}
.buy{font:800 11px var(--mono);white-space:nowrap;padding:8px 10px;border-radius:9px;border:1px solid rgba(255,194,75,.45);background:rgba(255,194,75,.1);color:var(--gold);cursor:pointer}
.buy.pol{border-color:rgba(52,211,153,.45);background:rgba(52,211,153,.1);color:var(--ok)}
.buy.own{border-color:rgba(52,211,153,.45);background:rgba(52,211,153,.1);color:var(--ok);pointer-events:none}
.buy.no{opacity:.4;pointer-events:none}
.led{display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--ink2);padding:7px 2px;border-top:1px solid var(--line)}.led:first-child{border-top:0}.led .m{font:700 12px var(--mono);color:var(--gold);white-space:nowrap}.led .m.ok{color:var(--ok)}.led .m.neg{color:var(--sig)}.led a{color:var(--cyan2)}
.prog{height:8px;background:rgba(255,255,255,.08);border-radius:4px;overflow:hidden;margin-top:8px}.prog i{display:block;height:100%;background:linear-gradient(90deg,var(--cyan),var(--gold));box-shadow:0 0 10px rgba(255,194,75,.5)}
.tip{margin:12px 0 0;padding:10px 12px;border-radius:10px;background:rgba(34,211,238,.07);border:1px solid rgba(34,211,238,.25);font-size:12px;line-height:1.45;color:var(--ink2);text-align:left}.tip b{display:block;font:700 9px var(--body);letter-spacing:.16em;text-transform:uppercase;color:var(--cyan);margin-bottom:3px}
.shrHow{margin:6px 0 8px;font-size:11px;line-height:1.45;color:var(--ink2)}.shrHow a{color:inherit}
.shr{margin-top:10px;padding:10px 12px;border-radius:10px;border:1px solid var(--line);background:rgba(14,23,45,.6);font-size:11px;color:var(--muted);text-align:center}.shr b{color:var(--gold)}.shr .btn{margin-top:8px}
/* invite friends card (2026-10-05) */
.inv{margin-top:14px;padding:14px 14px 12px;border-radius:14px;border:1px solid rgba(34,211,238,.5);background:linear-gradient(180deg,rgba(14,40,58,.92),rgba(14,23,45,.96));box-shadow:0 0 34px -14px rgba(34,211,238,.6);text-align:left}
.inv .eyebrow{font:800 13px var(--display);letter-spacing:.14em;text-transform:uppercase;color:var(--cyan2)}
.invLead{margin:6px 0 10px;font-size:13px;line-height:1.45;color:var(--ink)}
.invLbl{display:block;font:700 9px var(--body);letter-spacing:.16em;text-transform:uppercase;color:var(--muted);margin-bottom:4px}
.invLink{display:block;width:100%;padding:10px 11px;border-radius:10px;border:1px solid var(--line);background:rgba(5,9,18,.75);color:var(--gold2);font:700 13px var(--mono);user-select:all;-webkit-user-select:all}
.invLink:focus{outline:2px solid var(--cyan);outline-offset:1px}
.invBtns{display:flex;gap:10px}.invBtns .btn{flex:1 1 0;min-width:0;font-size:13px;padding:12px 8px}
.invBtns .btn.done{background:linear-gradient(180deg,#A7F3D0,var(--ok) 55%,#059669)}
.invNote{margin:8px 0 0;font-size:11px;line-height:1.45;color:var(--muted)}.invNote a{color:var(--cyan2)}
.invStat{margin-top:10px;padding-top:8px;border-top:1px solid var(--line);font-size:11px;color:var(--muted)}.invStat b{color:var(--gold)}
.toast{position:absolute;left:50%;bottom:calc(70px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);z-index:20;background:var(--panel2);border:1px solid var(--line);color:var(--ink);font-size:12px;padding:8px 12px;border-radius:10px;opacity:0;transition:opacity .2s;pointer-events:none;max-width:92%;text-align:center}
.toast.on{opacity:1}
/* member welcome offer (2026-10-05): an extra card under the chapter-clear result, never during a run, never blocking */
.offer{margin-top:12px;background:linear-gradient(180deg,rgba(40,32,12,.96),rgba(14,23,45,.98));border:1px solid rgba(255,194,75,.45);border-radius:16px;padding:16px 16px 12px;text-align:center;box-shadow:0 20px 50px -20px rgba(0,0,0,.9),0 0 40px -18px rgba(255,194,75,.45);animation:offerIn .4s ease-out .7s backwards}
.offer .eyebrow{font:700 10px var(--body);letter-spacing:.2em;text-transform:uppercase;color:var(--gold)}
.offer h4{font:900 17px/1.15 var(--display);letter-spacing:.05em;text-transform:uppercase;margin:6px 0 4px}
.offer p{font-size:13px;color:var(--ink2);margin:4px 0 0}.offer p b{color:var(--gold)}
.offer .btn{text-decoration:none;text-align:center;font-size:13px;padding:12px}
@keyframes offerIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
.free{padding:9px 12px;border-radius:10px;background:rgba(255,194,75,.1);border:1px solid rgba(255,194,75,.45);font-size:12px;color:var(--gold2);text-align:left}.free b{color:var(--gold)}
.buy.free{border-color:rgba(255,194,75,.7);background:rgba(255,194,75,.2);color:var(--gold2)}
.tapdesk{position:absolute;bottom:calc(14px + env(safe-area-inset-bottom,0px));left:14px;z-index:5;font:600 10px var(--body);letter-spacing:.14em;text-transform:uppercase;color:var(--muted);pointer-events:none}
</style>
</head>
<body>
<div class="frame"><div class="phone" id="phone">
<canvas id="game"></canvas>
<div class="hud" id="hud">
<div class="st gold"><small>Drips</small><span id="hDrips">0</span></div>
<div class="st cy"><small>Chapter</small><span id="hChap">1</span></div>
<div class="st r"><small>Best</small><span id="hBest">0</span></div>
<div class="fuel" id="fuel"><i id="fuelBar"></i></div>
<div class="goal"><span>Chapter goal</span><span><b id="hGoalN">0</b> / <span id="hGoal">20</span> drips</span></div>
</div>
<div class="pill" id="pill"></div>
<div class="tapdesk" id="tapdesk" hidden>tap · click · space</div>
<button class="mute" id="mute" type="button" title="Sound">♪</button>
<div class="toast" id="toast"></div>
<div class="ov lobby" id="ovLobby" hidden>
<div><div class="logo">Drip<span>Runner</span></div><div class="tag">Hop the network. Bank the drips. Get paid in POL.</div></div>
<div>
<div class="stats">
<div class="stat"><small>Chapter</small><b class="cy" id="lChap">1</b></div>
<div class="stat"><small>Drips</small><b class="gold" id="lDrips">0</b></div>
<div class="stat"><small>Balance</small><b class="ok" id="lPol">0.000</b></div>
</div>
<div class="pool" id="lPool"></div>
<div class="free" id="lPerk" hidden></div>
<div class="tip" id="lTip" hidden></div>
<button class="btn" id="bPlay" type="button">Play</button>
<div class="row2"><button class="btn ghost" id="bHangar" type="button">Hangar</button><button class="btn ghost" id="bBalance" type="button">Balance</button></div>
<!-- invite friends (2026-10-05, Marty: members could not find their link): a signed-in player's own /r/<username> link, right under Play -->
<section class="inv" id="lShare" hidden aria-labelledby="invTitle">
<div class="eyebrow" id="invTitle">Invite friends</div>
<p class="invLead">Invite friends to Drip Runner. When they join InstantAdPay from your link, you are their sponsor.</p>
<div id="invHas">
<label class="invLbl" for="invLink">Your invite link</label>
<input class="invLink" id="invLink" type="text" readonly value="" aria-label="Your invite link">
<div class="invBtns"><button class="btn" id="bCopy" type="button">Copy link</button><button class="btn ghost" id="bShare" type="button">Share</button></div>
<p class="invNote">It shows your own card when you post it on Telegram, Facebook or X.</p>
<div class="invStat" id="lShareStat"></div>
<p class="shrHow" id="lShareHow"></p>
</div>
<p class="invNote" id="invNone" hidden>Your invite link uses your InstantAdPay username. <a id="invNoneGo" href="https://instantadpay.com/my">Set your username on InstantAdPay</a>, then come back here.</p>
</section>
<a class="btn gold" id="bLevel" href="https://instantadpay.com/my#buy" style="text-decoration:none;text-align:center;font-size:13px;padding:11px">Level up on InstantAdPay</a>
<a class="btn" id="bSignin" href="#" hidden style="text-decoration:none;text-align:center">Sign in to keep progress</a>
<div class="member" id="lMember"><i></i>connecting…</div>
<div id="moreGames" class="moreGames" hidden></div>
<div class="member" style="margin-top:6px"><a id="lIap" href="https://instantadpay.com/my" style="color:var(--muted)">InstantAdPay dashboard</a> · <a href="/" style="color:var(--muted)">tester briefing</a></div>
</div>
</div>
<div class="ov" id="ovLoad"><div class="card"><div class="eyebrow">Drip Runner</div><h2 id="loadTitle">Connecting…</h2><p id="loadText">Checking your InstantAdPay sign-in.</p><button class="btn" id="loadGuest" type="button" hidden>Play now</button><a class="btn" id="loadBtn" href="/" hidden>Tester page</a></div></div>
<div class="ov" id="ovClear" hidden><div class="card">
<div class="eyebrow" id="cEyebrow">Chapter cleared</div><h2 id="cTitle">Banked 20 drips</h2>
<div class="big" id="cBig">+0.010<small>POL</small></div><p id="cText"></p><span class="chip ok" id="cChip"></span>
<div class="tip" id="cTip" hidden></div>
<button class="btn gold" id="bNext" type="button">Next chapter</button>
<div class="row2"><button class="btn ghost" id="bShareClear" type="button" hidden>Share this</button><a class="btn ghost" id="bClearSignin" href="#" hidden style="text-decoration:none;text-align:center">Sign in to earn</a></div><button class="btn ghost" id="bLobby1" type="button">Back to lobby</button>
</div>
<div class="offer" id="cOffer" hidden><div class="eyebrow">Member welcome offer</div><h4>Become an InstantAdPay member</h4><p id="cOfferText"></p>
<a class="btn gold" id="cOfferGo" href="https://instantadpay.com/my?from=driprunner#buy">Get the $5 package</a><button class="btn ghost" id="cOfferNo" type="button">Not now</button></div>
</div>
<div class="ov" id="ovOver" hidden><div class="card">
<div class="eyebrow" id="oEyebrow">Out of fuel</div><h2 id="oTitle">Run over</h2><p id="oText"></p>
<button class="btn sig" id="bRefuel" type="button">Refuel · sponsor page</button><span class="chip sig" id="oChip">sponsor page or video on InstantAdPay · pays your fuel</span>
<div class="tip" id="oTip" hidden></div>
<div class="row2"><button class="btn ghost" id="bRestart" type="button">Restart</button><button class="btn ghost" id="bLobby2" type="button">Lobby</button></div>
</div></div>
<div class="ov" id="ovHangar" hidden><div class="sheet">
<h3>Hangar <span class="bal" id="hgBal"></span></h3>
<div class="free" id="hgFree" hidden><b>Free upgrade ready.</b> Your member perk: your next hangar purchase costs nothing. Pick any item below.</div>
<div class="item" id="itMagnet"><div class="ic gold"><i></i></div><div><b>Drip magnet</b><small>pulls drips toward you, whole next run</small></div><button class="buy" data-buy="magnet" type="button"></button></div>
<div class="item" id="itShip"><div class="ic"><i></i></div><div><b>Courier Mk II</b><small>lighter hull, tighter hops, gold trail</small></div><button class="buy" data-buy="ship" type="button"></button></div>
<div class="item" id="itShield"><div class="ic sig"><i></i></div><div><b>Shield core</b><small>survive one hit next run · paid from your POL balance</small></div><button class="buy pol" data-buy="shield" type="button"></button></div>
<div class="item" id="itSlow"><div class="ic vi"><i></i></div><div><b>Slow field</b><small>bots crawl for the first 15 s · paid from your POL balance</small></div><button class="buy pol" data-buy="slow" type="button"></button></div>
<p style="font-size:11px;color:var(--muted);margin:4px 2px 0">POL spent here goes back into the pool that pays everyone's chapter drips.</p>
<button class="btn ghost" id="bLobby3" type="button">Back</button>
</div></div>
<div class="ov" id="ovBal" hidden><div class="sheet">
<h3>Balance</h3>
<div class="card" style="padding:14px;text-align:left"><div class="eyebrow">Game balance</div><div class="big" style="font-size:36px;margin:4px 0 0"><span id="bPol">0.000</span><small>POL</small></div><p id="bNote"></p><div class="prog"><i id="bProg" style="width:0%"></i></div></div>
<div id="ledger"></div>
<p style="font-size:11px;color:var(--muted);margin:4px 2px 0" id="bWallet"></p>
<button class="btn ghost" id="bLobby4" type="button">Back</button>
</div></div>
</div></div>
<script src="https://instantadpay.com/assets/game-signin.js?v=20261003a" async></script>
<script src="https://instantadpay.com/assets/game-strip.js?v=20261003a"></script>
<script src="/spawn.js"></script>
<script src="/play.js?v=20261102gate"></script>
</body>
</html>
+63 -17
View File
@@ -42,10 +42,13 @@ var toastT = null; function toast(m) { $('toast').textContent = m; $('toast').cl
function pill(m) { var p = $('pill'); p.textContent = m; p.classList.remove('on'); void p.offsetWidth; p.classList.add('on'); setTimeout(function () { p.classList.remove('on'); }, 900); }
var hudCache = {}; function setHud() { if (!R) return; var v = { d: R.drips, c: R.chapter, b: Math.max(P.best, R.drips), g: R.chapDrips, gg: R.goal }; if (v.d !== hudCache.d) $('hDrips').textContent = v.d; if (v.c !== hudCache.c) $('hChap').textContent = v.c; if (v.b !== hudCache.b) $('hBest').textContent = v.b; if (v.g !== hudCache.g) $('hGoalN').textContent = v.g; if (v.gg !== hudCache.gg) $('hGoal').textContent = v.gg; hudCache = v; $('fuelBar').style.width = Math.max(0, R.fuel) + '%'; $('fuel').classList.toggle('low', R.fuel < 22); }
function f3(n) { return Number(n || 0).toFixed(3); }
// a signed-in player's own wallet (the session's, or one InstantAdPay pushed since: me.hasWallet); POL with no wallet waits for the link (2026-10-27)
function hasW() { return !!(ME && !ME.guest && (ME.wallet || ME.hasWallet)); }
function linkW() { return '<a href="' + esc(IAP) + '/my#wallet" target="_blank" rel="noopener">Link your wallet to receive this POL</a>'; }
/* ---------- lobby / me ---------- */
var ME_EXTRA = {};
function loadMe() { return api('/api/me').then(function (r) { if (r._status !== 200) throw r; ME = r.me; P = r.player; BAL = r.balance; POOL = r.pool; IAP = r.iap || IAP; TIPS = r.tips || []; ME_EXTRA = { signin: r.signin, share: r.share, referrals: r.referrals }; return r; }); }
function loadMe() { return api('/api/me').then(function (r) { if (r._status !== 200) throw r; ME = r.me; P = r.player; BAL = r.balance; POOL = r.pool; IAP = r.iap || IAP; TIPS = r.tips || []; ME_EXTRA = { signin: r.signin, share: r.share, referrals: r.referrals, perk: r.perk || ME_EXTRA.perk || null, gamepass: r.gamepass || null }; return r; }); } // perk: the one-time member message, kept for this page load
// share: the phone's share sheet where there is one, else copy the link
function share(text) {
var url = ME_EXTRA.share; if (!url) return toast('Set a username on InstantAdPay to get a share link.');
@@ -57,20 +60,31 @@ function share(text) {
function lobby() {
R = null; $('hud').classList.remove('on'); $('tapdesk').hidden = true;
$('lChap').textContent = P.chapter; $('lDrips').textContent = P.bank.toLocaleString(); $('lPol').textContent = f3(BAL.unpaid);
$('lPool').innerHTML = 'POL pool <b>' + f3(POOL.available) + '</b> · today’s cap left <b>' + f3(POOL.capLeft) + '</b> · a chapter drip is <b>' + f3(POOL.dripPol) + '</b>';
// the tiers (2026-11-02): guests earn nothing, a free account earns a share of the table, Game Pass holders earn the table
$('lPool').innerHTML = 'POL pool <b>' + f3(POOL.available) + '</b> · today’s cap left <b>' + f3(POOL.capLeft) + '</b> · a chapter drip is <b>' + f3(POOL.dripPol) + '</b>' + (POOL.tier === 'guest' ? ' · guests earn nothing, sign in free to earn' : POOL.tier === 'free' ? ' · yours pays <b>' + f3(POOL.yourDrip) + '</b> (' + (POOL.freeSharePct || 25) + '%), Game Pass holders earn the full amount' : '');
$('lIap').href = IAP + '/my'; $('bLevel').href = IAP + '/my#buy'; tip('lTip');
try { if (BAL && BAL.unpaid > 0 && ME && !hasW() && !ME.guest && !sessionStorage.getItem('dr.walletnudge')) { sessionStorage.setItem('dr.walletnudge', '1'); toast(f3(BAL.unpaid) + ' POL is waiting. Link your wallet on InstantAdPay to receive this POL.'); } } catch (e) {}
$('lPerk').hidden = !ME_EXTRA.perk; $('lPerk').textContent = ME_EXTRA.perk || ''; // member perk (2026-10-05)
// Game Pass (InstantAdPay, all nine games): active until <date>, or the link to get it; opens a new tab (the game may be framed)
(function () { var g = ME_EXTRA.gamepass, el = $('lPass'); if (!el) { el = document.createElement('p'); el.id = 'lPass'; el.className = 'fine'; $('lPool').parentNode.insertBefore(el, $('lPool').nextSibling); }
if (!g || !g.on) { el.hidden = true; return; } el.hidden = false;
el.innerHTML = g.active ? '🎫 Game Pass active' + (g.untilText ? ' until ' + esc(g.untilText) : '') + ' · the full POL on every first clear, a shield at the start of every run' : '🎫 <a href="' + esc(g.url) + '" target="_blank" rel="noopener">Get the Game Pass</a> · the full POL on every first clear (a free account earns ' + (POOL.freeSharePct || 25) + '%), higher daily caps across all nine games, a shield every run here'; })();
$('bHangar').textContent = P.freeUpgrades > 0 ? 'Hangar · ' + P.freeUpgrades + ' free' : 'Hangar';
// signed in through the game: these open InstantAdPay already signed in (in-game sign-in pass, 2026-10-03)
if (window.IAPGames && !$('moreGames').dataset.done) { $('moreGames').dataset.done = 1; IAPGames.strip($('moreGames'), { current: 'driprunner', title: 'More games that pay POL' }); } // cross-promo strip (2026-10-03)
[['lIap', 'overview'], ['bLevel', 'buy']].forEach(function (x) { var a = $(x[0]); if (a && !a.dataset.pass) { a.dataset.pass = 1; a.addEventListener('click', function (ev) { if (window.IAPSignin && IAPSignin.hasPass()) { ev.preventDefault(); IAPSignin.enter(x[1]); } }); } });
if (ME.guest) {
$('lMember').innerHTML = '<i class="no"></i>Playing as a guest · sign in to keep your progress and collect POL';
$('lMember').innerHTML = '<i class="no"></i>Playing as a guest · guest runs earn no POL. Sign in free to earn on every new chapter; the Game Pass pays the full amount';
$('bSignin').hidden = false; $('bSignin').href = ME_EXTRA.signin || '/signin'; $('lShare').hidden = true;
} else {
$('lMember').innerHTML = '<i class="' + (ME.wallet ? '' : 'no') + '"></i>InstantAdPay · ' + (ME.username ? '@' + ME.username : '#' + ME.memberId) + ' · ' + (ME.wallet ? ME.wallet.slice(0, 6) + '…' + ME.wallet.slice(-4) : 'no wallet on file');
$('lMember').innerHTML = '<i class="' + (hasW() ? '' : 'no') + '"></i>InstantAdPay · ' + (ME.username ? '@' + ME.username : '#' + ME.memberId) + ' · ' + (ME.wallet ? ME.wallet.slice(0, 6) + '…' + ME.wallet.slice(-4) : hasW() ? 'wallet linked' : 'no wallet on file · ' + linkW());
$('bSignin').hidden = true;
var rf = ME_EXTRA.referrals || {};
$('lShare').hidden = !ME_EXTRA.share;
// the invite card shows for every signed-in player; without a username there is no link yet, so it says how to get one
$('lShare').hidden = false; $('invHas').hidden = !ME_EXTRA.share; $('invNone').hidden = !!ME_EXTRA.share; $('invNoneGo').href = IAP + '/my';
$('invLink').value = ME_EXTRA.share || ''; $('bShare').hidden = !navigator.share;
$('lShareHow').innerHTML = 'Players whose InstantAdPay sponsor is you are your team. Each time one of them refuels, ' + (rf.pct || 10) + '% of what that refuel adds to the pool is credited to your balance, and it is sent to your wallet with your drips at ' + Number((BAL && BAL.threshold) || 0.25).toFixed(2) + ' POL. <a href="/#team" target="_blank" rel="noopener">How it works</a>';
$('lShareStat').innerHTML = 'Your link: <b>' + (rf.clicks || 0) + '</b> visits · <b>' + (rf.count || 0) + '</b> players on your team · <b>' + f3(rf.earned) + '</b> POL earned from their refuels (' + (rf.pct || 0) + '% of each)';
$('lShareStat').innerHTML = 'Your link: <b>' + (rf.clicks || 0) + '</b> visit' + (rf.clicks === 1 ? '' : 's') + ' · <b>' + (rf.count || 0) + '</b> player' + (rf.count === 1 ? '' : 's') + ' on your team · <b>' + f3(rf.earned) + '</b> POL earned from their refuels (' + (rf.pct || 0) + '% of each)';
}
show('ovLobby');
}
@@ -135,7 +149,7 @@ function over(title, why) {
setTimeout(function () { if (!R) return; $('oEyebrow').textContent = title; $('oTitle').textContent = 'Run over at ' + R.drips; $('oText').textContent = why + ' Refuel with a sponsor visit and keep this run, drips and chapter progress intact.'; $('bRefuel').hidden = false; $('oChip').hidden = false; tip('oTip'); show('ovOver'); }, 450);
}
function cleared() {
R.paused = true; pill('Verifying…');
R.paused = true; pill('Verifying…'); $('cOffer').hidden = true;
flush(true).then(function (r) {
if (!R) return;
if (!r.cleared) { R.paused = false; if (r.short) toast('Server count says ' + r.short + ' more to go'); return; }
@@ -143,17 +157,45 @@ function cleared() {
$('cEyebrow').textContent = 'Chapter ' + c.chapter + ' cleared'; $('cTitle').textContent = 'Banked ' + (R.goal) + ' drips';
var m = Math.floor(c.playTime / 60), s = c.playTime % 60; var tm = m + ':' + (s < 10 ? '0' : '') + s;
$('cBig').innerHTML = '+' + f3(c.pol) + '<small>POL</small>'; $('cBig').classList.toggle('dim', !c.pol);
var why = { paid: 'First clear, verified. Added to your game balance.', replay: c.first ? 'Verified.' : 'You cleared this one before. Only the first clear pays.', pool: 'The POL pool is empty right now. Refuel visits fill it, so this clear counts but pays nothing.', cap: 'Today’s pool cap is spent. Chapter counts, no POL today.', flagged: 'This run was flagged by the server check, so it pays nothing.', guest: 'You are playing as a guest. Sign in with InstantAdPay and this clear pays ' + f3(POOL.dripPol) + ' POL into your balance. Your progress comes with you.' };
var why = { paid: 'First clear, verified. Added to your game balance.', replay: c.first ? 'Verified.' : 'You cleared this one before. Only the first clear pays.', pool: 'The POL pool is empty right now. Refuel visits fill it, so this clear counts but pays nothing.', cap: 'Today’s pool cap is spent. Chapter counts, no POL today.', flagged: 'This run was flagged by the server check, so it pays nothing.', guest: 'You are playing as a guest, so this clear pays nothing. Sign in with InstantAdPay (free) and your next first clears earn POL; Game Pass holders earn the full amount. Your progress comes with you.' };
$('bShareClear').hidden = !!ME.guest || !ME_EXTRA.share; $('bShareClear').dataset.text = 'I just cleared Chapter ' + c.chapter + ' in Drip Runner' + (c.pol ? ' and it paid ' + f3(c.pol) + ' POL' : '') + '. Hop the network, dodge the bots:';
$('bClearSignin').hidden = !ME.guest; if (ME.guest) $('bClearSignin').href = ME_EXTRA.signin || '/signin';
$('cText').textContent = why[c.reason] || ''; $('cChip').className = 'chip ' + (c.pol ? 'ok' : 'sig'); $('cChip').textContent = (c.pol ? 'verified' : c.reason) + ' · ' + tm + ' play time';
$('cText').textContent = why[c.reason] || '';
// the Game Pass truth (deferred to later days, or recorded while InstantAdPay confirms) + the nudge, in a new tab (the game may be framed)
if (c.note) { var gpp = ME_EXTRA.gamepass; $('cText').innerHTML = esc(c.note) + (gpp && gpp.on && !gpp.active && /Get the Pass/.test(c.note) ? ' <a href="' + esc(gpp.url) + '" target="_blank" rel="noopener">Get the Game Pass</a>' : ''); } if (c.pol && !ME.guest && !hasW()) $('cText').innerHTML += ' ' + linkW() + '.'; $('cChip').className = 'chip ' + (c.pol ? 'ok' : 'sig'); $('cChip').textContent = (c.pol ? 'verified' : c.reason) + ' · ' + tm + ' play time';
R.chapter = c.next; R.goal = c.nextGoal; R.chapDrips = 0; if (r.pool != null) POOL.available = r.pool;
tip('cTip'); setTimeout(function () { show('ovClear'); }, 500);
tip('cTip'); setTimeout(function () { show('ovClear'); if (r.starterOffer) starterOffer(r.starterOffer); }, 500); // the offer card fades in under the result (CSS delay)
});
}
/* member welcome offer (2026-10-05): the server sends it after a clear, at most once a Central day, to signed-in players who are
not InstantAdPay members yet. Dismissible, never blocks the next chapter. In a frame the link opens a new tab. */
function starterOffer(o) {
var b = Number(o.bonus) > 0 ? '+' + Number(o.bonus).toLocaleString() + ' bonus ad credits' : 'bonus ad credits';
$('cOfferText').innerHTML = 'Your first $5 package comes with <b>' + esc(b) + '</b>, and ' + esc(o.perk || 'a free hangar upgrade') + ' here in Drip Runner.';
var a = $('cOfferGo'); a.href = o.url || (IAP + '/my?from=driprunner#buy');
var framed = false; try { framed = window.self !== window.top; } catch (e) { framed = true; }
if (framed) { a.target = '_blank'; a.rel = 'noopener'; } else { a.removeAttribute('target'); a.removeAttribute('rel'); }
$('cOffer').hidden = false;
}
$('cOfferNo').addEventListener('click', function () { $('cOffer').hidden = true; });
$('bNext').addEventListener('click', function () { if (!R) return; R.paused = false; R.inv = 1.5; hideAll(); });
$('bShareClear').addEventListener('click', function () { share(this.dataset.text || 'Play Drip Runner with me:'); });
$('bShare').addEventListener('click', function () { share('I am playing Drip Runner, a game that pays in POL. Hop the network, dodge the bots:'); });
$('bShare').addEventListener('click', function () { share('Come play Drip Runner with me. Hop the network, dodge the bots:'); });
// Copy: the clipboard API where the page may use it, else select the field and copy, else a prompt to copy by hand
var copyT = null;
function copied(ok) {
var b = $('bCopy'); clearTimeout(copyT);
if (!ok) { window.prompt('Copy your invite link', ME_EXTRA.share); return; }
b.textContent = 'Copied!'; b.classList.add('done'); toast('Invite link copied. Paste it anywhere.');
copyT = setTimeout(function () { b.textContent = 'Copy link'; b.classList.remove('done'); }, 2200);
}
function copyFallback() { var f = $('invLink'), ok = false; try { f.focus(); f.select(); f.setSelectionRange(0, f.value.length); ok = document.execCommand('copy'); } catch (e) { ok = false; } f.blur(); copied(ok); }
$('bCopy').addEventListener('click', function () {
var url = ME_EXTRA.share; if (!url) return;
if (navigator.clipboard && navigator.clipboard.writeText && window.isSecureContext !== false) navigator.clipboard.writeText(url).then(function () { copied(true); }, copyFallback);
else copyFallback();
});
$('invLink').addEventListener('focus', function () { this.select(); });
$('bRestart').addEventListener('click', function () { endRun().then(newRun); });
function endRun() { var id = R && R.id; R = null; hideAll(); return id ? api('/api/run/end', { runId: id }).catch(function () {}) : Promise.resolve(); }
['bLobby1', 'bLobby2'].forEach(function (id) { $(id).addEventListener('click', function () { endRun().then(loadMe).then(lobby); }); });
@@ -192,15 +234,15 @@ function tryResume(q) {
/* ---------- hangar / balance ---------- */
function hangar() {
show('ovHangar'); $('hgBal').textContent = P.bank.toLocaleString() + ' drips · ' + f3(BAL.unpaid) + ' POL';
var pr = P.prices;
var pr = P.prices, free = P.freeUpgrades > 0; $('hgFree').hidden = !free; // the member perk: the next purchase costs nothing
set('itMagnet', 'magnet', P.items.magnet, P.bank >= pr.drips.magnet, pr.drips.magnet + ' drips', 'armed');
set('itShip', 'ship', P.items.ship, P.bank >= pr.drips.ship, pr.drips.ship + ' drips', 'owned');
set('itShield', 'shield', P.items.shield, BAL.unpaid >= pr.pol.shield, f3(pr.pol.shield) + ' POL', 'armed');
set('itSlow', 'slow', P.items.slow, BAL.unpaid >= pr.pol.slow, f3(pr.pol.slow) + ' POL', 'armed');
function set(id, key, own, can, label, ownLabel) { var it = $(id), b = it.querySelector('.buy'); it.classList.toggle('owned', !!own); b.className = 'buy' + (/POL/.test(label) ? ' pol' : '') + (own ? ' own' : (can ? '' : ' no')); b.textContent = own ? ownLabel : label; }
function set(id, key, own, can, label, ownLabel) { var it = $(id), b = it.querySelector('.buy'); it.classList.toggle('owned', !!own); b.className = 'buy' + (/POL/.test(label) ? ' pol' : '') + (own ? ' own' : (free ? ' free' : (can ? '' : ' no'))); b.textContent = own ? ownLabel : (free ? 'Free' : label); }
}
$('ovHangar').addEventListener('click', function (e) { var b = e.target.closest('[data-buy]'); if (!b) return; b.disabled = true;
api('/api/hangar/buy', { item: b.dataset.buy }).then(function (r) { b.disabled = false; if (r._status !== 200) return toast(r.error || 'Could not buy that.'); P = r.player; BAL = r.balance; sfx.buy(); toast('Paid ' + r.paid); hangar(); }); });
api('/api/hangar/buy', { item: b.dataset.buy }).then(function (r) { b.disabled = false; if (r._status !== 200) return toast(r.error || 'Could not buy that.'); P = r.player; BAL = r.balance; sfx.buy(); toast(r.free ? 'Free upgrade used. Enjoy the run!' : 'Paid ' + r.paid); hangar(); }); });
function balance() {
show('ovBal'); api('/api/balance').then(function (b) { BAL = b;
$('bPol').textContent = f3(b.unpaid); var pct = Math.min(100, b.unpaid / b.threshold * 100); $('bProg').style.width = pct + '%';
@@ -208,7 +250,11 @@ function balance() {
var h = ''; if (!b.history.length) h = '<div class="led"><span>No drips yet. Clear a chapter.</span><span class="m">0.000</span></div>';
b.history.forEach(function (l) { var cls = l.kind === 'payout' ? (l.status === 'paid' ? 'm ok' : l.status === 'failed' ? 'm neg' : 'm') : (l.pol < 0 ? 'm neg' : 'm'); h += '<div class="led"><span>' + esc(l.label) + (l.tx ? ' · <a href="https://polygonscan.com/tx/' + esc(l.tx) + '" target="_blank" rel="noopener">tx</a>' : '') + '</span><span class="' + cls + '">' + (l.kind === 'payout' ? '' : (l.pol < 0 ? '' : '+')) + f3(l.pol) + '</span></div>'; });
$('ledger').innerHTML = h;
$('bWallet').textContent = b.wallet ? 'Wallet: ' + b.wallet + ' (from your InstantAdPay account).' : 'No wallet on your InstantAdPay account yet. Link one there or payouts cannot be sent.';
// no wallet yet (2026-10-27): the link, never a line that implies the POL was sent; a player with a wallet sees the same line as before
var wl = b.wallet || (ME && ME.wallet);
if (wl) $('bWallet').textContent = 'Wallet: ' + wl + ' (from your InstantAdPay account).';
else if (hasW()) $('bWallet').textContent = 'Wallet linked on your InstantAdPay account. Your balance is sent to it at ' + b.threshold + ' POL.';
else $('bWallet').innerHTML = (b.unpaid > 0 ? '<b style="color:#f2b544">' + f3(b.unpaid) + ' POL is waiting.</b> ' : '') + '<span style="color:#f2b544">' + linkW() + '</span> (one free signature on InstantAdPay) and it is sent automatically, including everything earned so far.';
});
}
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]; }); }
@@ -251,12 +297,12 @@ resize(); requestAnimationFrame(loop);
loadMe().then(function () {
var q = new URLSearchParams(location.search);
if (q.get('resume')) { history.replaceState(null, '', '/play'); return tryResume(q); }
if (q.get('collected')) { history.replaceState(null, '', '/play'); setTimeout(function () { toast('Signed in. Your guest clears paid ' + q.get('collected') + ' drip' + (q.get('collected') === '1' ? '' : 's') + ' into your balance.'); }, 600); }
if (q.get('carried') || q.get('collected')) { history.replaceState(null, '', '/play'); setTimeout(function () { toast('Signed in. Your guest progress came with you. From here on your first clears earn POL.'); }, 600); } // guest runs earn nothing (2026-11-02)
lobby();
}).catch(function (r) {
var b = $('loadBtn'); b.hidden = false; b.href = (r && (r.signin || r.iap)) || '/signin';
if (r && r.guestOk) { // came through a share or tester link: play first, sign in later
$('loadTitle').textContent = 'Ready to run'; $('loadText').textContent = 'Play a run right now, no sign-in. Sign in with InstantAdPay when you want to keep your progress, refuel, and collect POL.';
$('loadTitle').textContent = 'Ready to run'; $('loadText').textContent = 'Play a run right now, no sign-in. Guest runs earn no POL: sign in with InstantAdPay (free) to earn a taste on every chapter you clear, refuel, and keep your progress. The Game Pass pays the full table.';
b.textContent = 'Sign in with InstantAdPay'; b.className = 'btn ghost'; var g = $('loadGuest'); g.hidden = false;
g.onclick = function () { g.disabled = true; api('/api/guest', {}).then(function (x) { if (x._status !== 200) { g.disabled = false; return toast(x.error || 'Could not start a guest run.'); } return loadMe().then(function () { lobby(); newRun(); }); }); };
return;
+28 -28
View File
@@ -1,28 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="robots" content="noindex,nofollow">
<title>Sign in · Drip Runner</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Orbitron:wght@600;800;900&family=Manrope:wght@400;600;800&display=swap">
<link rel="stylesheet" href="/site.css">
<style>
html{background:#050912}
.si{max-width:420px;margin:0 auto;padding-top:36px;display:grid;gap:18px}
.si .logo{font-size:30px;text-align:center}
.si .card{--si-accent:var(--cyan);--si-accent-ink:#04121a;--si-ink:var(--ink);--si-muted:var(--ink2);--si-field:rgba(5,9,18,.6);--si-line:var(--line);--si-font:var(--body);--si-bad:#ff7a9c}
.si .card h2{margin:0}
.si .back{text-align:center;font-size:14px}.si .back a{color:var(--muted)}
</style>
</head>
<body>
<main class="si">
<a href="/" style="text-decoration:none"><p class="logo">Drip <span>Runner</span></p></a>
<section class="card" id="iapSignin"><p>Loading sign-in…</p></section>
<p class="back"><a href="/play">Keep playing as a guest</a></p>
</main>
<script src="https://instantadpay.com/assets/game-signin.js?v=20261003a"></script>
<script src="/signin.js"></script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="robots" content="noindex,nofollow">
<title>Sign in · Drip Runner</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Orbitron:wght@600;800;900&family=Manrope:wght@400;600;800&display=swap">
<link rel="stylesheet" href="/site.css">
<style>
html{background:#050912}
.si{max-width:420px;margin:0 auto;padding-top:36px;display:grid;gap:18px}
.si .logo{font-size:30px;text-align:center}
.si .card{--si-accent:var(--cyan);--si-accent-ink:#04121a;--si-ink:var(--ink);--si-muted:var(--ink2);--si-field:rgba(5,9,18,.6);--si-line:var(--line);--si-font:var(--body);--si-bad:#ff7a9c}
.si .card h2{margin:0}
.si .back{text-align:center;font-size:14px}.si .back a{color:var(--muted)}
</style>
</head>
<body>
<main class="si">
<a href="/" style="text-decoration:none"><p class="logo">Drip <span>Runner</span></p></a>
<section class="card" id="iapSignin"><p>Loading sign-in…</p></section>
<p class="back"><a href="/play">Keep playing as a guest</a></p>
</main>
<script src="https://instantadpay.com/assets/game-signin.js?v=20261003b"></script>
<script src="/signin.js?v=20261005b"></script>
</body>
</html>
+3 -1
View File
@@ -4,5 +4,7 @@
var box = document.getElementById('iapSignin');
if (!window.IAPSignin) { box.innerHTML = '<p>Sign-in could not load. <a href="https://instantadpay.com/api/my/driprunner" style="color:var(--cyan)">Sign in on InstantAdPay instead</a>.</p>'; return; }
var m = /(?:^|;\s*)dr\.ref=([^;]+)/.exec(document.cookie || ''); // the share link a guest arrived on: their sponsor
IAPSignin.mount(box, { game: 'driprunner', ref: m ? decodeURIComponent(m[1]) : '', title: 'Sign in to run', oneTap: IAPSignin.origin + '/api/my/driprunner' });
var s = /(?:^|;\s*)dr\.src=([^;]+)/.exec(document.cookie || ''); // paid-traffic source, if any (2026-10-03)
var q = String(new URLSearchParams(location.search).get('ref') || '').replace(/[^A-Za-z0-9_.-]/g, '').slice(0, 40); // /signin?ref=<name> works even where the cookie was refused (2026-10-05)
IAPSignin.mount(box, { game: 'driprunner', src: s ? decodeURIComponent(s[1]).split('|')[0] : '', ref: q || (m ? decodeURIComponent(m[1]) : ''), title: 'Sign in to run', oneTap: IAPSignin.origin + '/api/my/driprunner' });
})();
+1 -1
View File
@@ -29,7 +29,7 @@
<li><b>Tap to hop.</b> The courier drops when you do nothing and hops when you tap. Space bar works on a computer.</li>
<li><b>Gold drips</b> are the score. <b>Magenta bots</b> end the run. From chapter 2, <b>orange firewalls</b> have to be threaded through the gap.</li>
<li><b>Fuel</b> drains all the time. Every drip tops it up a little. Empty tank, run over.</li>
<li><b>Chapters.</b> Each chapter has a drip goal for one run. Clear it and you move up. The first time you clear a chapter, a drip of POL lands in your game balance.</li>
<li><b>Chapters.</b> Each chapter has a drip goal for one run. Clear it and you move up. Signed in, the first time you clear a chapter a drip of POL lands in your game balance (a free account earns a taste of it, Game Pass holders the full drip). Guest runs earn no POL.</li>
</ul>
<h2>Where the POL comes from</h2>
+459 -349
View File
@@ -1,349 +1,459 @@
// Drip Runner: a hop-and-collect game for InstantAdPay members, paid in POL, funded by the
// verified visits players make to refuel. Trial build (2026-09-30).
//
// Gates, all default-deny, all from the environment:
// CURTAIN=<secret> the tester page at / shows "Coming soon" to anyone without ?k=<secret>
// OUTBOUND=on required before anything leaves this server (Telegram to Marty). No mailer exists.
// DR_SSO_SECRET shared with InstantAdPay: hand-off tokens, refuel tokens, receipts, callbacks
// ADMIN_KEY the admin page and API
// IAP_URL https://instantadpay.com (where refuel visits happen)
// SITE_URL this app's public URL
// DR_WALLET_KEY / DR_RPC / DR_CHAIN_ID / DR_DRY_RUN the faucet (lib/faucet.js)
// DR_TG_TOKEN / DR_TG_CHAT Marty's private alerts (payouts, failures, low balance)
// Who may sign in is a setting (admin page): 'testers' (allowlist), 'open', 'closed'.
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const store = require('./lib/store');
const sso = require('./lib/sso');
const game = require('./lib/game');
const ledger = require('./lib/ledger');
const faucet = require('./lib/faucet');
const spawn = require('./lib/spawn');
const badge = require('./lib/badge');
const tips = require('./lib/tips'); // facts you learn as you play, priced from the live IAP catalog
const PORT = Number(process.env.PORT || 3000);
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const PUBLIC_DIR = path.join(__dirname, 'public');
const CURTAIN = String(process.env.CURTAIN || '').trim();
const ADMIN_KEY = String(process.env.ADMIN_KEY || '').trim();
const SITE = String(process.env.SITE_URL || 'https://driprunner.saasy.top').replace(/\/+$/, '');
const IAP = String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
const SECRET = String(process.env.DR_SSO_SECRET || '').trim();
const outbound = () => process.env.OUTBOUND === 'on';
const IS_PROD = process.env.NODE_ENV === 'production';
store.init(DATA_DIR);
badge.init({ publicDir: PUBLIC_DIR, dataDir: DATA_DIR });
const faucetOn = faucet.init();
// ---- Telegram to Marty (outward: gated) -------------------------------------------------------
async function telegram(text) {
if (!outbound()) return false;
const tok = process.env.DR_TG_TOKEN, chat = process.env.DR_TG_CHAT; if (!tok || !chat) return false;
try { const r = await fetch('https://api.telegram.org/bot' + tok + '/sendMessage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chat_id: chat, text, parse_mode: 'HTML', disable_web_page_preview: true }) }); return r.ok; } catch (e) { return false; }
}
const fmt = n => Number(n).toLocaleString('en-US', { maximumFractionDigits: 4 });
// ---- public badge posts (Marty, 2026-09-30): unlocks, chapter and refuel milestones, payouts, as photo cards ----
// DR_TG_PUBLIC_CHAT / DR_TG_PUBLIC_TOPIC = the room (PolHunter's), DR_TG_PUBLIC_GENERAL=on also posts the photo to the general channel.
async function telegramPhoto(file, caption, general, 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('<b>Drip Runner</b>', '<b>Drip Runner</b> <i>(coming soon \u00b7 now in testing)</i>') : opts.caption;
const foot = trial() ? '<i>Testers are playing a preview. When Drip Runner goes live, amounts like this pay out in POL to the wallet on your InstantAdPay account.</i>' : '<i>Play from your InstantAdPay dashboard.</i>';
const cap = head + '\n' + line2 + '\n' + foot;
if (!file) return telegram(cap);
const ok = await telegramPhoto(file, cap, 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} <b>Drip Runner</b> \u00b7 <b>' + nameOf(me) + '</b> unlocked the <b>' + ITEM_NAMES[item] + '</b> (' + paid + ')', topic: ACH() }).catch(() => {}); }
function announceChapter(me, ch, pol) { const id = badge.CHAPTER_BADGES[ch]; if (!id) return; announce(id, me, { caption: '\u{1F3C1} <b>Drip Runner</b> \u00b7 <b>' + nameOf(me) + '</b> cleared <b>Chapter ' + ch + '</b>' + (pol ? ' \u00b7 <b>+' + fmt(pol) + ' POL</b>' : ''), 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 <b>Drip Runner</b> \u00b7 <b>' + nameOf(me) + '</b> has refuelled <b>' + n + ' times</b>. Every refuel is a verified visit to a member\u2019s page on InstantAdPay.', topic: ACH() }).catch(() => {}); }
function announcePaid(p) { announce('paid', { memberId: p.memberId, username: p.username }, { key: 'paid:' + p.id, caption: '\u{1F4B8} <b>Drip Runner</b> \u00b7 <b>' + nameOf(p) + '</b> was paid <b>' + fmt(p.pol) + ' POL</b> \u00b7 <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>', line2: 'paid ' + fmt(p.pol) + ' POL to their wallet \u00b7 ' + earningsLine(p.memberId).replace(/^earned [^\u00b7]+\u00b7 /, '') }).catch(() => {}); }
const explorer = () => Number(process.env.DR_CHAIN_ID) === 80002 ? 'https://amoy.polygonscan.com' : 'https://polygonscan.com';
async function notify(kind, p) {
const who = p && (p.username ? '@' + p.username : '#' + p.memberId);
if (kind === 'paid') { announcePaid(p); return telegram('\u{1F3AE} <b>Drip Runner</b> · paid ' + who + ' <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>'); }
if (kind === 'failed') return telegram('❌ <b>Drip Runner</b> · payout to ' + who + ' failed: ' + p.error);
if (kind === 'low') return telegram('⚠️ <b>Drip Runner wallet is low</b>: ' + fmt(p.balance) + ' POL in ' + p.address + ' (needs ' + fmt(p.threshold) + ').');
if (kind === 'refused') return telegram('\u{1F6AB} <b>Drip Runner</b> \u00b7 ' + who + ' (' + p.email + ') tried to sign in but is not on the tester list. Add them under Admin > Settings > Testers: ' + SITE + '/admin');
if (kind === 'signin') return telegram('\u{1F44B} <b>Drip Runner</b> · first sign-in: ' + who + ' (' + (p.wallet ? 'wallet on file' : 'NO wallet yet') + ')');
if (kind === 'refuel') return telegram('⛽ <b>Drip Runner</b> · ' + who + ' refuelled on campaign #' + p.campaignId + ': +' + fmt(p.pol) + ' POL to the pool (' + p.credits + ' credits, $' + p.share + ' share)');
return false;
}
// ---- helpers ---------------------------------------------------------------------------------
const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.webp': 'image/webp', '.mp4': 'video/mp4' };
// 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:; connect-src 'self' " + IAP + "; frame-ancestors 'none'; form-action 'self' " + IAP;
const SEC = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'X-Frame-Options': 'DENY', 'Content-Security-Policy': CSP };
function json(res, code, body, extra) { res.writeHead(code, Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, SEC, extra || {})); res.end(JSON.stringify(body)); }
function sendFile(res, file, extra) {
fs.readFile(file, (err, buf) => {
if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
res.writeHead(200, Object.assign({ 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store' }, SEC, extra || {}));
res.end(buf);
});
}
function page(res, code, title, body, extra) {
res.writeHead(code, Object.assign({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }, SEC, extra || {}));
res.end('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>' + title + '</title><link rel="stylesheet" href="/site.css"></head><body class="plain"><main class="card"><h1>' + title + '</h1>' + body + '</main></body></html>');
}
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
function readBody(req) {
return new Promise(resolve => { let d = ''; req.on('data', c => { d += c; if (d.length > 200000) req.destroy(); }); req.on('end', () => { let j = {}; try { j = JSON.parse(d || '{}'); } catch (e) {} resolve({ raw: d, body: j }); }); });
}
const CURTAIN_PAGE = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>Coming soon</title><style>*{margin:0;padding:0;box-sizing:border-box}html,body{height:100%}body{display:flex;align-items:center;justify-content:center;padding:24px;background:#050912;color:#e6edf3;font:16px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif}.card{max-width:420px;text-align:center}h1{font-size:clamp(28px,7vw,44px);font-weight:700;margin-bottom:14px}p{color:#8b949e}</style></head><body><div class="card"><h1>Coming soon</h1><p>This site is still being built.</p></div></body></html>';
function curtained(req, res, u) {
if (!CURTAIN) return false;
if (u.searchParams.get('k') === CURTAIN) { u.searchParams.delete('k'); res.writeHead(302, { 'Set-Cookie': 'dr.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : ''), Location: u.pathname + (u.searchParams.toString() ? '?' + u.searchParams : ''), 'Cache-Control': 'no-store' }); res.end(); return true; }
const m = /(?:^|;\s*)dr\.pass=([^;]+)/.exec(req.headers.cookie || '');
if (m && decodeURIComponent(m[1]) === CURTAIN) return false;
res.writeHead(503, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' }); res.end(req.method === 'HEAD' ? '' : CURTAIN_PAGE); return true;
}
function admin(req, u) { const k = req.headers['x-admin-key'] || u.searchParams.get('key'); return !!(ADMIN_KEY && k && k.length === ADMIN_KEY.length && crypto.timingSafeEqual(Buffer.from(k), Buffer.from(ADMIN_KEY))); }
// who may come through the hand-off
// 'key' (Marty, 2026-09-30: "let anyone I send the link to with the key test"): the hand-off is accepted when the
// browser carries the curtain pass, i.e. the person opened the tester link with the key first. The list still works too.
function hasPass(req) { const m = /(?:^|;\s*)dr\.pass=([^;]+)/.exec(req.headers.cookie || ''); return !!(CURTAIN && m && decodeURIComponent(m[1]) === CURTAIN); }
function allowed(claims, req) {
const s = ledger.settings(); const mode = String(process.env.DR_SIGNUPS || s.signups || 'testers');
if (mode === 'open') return true; if (mode === 'closed') return false;
const list = (s.testers || []).map(x => String(x).trim().toLowerCase()).filter(Boolean);
if (list.includes(String(claims.email || '').toLowerCase()) || list.includes(String(claims.memberId)) || (claims.username && list.includes(String(claims.username).toLowerCase()))) return true; // email, member id or IAP username
return mode === 'key' && req && hasPass(req);
}
// the IAP -> game callback is signed over the timestamp and the raw body with the shared secret
function callbackOk(req, raw) {
const ts = String(req.headers['x-dr-ts'] || ''), sig = String(req.headers['x-dr-sig'] || '');
if (!SECRET || !ts || !sig || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return false;
const want = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex');
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
}
const intents = { get: n => store.read('refuel-intents', {})[n] || null, set: (n, v) => store.update('refuel-intents', {}, all => { const cut = Date.now() - 86400000; for (const k of Object.keys(all)) if (all[k].ts < cut) delete all[k]; all[n] = v; return all; }), upd: (n, fn) => store.update('refuel-intents', {}, all => { if (all[n]) fn(all[n]); return all; })[n] };
async function creditRefuel(intent, nonce, info) {
if (intent.credited) return intent;
const me = { memberId: intent.memberId, username: intent.username, wallet: intent.wallet };
const 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', '<p>' + esc(r.error) + '</p><p><a class="btn" href="/signin">Try again</a></p>');
if (!allowed(r.claims, req)) { console.log('hand-off refused: not a tester', r.claims.memberId, r.claims.username || '', String(r.claims.email || '').replace(/^(.).*(@.*)$/, '$1***$2')); notify('refused', { memberId: r.claims.memberId, username: r.claims.username, email: r.claims.email }).catch(() => {}); }
if (!allowed(r.claims, req)) { const keyMode = String(process.env.DR_SIGNUPS || ledger.settings().signups) === 'key'; return page(res, 403, keyMode ? 'Open the tester link first' : 'Not on the tester list yet', keyMode ? '<p>Drip Runner is in a closed trial. Open the tester link Marty sent you (the one with the key) in this same browser, then tap Open Drip Runner again. Your InstantAdPay account is ' + esc(r.claims.username ? '@' + r.claims.username : '#' + r.claims.memberId) + '.</p>' : '<p>Drip Runner is in a closed trial. Your InstantAdPay account (' + esc(r.claims.username ? '@' + r.claims.username : '#' + r.claims.memberId) + ') is not on the tester list. Ask Marty to add you.</p>'); }
const existing = sso.fromRequest(req);
let sid;
if (existing && existing.memberId === Number(r.claims.memberId)) { sso.refresh(existing.sid, r.claims); sid = existing.sid; }
else sid = sso.startSession(r.claims);
// 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 === '/signin') return sendFile(res, path.join(PUBLIC_DIR, 'signin.html')); // 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 })), 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 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.' });
}
});
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 } });
}
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=<secret> the tester page at / shows "Coming soon" to anyone without ?k=<secret>
// OUTBOUND=on required before anything leaves this server (Telegram to Marty). No mailer exists.
// DR_SSO_SECRET shared with InstantAdPay: hand-off tokens, refuel tokens, receipts, callbacks
// ADMIN_KEY the admin page and API
// IAP_URL https://instantadpay.com (where refuel visits happen)
// SITE_URL this app's public URL
// DR_WALLET_KEY / DR_RPC / DR_CHAIN_ID / DR_DRY_RUN the faucet (lib/faucet.js)
// DR_TG_TOKEN / DR_TG_CHAT Marty's private alerts (payouts, failures, low balance)
// Who may sign in is a setting (admin page): 'testers' (allowlist), 'open', 'closed'.
'use strict';
const http = require('http');
const discordRelay = require('./discord-relay.cjs'); // mirror group posts into the CTB Discord (2026-10-09)
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();
// Game Pass bridge (GAMEPASS=on, docs/GAME-PASS.md 3a): signed calls to InstantAdPay's polgrant with the same shared secret; stuck grants alert like the faucet
ledger.gp.use({ game: 'driprunner', secret: SECRET, iap: IAP, store, notify: (kind, p) => notify(kind, p) });
// ---- 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;
discordRelay.mirror({ chatId: chat, threadId: topic && !general ? Number(topic) : undefined, text: caption, photo: fs.readFileSync(file) });
try {
const fd = new FormData(); fd.append('chat_id', chat); fd.append('caption', caption); fd.append('parse_mode', 'HTML'); if (topic && !general) fd.append('message_thread_id', String(topic));
fd.append('photo', new Blob([fs.readFileSync(file)], { type: 'image/jpeg' }), 'badge.jpg');
const r = await fetch('https://api.telegram.org/bot' + tok + '/sendPhoto', { method: 'POST', body: fd }); return r.ok;
} catch (e) { return false; }
}
const nameOf = me => me.username ? '@' + me.username : '#' + me.memberId;
const trial = () => ledger.settings().trial !== false; // Marty, 2026-09-30: while testing, say so, and show what they WOULD have earned once live
function earningsLine(memberId) {
const a = ledger.account(memberId); const p = game.player(memberId) || {}; const refuels = store.read('refuels', []).filter(r => r.memberId === Number(memberId)).length;
return (trial() ? 'would have earned ' : 'earned ') + fmt(a.earnedTotal || 0) + ' POL so far \u00b7 ' + refuels + ' refuel' + (refuels === 1 ? '' : 's') + ' \u00b7 chapter ' + (p.chapter || 1);
}
// one post per (member, badge); a payout card is one per payout row
async function announce(id, me, opts) {
opts = opts || {}; const key = opts.key || id;
const posted = store.read('posted', {}); const mine = new Set(posted[String(me.memberId)] || []);
if (mine.has(key)) return false;
store.update('posted', {}, all => { all[String(me.memberId)] = [...mine, key]; return all; });
const line2 = opts.line2 || earningsLine(me.memberId);
const file = await badge.render(id, nameOf(me), line2, trial() ? 'COMING SOON \u00b7 NOW IN TESTING' : '');
const head = trial() ? opts.caption.replace('<b>Drip Runner</b>', '<b>Drip Runner</b> <i>(coming soon \u00b7 now in testing)</i>') : opts.caption;
const foot = trial() ? '<i>Testers are playing a preview. When Drip Runner goes live, amounts like this pay out in POL to the wallet on your InstantAdPay account.</i>' : '<i>Play from your InstantAdPay dashboard.</i>';
const cap = head + '\n' + line2 + '\n' + foot;
if (!file) return telegram(cap);
const ok = await telegramPhoto(file, cap, 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} <b>Drip Runner</b> \u00b7 <b>' + nameOf(me) + '</b> unlocked the <b>' + ITEM_NAMES[item] + '</b> (' + paid + ')', topic: ACH() }).catch(() => {}); }
function announceChapter(me, ch, pol) { const id = badge.CHAPTER_BADGES[ch]; if (!id) return; announce(id, me, { caption: '\u{1F3C1} <b>Drip Runner</b> \u00b7 <b>' + nameOf(me) + '</b> cleared <b>Chapter ' + ch + '</b>' + (pol ? ' \u00b7 <b>+' + fmt(pol) + ' POL</b>' : ''), 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 <b>Drip Runner</b> \u00b7 <b>' + nameOf(me) + '</b> has refuelled <b>' + n + ' times</b>. Every refuel is a verified visit to a member\u2019s page on InstantAdPay.', topic: ACH() }).catch(() => {}); }
function announcePaid(p) { announce('paid', { memberId: p.memberId, username: p.username }, { key: 'paid:' + p.id, caption: '\u{1F4B8} <b>Drip Runner</b> \u00b7 <b>' + nameOf(p) + '</b> was paid <b>' + fmt(p.pol) + ' POL</b> \u00b7 <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>', line2: 'paid ' + fmt(p.pol) + ' POL to their wallet \u00b7 ' + earningsLine(p.memberId).replace(/^earned [^\u00b7]+\u00b7 /, '') }).catch(() => {}); }
const explorer = () => Number(process.env.DR_CHAIN_ID) === 80002 ? 'https://amoy.polygonscan.com' : 'https://polygonscan.com';
async function notify(kind, p) {
const who = p && (p.username ? '@' + p.username : '#' + p.memberId);
// the payout card already goes to the shared payments topic (announcePaid); the private copy to Marty was a duplicate
// of every public line and stopped 2026-11-02 on his word. Failures and low-wallet alerts stay private below.
if (kind === 'paid') { announcePaid(p); return Promise.resolve(true); }
if (kind === 'failed') return telegram('❌ <b>Drip Runner</b> · payout to ' + who + ' failed: ' + p.error);
if (kind === 'low') return telegram('⚠️ <b>Drip Runner wallet is low</b>: ' + fmt(p.balance) + ' POL in ' + p.address + ' (needs ' + fmt(p.threshold) + ').');
if (kind === 'gpstuck') return telegram('⚠️ <b>Drip Runner</b> Game Pass grant stuck 48 h: member #' + p.memberId + ' ' + (p.email || '') + ' ref ' + p.ref + ' (' + fmt(p.pol) + ' POL, ' + p.kind + '). InstantAdPay /api/partner/polgrant unreachable: ' + (p.error || '?'));
if (kind === 'refused') return telegram('\u{1F6AB} <b>Drip Runner</b> \u00b7 ' + who + ' (' + p.email + ') tried to sign in but is not on the tester list. Add them under Admin > Settings > Testers: ' + SITE + '/admin');
if (kind === 'signin') return telegram('\u{1F44B} <b>Drip Runner</b> · first sign-in: ' + who + ' (' + (p.wallet ? 'wallet on file' : 'NO wallet yet') + ')' + (p.via ? ' · came in through ' + p.via + ', played as a guest first (guest runs earn nothing)' : ''));
if (kind === 'refuel') return telegram('⛽ <b>Drip Runner</b> · ' + who + ' refuelled on campaign #' + p.campaignId + ': +' + fmt(p.pol) + ' POL to the pool (' + p.credits + ' credits, $' + p.share + ' share)');
return false;
}
// ---- helpers ---------------------------------------------------------------------------------
const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.webp': 'image/webp', '.mp4': 'video/mp4' };
// 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('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>' + title + '</title><link rel="stylesheet" href="/site.css"></head><body class="plain"><main class="card"><h1>' + title + '</h1>' + body + '</main></body></html>');
}
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
function readBody(req) {
return new Promise(resolve => { let d = ''; req.on('data', c => { d += c; if (d.length > 200000) req.destroy(); }); req.on('end', () => { let j = {}; try { j = JSON.parse(d || '{}'); } catch (e) {} resolve({ raw: d, body: j }); }); });
}
const CURTAIN_PAGE = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>Coming soon</title><style>*{margin:0;padding:0;box-sizing:border-box}html,body{height:100%}body{display:flex;align-items:center;justify-content:center;padding:24px;background:#050912;color:#e6edf3;font:16px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif}.card{max-width:420px;text-align:center}h1{font-size:clamp(28px,7vw,44px);font-weight:700;margin-bottom:14px}p{color:#8b949e}</style></head><body><div class="card"><h1>Coming soon</h1><p>This site is still being built.</p></div></body></html>';
function curtained(req, res, u) {
if (!CURTAIN) return false;
if (u.searchParams.get('k') === CURTAIN) { u.searchParams.delete('k'); res.writeHead(302, { 'Set-Cookie': 'dr.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : ''), Location: u.pathname + (u.searchParams.toString() ? '?' + u.searchParams : ''), 'Cache-Control': 'no-store' }); res.end(); return true; }
const m = /(?:^|;\s*)dr\.pass=([^;]+)/.exec(req.headers.cookie || '');
if (m && decodeURIComponent(m[1]) === CURTAIN) return false;
res.writeHead(503, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' }); res.end(req.method === 'HEAD' ? '' : CURTAIN_PAGE); return true;
}
function admin(req, u) { const k = req.headers['x-admin-key'] || u.searchParams.get('key'); return !!(ADMIN_KEY && k && k.length === ADMIN_KEY.length && crypto.timingSafeEqual(Buffer.from(k), Buffer.from(ADMIN_KEY))); }
// who may come through the hand-off
// 'key' (Marty, 2026-09-30: "let anyone I send the link to with the key test"): the hand-off is accepted when the
// browser carries the curtain pass, i.e. the person opened the tester link with the key first. The list still works too.
function hasPass(req) { const m = /(?:^|;\s*)dr\.pass=([^;]+)/.exec(req.headers.cookie || ''); return !!(CURTAIN && m && decodeURIComponent(m[1]) === CURTAIN); }
function allowed(claims, req) {
const s = ledger.settings(); const mode = String(process.env.DR_SIGNUPS || s.signups || 'testers');
if (mode === 'open') return true; if (mode === 'closed') return false;
const list = (s.testers || []).map(x => String(x).trim().toLowerCase()).filter(Boolean);
if (list.includes(String(claims.email || '').toLowerCase()) || list.includes(String(claims.memberId)) || (claims.username && list.includes(String(claims.username).toLowerCase()))) return true; // email, member id or IAP username
return mode === 'key' && req && hasPass(req);
}
// the IAP -> game callback is signed over the timestamp and the raw body with the shared secret
function callbackOk(req, raw) {
const ts = String(req.headers['x-dr-ts'] || ''), sig = String(req.headers['x-dr-sig'] || '');
if (!SECRET || !ts || !sig || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return false;
const want = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex');
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
}
const intents = { get: n => store.read('refuel-intents', {})[n] || null, set: (n, v) => store.update('refuel-intents', {}, all => { const cut = Date.now() - 86400000; for (const k of Object.keys(all)) if (all[k].ts < cut) delete all[k]; all[n] = v; return all; }), upd: (n, fn) => store.update('refuel-intents', {}, all => { if (all[n]) fn(all[n]); return all; })[n] };
async function creditRefuel(intent, nonce, info) {
if (intent.credited) return intent;
const me = { memberId: intent.memberId, username: intent.username, wallet: intent.wallet };
const 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;
// InstantAdPay asks every hour which players have POL waiting and no wallet linked (wallet-link nudges,
// 2026-10-07). GET /api/iap/unpaid?ts=<ms>&sig=<hex HMAC-SHA256(shared secret, 'unpaid\n' + ts)>, 10-minute window.
if (p === '/api/iap/unpaid' && req.method === 'GET') {
const ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || '');
const sec = SECRET;
if (!sec || sec.length < 32 || !ts || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return json(res, 401, { error: 'bad signature' });
const want = crypto.createHmac('sha256', sec).update('unpaid\n' + ts).digest('hex');
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' });
const accts = store.read('accounts', {}), players = store.read('players', {}); const rows = Object.entries(accts).filter(([k, a]) => Number(a.unpaid) > 0 && !a.wallet).map(([k, a]) => ({ memberId: Number(k), username: a.username || (players[k] || {}).username || null, email: (players[k] || {}).email || null, unpaid: Number(Number(a.unpaid).toFixed(4)) }));
return json(res, 200, { ok: true, game: 'driprunner', rows });
}
// InstantAdPay pushes the wallet a member linked after their last hand-off (2026-10-25: solanaclick had 1.5 POL stuck behind
// a remembered game session that never saw the wallet). POST JSON {email, wallet, username, memberId}; headers X-IAP-Ts and
// X-IAP-Sig = hex HMAC-SHA256(shared secret, 'wallet\n' + ts + '\n' + hex sha256(body)), 10-minute window. It fills an EMPTY
// wallet through the same setWallet path /auth uses; the same wallet again is a no-op; a different wallet is refused, never replaced.
if (p === '/api/iap/wallet' && req.method === 'POST') {
const raw = await new Promise(ok => { let d = ''; req.on('data', c => { d += c; if (d.length > 20000) req.destroy(); }); req.on('end', () => ok(d)); req.on('error', () => ok('')); });
const ts = String(req.headers['x-iap-ts'] || ''), sig = String(req.headers['x-iap-sig'] || '');
if (SECRET.length < 32 || !ts || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return json(res, 401, { error: 'bad signature' });
const want = crypto.createHmac('sha256', SECRET).update('wallet\n' + ts + '\n' + crypto.createHash('sha256').update(raw).digest('hex')).digest('hex');
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' });
let b; try { b = JSON.parse(raw); } catch (e) { return json(res, 400, { error: 'bad body' }); }
const em = String((b && b.email) || '').trim().toLowerCase(), w = String((b && b.wallet) || '').trim(), uname = (b && b.username) ? String(b.username).slice(0, 40) : null;
const mid0 = Number(b && b.memberId) || 0;
// since 2026-10-27 IAP pushes the signature-linked wallet whether or not it is activated on chain: memberId is 0 (or missing)
// for a member who is not on chain yet, and that player lives here under sso.emailId(email), so the wallet goes there
if (!em || mid0 < 0 || !/^0x[a-f0-9]{40}$/i.test(w)) return json(res, 400, { error: 'bad email, member id or wallet' });
try {
// Drip Runner keys players by member id; a wallet-less member played under sso.emailId(email) (negative). /auth moves that
// history onto the real id with game.adopt; the push does the same, then fills the wallet on the account.
const wl = w.toLowerCase(), eid = sso.emailId(em), mid = mid0 > 0 ? mid0 : eid, acc0 = store.read('accounts', {}), pls0 = store.read('players', {});
if (!acc0[String(mid)] && !pls0[String(mid)] && !acc0[String(eid)] && !pls0[String(eid)]) return json(res, 404, { error: 'unknown player' });
const had = (acc0[String(mid)] && acc0[String(mid)].wallet) || null, mask = em.replace(/^(..).*(@.*)$/, '$1***$2');
if (had && had.toLowerCase() !== wl) { console.log(new Date().toISOString(), 'iap wallet push REFUSED (a different wallet is set)', mask, mid, had, wl); return json(res, 409, { error: 'a different wallet is already set', wallet: had }); }
let adopted = false; if (mid !== eid && pls0[String(eid)]) adopted = !!game.adopt(eid, mid).moved;
// fill an empty wallet only; a player with no account row yet (nothing earned so far) gets one holding the wallet, so the
// POL they earn next is paid by the sweep even when their game session never saw the wallet
const hasPlayer = !!store.read('players', {})[String(mid)];
store.update('accounts', {}, all => { let x = all[String(mid)]; if (!x && hasPlayer) x = all[String(mid)] = { memberId: mid, unpaid: 0, paidTotal: 0, spentTotal: 0, earnedTotal: 0 }; if (x && !x.wallet) { x.wallet = wl; x.username = x.username || uname || null; x.email = x.email || em; } return all; });
if (hasPlayer) game.updPlayer(mid, x => { x.email = x.email || em; x.username = uname || x.username || null; if (!x.wallet) x.wallet = wl; });
const acc = store.read('accounts', {})[String(mid)] || {}, unpaid = Number(Number(acc.unpaid || 0).toFixed(4)), changed = !had && !!acc.wallet;
if (changed || adopted) store.update('iapwallets', [], l => { l.unshift({ at: Date.now(), email: em, memberId: mid0, local: mid, wallet: wl, adopted, unpaid }); return l.slice(0, 300); });
console.log(new Date().toISOString(), 'iap wallet push', changed ? 'FILLED' : had ? 'already set' : 'no account', mask, mid, wl, adopted ? 'adopted ' + eid : '', 'unpaid', unpaid);
return json(res, 200, { ok: true, changed, adopted, wallet: acc.wallet || null, unpaid });
} catch (e) { console.error('iap wallet push', e.message); return json(res, 500, { error: 'failed' }); }
}
// 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', '<p>' + esc(r.error) + '</p><p><a class="btn" href="/signin">Try again</a></p>');
if (!allowed(r.claims, req)) { console.log('hand-off refused: not a tester', r.claims.memberId, r.claims.username || '', String(r.claims.email || '').replace(/^(.).*(@.*)$/, '$1***$2')); notify('refused', { memberId: r.claims.memberId, username: r.claims.username, email: r.claims.email }).catch(() => {}); }
if (!allowed(r.claims, req)) { const keyMode = String(process.env.DR_SIGNUPS || ledger.settings().signups) === 'key'; return page(res, 403, keyMode ? 'Open the tester link first' : 'Not on the tester list yet', keyMode ? '<p>Drip Runner is in a closed trial. Open the tester link Marty sent you (the one with the key) in this same browser, then tap Open Drip Runner again. Your InstantAdPay account is ' + esc(r.claims.username ? '@' + r.claims.username : '#' + r.claims.memberId) + '.</p>' : '<p>Drip Runner is in a closed trial. Your InstantAdPay account (' + esc(r.claims.username ? '@' + r.claims.username : '#' + r.claims.memberId) + ') is not on the tester list. Ask Marty to add you.</p>'); }
const existing = sso.fromRequest(req);
let sid;
if (existing && existing.memberId === Number(r.claims.memberId)) { sso.refresh(existing.sid, r.claims); sid = existing.sid; }
else sid = sso.startSession(r.claims);
// 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'); }
// a guest's progress (chapters, drips, best) follows them; guest rewards never turn into POL (Marty 2026-11-02: guests earn nothing)
const carried = guest ? !!game.adopt(guest.memberId, r.claims.memberId).moved : false;
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(); });
// the hand-off wallet is the member's signature-linked wallet (on chain or not, 2026-10-27): it fills an EMPTY account wallet
// so POL already earned pays on the next sweep; an account that already has a wallet keeps it
if (r.claims.wallet && /^0x[a-f0-9]{40}$/i.test(String(r.claims.wallet))) store.update('accounts', {}, all => { const x = all[String(r.claims.memberId)]; if (x && !x.wallet) x.wallet = String(r.claims.wallet).toLowerCase(); return all; });
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)
if (r.claims.gamePass != null) ledger.gp.rememberPass(ledger.iapId(r.claims), r.claims.email, r.claims.gamePass); // the Game Pass flag rides on the hand-off as gamePass:{active,until} (GAME-PASS.md 3a item 7)
{ 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' + (carried ? '?carried=1' : ''), '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, part of the Crypto Team Build Network. Play free; sign in with a free InstantAdPay account to earn POL on every chapter you clear, and the Game Pass pays the full reward.';
res.writeHead(200, Object.assign({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }, SEC));
return res.end('<!doctype html><html><head><meta charset="utf-8"><title>' + esc(t) + '</title><meta name="description" content="' + esc(d) + '"><meta property="og:type" content="website"><meta property="og:site_name" content="Drip Runner"><meta property="og:url" content="' + esc(SITE + '/r/' + mr[1]) + '"><meta property="og:title" content="' + esc(t) + '"><meta property="og:description" content="' + esc(d) + '"><meta property="og:image" content="' + esc(nm ? card : SITE + '/og-driprunner.jpg') + '"><meta property="og:image:width" content="' + (nm ? 1080 : 1200) + '"><meta property="og:image:height" content="' + (nm ? 1080 : 630) + '"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' + esc(t) + '"><meta name="twitter:image" content="' + esc(nm ? card : SITE + '/og-driprunner.jpg') + '"></head><body><a href="/play">Play Drip Runner</a></body></html>');
}
}
{ 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=<click id>): 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=<username> on the landing, the game or sign-in (2026-10-05, the IAP viral-link pattern): the same sponsor cookie as /r/<name>,
// last touch wins. ?r= too on the landing only (the framed /r/<name> lands on /?r=<name>); 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', 'freeSharePct']) if (body[k] != null && body[k] !== '' && Number.isFinite(Number(body[k])) && Number(body[k]) >= 0) patch[k] = Number(body[k]);
if (patch.freeSharePct != null) patch.freeSharePct = Math.min(100, patch.freeSharePct); // the free tier's share of the table (2026-11-02)
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') {
// me.hasWallet: the player's own wallet is on file (it can arrive by the IAP push after this session began, 2026-10-27)
const pl = ledger.pool();
if (!me.guest && ledger.gp.on()) ledger.gp.fetchPass(ledger.iapId(me), me.email).catch(() => {}); // keep the Game Pass flag fresh (display + the shield perk; grant answers carry the truth)
const refs = me.guest ? [] : game.referralsOf(me);
// tier (2026-11-02): guest = earns nothing, free = freeSharePct of the table (yourDrip), full = the table (Game Pass, or GAMEPASS off)
return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet, guest: !!me.guest, hasWallet: !me.guest && !!(me.wallet || ledger.account(me.memberId).wallet || (game.player(me.memberId) || {}).wallet) }, player: game.view(me), balance: ledger.balance(me.memberId), pool: { available: pl.available, capLeft: pl.capLeft, dripPol: Number(ledger.settings().dripPol), tier: ledger.tierOf(me), freeSharePct: ledger.freeShare(), yourDrip: me.guest ? 0 : ledger.dripFor(me) }, 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)
gamepass: me.guest ? null : ledger.gp.view(ledger.iapId(me), me.email) }); // Game Pass: active until <date>, or the link to get it
}
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 = await 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); }
// Game Pass: refs that could not reach InstantAdPay retry every 5 minutes (polgrant.js); carry-forward IAP still owes is collected once a day
ledger.gp.startRetry(ledger.payQueued); setInterval(() => ledger.carrySweep().catch(e => console.error('carry', e.message)), 120000).unref();
+82
View File
@@ -0,0 +1,82 @@
// Game Pass bridge checks (docs/GAME-PASS.md 3a), all local: a stub InstantAdPay on 127.0.0.1 answers /api/partner/polgrant
// with scripted allowed/deferred, a 500, or nothing. The grant client (allowed / deferred / retry, fail closed, the retry
// queue, the 48 h alert), the game's gated chapter drip (every chapter's first clear = 'progress', ref chapter:<n>), the
// wallet-less member (negative local id -> memberId 0 + email on the wire), deferral + carry-forward, and the shield perk flag.
// Production is never contacted. Run: node test/gamepass.js
'use strict';
const http = require('http'), crypto = require('crypto'), fs = require('fs'), os = require('os'), path = require('path');
process.env.GAMEPASS = 'on'; process.env.DR_SSO_SECRET = 'y'.repeat(48);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dr-gp-'));
const store = require('../lib/store'); store.init(dir);
const ledger = require('../lib/ledger'); const gp = ledger.gp; const game = require('../lib/game'); const sso = require('../lib/sso');
const SECRET = 'test-secret-'.padEnd(40, 'x'), GAME = 'driprunner';
let pass = 0, fail = 0;
const ok = (name, cond, info) => { if (cond) { pass++; console.log(' ok ', name); } else { fail++; console.log(' FAIL', name, info === undefined ? '' : JSON.stringify(info)); } };
(async () => {
const seen = []; let mode = 'ok'; const script = {};
const stub = http.createServer((req, res) => { let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
const sig = crypto.createHmac('sha256', SECRET).update(req.headers['x-game-ts'] + '\n' + raw).digest('hex');
if (sig !== req.headers['x-game-sig']) { res.writeHead(401, { 'Content-Type': 'application/json' }); return res.end('{"error":"bad signature"}'); }
if (mode === '500') { res.writeHead(500); return res.end('boom'); }
const b = JSON.parse(raw); if (b.game !== GAME) { res.writeHead(400); return res.end('{"error":"wrong game"}'); } seen.push(Object.assign({ url: req.url }, b));
const s = script[b.ref] || { allowed: b.pol, deferred: 0 };
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ allowed: s.allowed, deferred: s.deferred || 0, carried: s.carried || 0, pass: !!s.pass, day: '2026-10-16' }));
}); });
await new Promise(r => stub.listen(0, '127.0.0.1', r)); const port = stub.address().port;
const alerts = []; gp.use({ game: GAME, secret: SECRET, iap: 'http://127.0.0.1:' + port, store, notify: async (k, p) => alerts.push([k, p]) });
// ---- the client
let r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:1' }); ok('daily inside the cap: allowed = pol', r.allowed === 0.3 && r.retry === false);
script['d:2'] = { allowed: 0.1 }; r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:2' }); ok('daily over the cap: dropped, the nudge names the Pass', r.allowed === 0.1 && /Get the Pass/.test(gp.note(r, 'daily', 0.3)));
script['p:1'] = { allowed: 1, deferred: 1 }; r = await gp.grant({ memberId: 7, kind: 'progress', pol: 2, ref: 'p:1' }); ok('progress over the cap: deferred', r.allowed === 1 && r.deferred === 1 && /pays out over the next days/.test(gp.note(r, 'progress', 2)));
mode = '500'; r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:5' }); ok('a 5xx fails closed', r.allowed === 0 && r.retry === true); mode = 'ok';
gp.use({ iap: 'http://127.0.0.1:9' }); r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:8' }); ok('an unreachable IAP fails closed', r.allowed === 0 && r.retry === true); gp.use({ iap: 'http://127.0.0.1:' + port });
gp.use({ secret: 'wrong-secret-'.padEnd(40, 'y') }); r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:7' }); ok('a rejected signature fails closed', r.allowed === 0 && r.retry === true); gp.use({ secret: SECRET });
const paidQ = []; const payQ = async (item, resp) => paidQ.push([item.ref, resp.allowed]);
mode = '500'; gp.enqueue({ memberId: 7, ref: 'q:1', kind: 'progress', pol: 0.5 }); let rr = await gp.retry(payQ, Date.now() + gp.RETRY_MS + 1); ok('IAP down: tried and kept', rr.tried === 1 && rr.paid === 0 && gp.queued(7, '', 'q:1'));
mode = 'ok'; rr = await gp.retry(payQ, Date.now() + 2 * gp.RETRY_MS + 2); ok('IAP back: paid and dequeued', rr.paid === 1 && paidQ[0][1] === 0.5 && !gp.queued(7, '', 'q:1'));
mode = '500'; gp.enqueue({ memberId: 7, ref: 'q:old', kind: 'daily', pol: 0.2, at: Date.now() - gp.GIVE_UP_MS - 1000 }); rr = await gp.retry(payQ, Date.now() + gp.RETRY_MS + 1);
ok('48 h without an answer: stuck, the admin chat told once', rr.stuck === 1 && alerts.length === 1 && alerts[0][0] === 'gpstuck'); gp.dequeue(7, '', 'q:old'); mode = 'ok';
// ---- the game: a chapter's first clear pays once -> 'progress'; the only POL Drip Runner pays
// the tiers (Marty 2026-11-02): guests earn nothing, a free account earns freeSharePct (25) of the drip, Game Pass holders the drip
ledger.setSettings({ seedPol: 100, dailyCapPol: 5, dripPol: 0.01 });
const me = { memberId: 7, email: 'hugh@example.com', username: 'hugh', wallet: '0x' + 'a'.repeat(40) }, today = ledger.ctDay();
ok('classification: every chapter is progress', ledger.kindOf('chapter:1') === 'progress' && ledger.kindOf('chapter:9') === 'progress');
ok('settings: freeSharePct defaults to 25 and is admin-editable', ledger.settings().freeSharePct === 25 && ledger.freeShare() === 25 && ledger.setSettings({ freeSharePct: 50 }).freeSharePct === 50 && ledger.dripFor(me) === 0.005 && ledger.setSettings({ freeSharePct: 25 }).freeSharePct === 25);
ok('tiers: no pass = free tier at 25% of the drip (4 decimals)', ledger.tierOf(me) === 'free' && !ledger.fullTier(me) && ledger.dripFor(me) === 0.0025);
seen.length = 0; let g = await ledger.chapterDripGated(me, 1, true);
ok('free tier: chapter 1 asks IAP for the scaled 0.0025 as progress (ref chapter:1), pays it, the note names the Pass', g.reason === 'paid' && g.pol === 0.0025 && seen[0].pol === 0.0025 && seen[0].ref === 'chapter:1' && seen[0].kind === 'progress' && seen[0].memberId === 7 && seen[0].email === 'hugh@example.com' && g.note === 'Game Pass holders earn the full amount.', g);
g = await ledger.chapterDripGated(me, 1, false); ok('a replay is not a reward (no IAP call)', g.reason === 'replay' && seen.length === 1);
// the pass: remembered from the hand-off, and re-recorded by every grant answer (so the stub says pass: true for a holder)
gp.rememberPass(7, me.email, { active: true, until: Date.now() + 86400000 }); ok('tiers: pass active = full tier, the whole drip', ledger.tierOf(me) === 'full' && ledger.fullTier(me) && ledger.dripFor(me) === 0.01);
for (const ref of ['chapter:2', 'chapter:4', 'carry:' + today]) script[ref] = { allowed: 0.01, pass: true };
g = await ledger.chapterDripGated(me, 2, true); ok('pass holder: chapter 2 pays the full 0.01, no free note', g.reason === 'paid' && g.pol === 0.01 && seen.at(-1).pol === 0.01 && !g.note, g);
script['chapter:3'] = { allowed: 0, deferred: 0.01, pass: true }; g = await ledger.chapterDripGated(me, 3, true);
ok('chapter 3 deferred: handled, owed, the player told', g.reason === 'deferred' && g.pol === 0 && ledger.account(7).gpOwed === 0.01 && /pays out over the next days/.test(g.note) && store.read('drips', []).some(d => d.chapter === 3 && d.pol === 0));
script['carry:' + today] = { allowed: 0.01, carried: 0.01, pass: true }; ok('carry sweep collects it once a day', (await ledger.carrySweep()) === 0.01 && ledger.account(7).gpOwed === 0 && (await ledger.carrySweep()) === 0);
mode = '500'; g = await ledger.chapterDripGated(me, 4, true); ok('IAP down: queued, nothing paid, the player told', g.reason === 'iap' && gp.queued(7, me.email, 'chapter:4') && /recorded/.test(g.note));
const n = seen.length; g = await ledger.chapterDripGated(me, 4, true); ok('a queued chapter is not asked again', g.reason === 'iap' && seen.length === n);
mode = 'ok'; await gp.retry(ledger.payQueued, Date.now() + gp.RETRY_MS + 1); ok('the queued chapter pays on retry', !gp.queued(7, me.email, 'chapter:4') && store.read('drips', []).some(d => d.chapter === 4 && d.pol === 0.01) && ledger.account(7).unpaid === 0.0325);
ok('the pool only counts what was paid', ledger.pool().out === 0.0325);
// a member with no wallet: negative local id (sso.emailId) -> memberId 0 + email on the wire; the pass flag keyed by email
const nw = { memberId: sso.emailId('nowallet@example.com'), email: 'nowallet@example.com', username: 'nw', wallet: null };
ok('the negative local id is never sent', nw.memberId < 0 && ledger.iapId(nw) === 0);
g = await ledger.chapterDripGated(nw, 1, true); ok('a wallet-less member is gated by email, on the free tier', g.reason === 'paid' && g.pol === 0.0025 && seen.at(-1).memberId === 0 && seen.at(-1).email === 'nowallet@example.com');
const guest = { memberId: -999999999999, guest: true, email: null }; seen.length = 0; const drips0 = store.read('drips', []).length; g = await ledger.chapterDripGated(guest, 1, true);
ok('a guest earns nothing: no IAP call, no drip row, reason guest (2026-11-02)', seen.length === 0 && g.reason === 'guest' && g.pol === 0 && store.read('drips', []).length === drips0 && ledger.tierOf(guest) === 'guest');
ok('...on the plain path too', ledger.chapterDrip(guest, 1, true).reason === 'guest' && store.read('drips', []).length === drips0);
ledger.setSettings({ dailyCapPol: 0.001 }); g = await ledger.chapterDripGated(me, 5, true); ok('the local daily cap still stands in front of IAP', g.reason === 'cap'); ledger.setSettings({ dailyCapPol: 5 });
gp.rememberPass(7, me.email, false);
process.env.GAMEPASS = 'off'; seen.length = 0; ok('GAMEPASS=off: everyone is on the full tier', ledger.fullTier(me) && ledger.tierOf(me) === 'full' && ledger.dripFor(me) === 0.01 && ledger.tierOf(guest) === 'guest');
g = await ledger.chapterDripGated(me, 5, true); ok('GAMEPASS=off: the plain chapterDrip pays the full drip, no IAP call, no free note', g.reason === 'paid' && g.pol === 0.01 && seen.length === 0 && !g.note); process.env.GAMEPASS = 'on';
ok('history explains deferral and carry', ledger.balance(7).history.some(h => /paying out over the next days/.test(h.label)) && ledger.balance(7).history.some(h => /Carried-over/.test(h.label)));
// the perk: a shield at the start of every run while the pass is active
gp.rememberPass(7, me.email, false); let run = game.start(me, 390, 760); ok('no pass: no free shield', run.armed.shield === false && !run.armed.passShield);
gp.rememberPass(7, me.email, { active: true, until: Date.now() + 86400000 }); run = game.start(me, 390, 760); ok('pass active: a shield at run start', run.armed.shield === true && run.armed.passShield === true && ledger.passActive(me));
game.updPlayer(7, x => { x.items.shield = true; }); run = game.start(me, 390, 760); ok('a bought Shield Core is kept for a later run while the pass covers this one', run.armed.shield === true && game.player(7).items.shield === true);
process.env.GAMEPASS = 'off'; run = game.start(me, 390, 760); ok('GAMEPASS=off: no perk (the bought shield is used as before)', run.armed.shield === true && !run.armed.passShield && !game.player(7).items.shield); process.env.GAMEPASS = 'on';
stub.close(); console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });
+43 -6
View File
@@ -31,7 +31,7 @@ const sleep = ms => new Promise(r => setTimeout(r, ms));
const spawnLib = require('../lib/spawn');
(async () => {
await sleep(1200);
for (let i = 0; i < 60; i++) { try { await fetch(B + '/health'); break; } catch (e) { await sleep(250); } }
process.env.DR_SSO_SECRET = SECRET; const sso = require('../lib/sso');
const h = await call('/health'); eq([h.body.sso, h.body.faucet, h.body.signups], [true, false, 'testers'], 'posture: sso on, faucet off, testers mode');
@@ -39,6 +39,8 @@ const spawnLib = require('../lib/spawn');
const tok0 = sso.mint({ memberId: 42, email: 'runner@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'runner42' });
const denied = await call('/auth?t=' + tok0); eq(denied.status, 403, 'a member not on the tester list is refused');
const st = await admin('/api/admin/settings', { testers: ['runner@example.com'], thresholdPol: 0.02, dripPol: 0.01 }); eq(st.body.settings.testers, ['runner@example.com'], 'admin adds a tester');
eq((await admin('/api/admin/state')).body.settings.freeSharePct, 25, 'freeSharePct defaults to 25');
eq((await admin('/api/admin/settings', { freeSharePct: 40 })).body.settings.freeSharePct, 40, 'admin saves freeSharePct'); await admin('/api/admin/settings', { freeSharePct: 25 });
const tok = sso.mint({ memberId: 42, email: 'runner@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'runner42' });
const a = await call('/auth?t=' + tok); eq([a.status, a.headers.get('location')], [302, '/play'], 'a listed member signs in and lands on the game');
eq((await call('/auth?t=' + tok)).status, 400, 'the hand-off token cannot be replayed');
@@ -81,6 +83,7 @@ const spawnLib = require('../lib/spawn');
// a replay of chapter 1 pays nothing; the hangar sink works; the sweep makes a payout row
const r2 = (await post('/api/run/start', { W, H })).body; eq(r2.chapter, 3, 'a new run starts on chapter 3 (progress kept)');
await post('/api/run/end', { runId: r2.runId });
const perkBuy = await post('/api/hangar/buy', { item: 'ship' }); eq([perkBuy.status, perkBuy.body.free], [200, true], 'the member perk (one free upgrade, 2026-10-05) pays for the first purchase'); // test/starter.js covers it in full
const buyNo = await post('/api/hangar/buy', { item: 'shield' }); eq(buyNo.status, 400, 'shield (0.05 POL) refused on a 0.01 balance');
await admin('/api/admin/settings', { itemPol: { slow: 0.005 } });
const buy = await post('/api/hangar/buy', { item: 'slow' }); eq([buy.status, buy.body.paid, buy.body.balance.unpaid], [200, '0.005 POL', 0.005], 'slow field bought from the POL balance');
@@ -98,7 +101,14 @@ const spawnLib = require('../lib/spawn');
const hit = async (p, opt = {}, ck = '') => { const r = await fetch(B + p, Object.assign({ redirect: 'manual' }, opt, { headers: Object.assign({ Cookie: ck, 'Content-Type': 'application/json' }, opt.headers || {}) })); const set = r.headers.getSetCookie ? r.headers.getSetCookie() : []; let body = null; try { body = await r.json(); } catch (e) {} return { status: r.status, body, set, loc: r.headers.get('location') }; };
const jarAdd = (ck, set) => { const parts = ck ? ck.split('; ') : []; for (const c of set) { const m = /^([^=]+)=([^;]*)/.exec(c); if (!m) continue; const i = parts.findIndex(x => x.startsWith(m[1] + '=')); if (i >= 0) parts.splice(i, 1); if (m[2]) parts.push(m[1] + '=' + m[2]); } return parts.join('; '); };
await admin('/api/admin/settings', { signups: 'open', thresholdPol: 5, refSharePct: 10 });
eq((await hit('/r/nobody')).loc, '/', 'a share link for an unknown player goes to the landing page');
eq((await hit('/r/nobody')).loc, '/?ref=nobody', 'a share link for a name the game does not know goes to the landing page with the name kept as ?ref');
// ?ref=<name> (2026-10-05): the landing, the game and sign-in all set the same sponsor cookie; ?r= only on the landing (on /play it is the refuel receipt)
for (const [path, want] of [['/?ref=Alice', 'alice'], ['/?r=alice', 'alice'], ['/play?ref=alice', 'alice'], ['/signin?ref=@alice', 'alice'], ['/play?r=receipt', null], ['/?ref=bad%20name', null]]) {
const x = await hit(path); const c = x.set.find(s => /^dr\.ref=/.test(s)) || null;
eq([x.status, c ? /^dr\.ref=([^;]*)/.exec(c)[1] : null], [200, want], path + (want ? ' sets dr.ref=' + want : ' sets no sponsor cookie'));
}
{ const x = await hit('/?ref=alice&src=adsterra&cid=c1'); eq([x.set.some(s => /^dr\.ref=alice/.test(s)), x.set.some(s => /^dr\.src=/.test(s))], [true, true], 'a paid-traffic landing with ?ref keeps both cookies'); }
{ const x = await hit('/r/runner42', { headers: { 'Sec-Fetch-Dest': 'iframe' } }); eq(x.loc, '/?r=runner42', 'a framed share link lands on the landing with ?r'); }
const sh = await hit('/r/runner42'); eq([sh.status, sh.loc, sh.set.some(c => /^dr\.ref=runner42/.test(c))], [302, '/play', true], 'a player share link sets the referrer and opens the game');
let g = jarAdd('', sh.set);
const me401 = await hit('/api/me', {}, g); eq([me401.status, me401.body.guestOk, me401.body.signin === '/signin'], [401, true, true], 'a newcomer is offered guest play, sign-in stays in the game (/signin; the kit carries the dr.ref sponsor)');
@@ -108,13 +118,14 @@ const spawnLib = require('../lib/spawn');
const ggen = spawnLib.drips(gr.seed, W, H); const gcl = []; let gT = 0; while (gcl.length < 20) { const gg = ggen(); for (const d of gg.drips) if (gcl.length < 20) { gT = spawnLib.arrival(gg.t, d.x0, W, gr.speed) + 0.1; gcl.push({ k: 'd', i: d.i, t: Math.round(gT * 1000) / 1000 }); } }
backdate(gr.runId, gT + 5);
const gev = (await hit('/api/run/events', { method: 'POST', body: JSON.stringify({ runId: gr.runId, t: gT + 0.2, events: gcl, goal: true }) }, g)).body;
eq([gev.cleared.chapter, gev.cleared.pol, gev.cleared.reason], [1, 0, 'guest'], 'a guest clear pays nothing yet (reason guest)');
eq([gev.cleared.chapter, gev.cleared.pol, gev.cleared.reason], [1, 0, 'guest'], 'a guest clear pays nothing (reason guest)');
eq((await hit('/api/me', {}, g)).body.pool.tier, 'guest', '/api/me says tier guest');
eq((await hit('/api/refuel/start', { method: 'POST', body: JSON.stringify({ runId: gr.runId }) }, g)).status, 403, 'a guest cannot refuel before signing in');
// the newcomer joins IAP under runner42 and signs in: the guest run is adopted and the clear pays
// the newcomer joins IAP under runner42 and signs in: the guest run is adopted; the progress follows, the POL does not (2026-11-02)
const tokN = sso.mint({ memberId: 77, email: 'newbie@example.com', wallet: '0x' + 'cd'.repeat(20), username: 'newbie', sponsorRef: 'runner42' });
const au = await hit('/auth?t=' + tokN, {}, g); g = jarAdd(g, au.set);
eq([au.status, au.loc], [302, '/play?collected=1'], 'sign-in adopts the guest and pays the pending clear');
const nme = (await hit('/api/me', {}, g)).body; eq([nme.me.guest, nme.player.chapter, nme.player.bank, nme.balance.unpaid], [false, 2, 20, 0.01], 'progress and the drip followed the newcomer');
eq([au.status, au.loc], [302, '/play?carried=1'], 'sign-in adopts the guest progress and pays nothing for guest clears');
const nme = (await hit('/api/me', {}, g)).body; eq([nme.me.guest, nme.player.chapter, nme.player.bank, nme.balance.unpaid, nme.balance.earnedTotal, nme.pool.tier], [false, 2, 20, 0, 0, 'full'], 'progress followed the newcomer, no POL for the guest clear; GAMEPASS off = full tier');
// the newcomer refuels: runner42 (their IAP sponsor) gets the slice
const nr = (await hit('/api/run/start', { method: 'POST', body: JSON.stringify({ W, H }) }, g)).body;
const nrf = (await hit('/api/refuel/start', { method: 'POST', body: JSON.stringify({ runId: nr.runId }) }, g)).body;
@@ -130,6 +141,32 @@ const spawnLib = require('../lib/spawn');
const tokW2 = sso.mint({ memberId: 91, email: 'free@example.com', wallet: '0x' + 'ef'.repeat(20), username: 'freebie' });
await hit('/auth?t=' + tokW2); const moved = gameLib.player(91); eq([moved && moved.chapter, moved && moved.bank, !!gameLib.player(wme.me.memberId)], [4, 33, false], 'after the wallet is linked, progress moves to the on-chain id');
// ---- 2026-10-27: IAP pushes the signature-linked wallet whether or not it is on chain (memberId 0) ----
const pushW = b => { const raw = JSON.stringify(b), ts = String(Date.now()); const sig = crypto.createHmac('sha256', SECRET).update('wallet\n' + ts + '\n' + crypto.createHash('sha256').update(raw).digest('hex')).digest('hex'); return hit('/api/iap/wallet', { method: 'POST', body: raw, headers: { 'X-IAP-Ts': ts, 'X-IAP-Sig': sig } }); };
const zw = '0x' + '12'.repeat(20); let z = '';
const az = await hit('/auth?t=' + sso.mint({ memberId: 0, email: 'tank@example.com', wallet: null, username: 'tanker' })); z = jarAdd(z, az.set);
const zme = (await hit('/api/me', {}, z)).body; const zid = zme.me.memberId;
eq([zid < 0, zme.me.hasWallet], [true, false], 'a holding-tank member plays on the email id with hasWallet false');
store.update('accounts', {}, all => { all[String(zid)] = { memberId: zid, unpaid: 0.02, paidTotal: 0, spentTotal: 0, earnedTotal: 0.02 }; return all; }); // POL earned before the wallet
const z1 = await pushW({ email: 'tank@example.com', wallet: zw, username: 'tanker', memberId: 0 });
eq([z1.status, z1.body.changed, z1.body.wallet, z1.body.unpaid], [200, true, zw, 0.02], 'push with memberId 0 fills the email-keyed wallet (200 changed:true)');
eq([(await pushW({ email: 'tank@example.com', wallet: zw })).body.changed, (await pushW({ email: 'tank@example.com', wallet: '0x' + '34'.repeat(20), memberId: 0 })).status], [false, 409], 'same wallet again (memberId missing) is a no-op; a different wallet is refused 409');
eq((await pushW({ email: 'nobody@example.com', wallet: zw, memberId: 0 })).status, 404, 'an unknown email is still 404');
eq((await hit('/api/me', {}, z)).body.me.hasWallet, true, 'the session that never saw the wallet now reports hasWallet');
await admin('/api/admin/settings', { thresholdPol: 0.005 });
const dz = ledger.payable().filter(x => x.memberId === zid); eq([dz.length, dz[0] && dz[0].wallet, dz[0] && dz[0].pol], [1, zw, 0.02], 'the payout sweep pays the linked wallet with memberId 0');
// a hand-off with memberId 0 and a wallet fills an empty account wallet too (POL earned so far pays on the next sweep)
const yw = '0x' + '56'.repeat(20);
await hit('/auth?t=' + sso.mint({ memberId: 0, email: 'tank2@example.com', wallet: null, username: 'tanker2' })); const yid = sso.emailId('tank2@example.com');
store.update('accounts', {}, all => { all[String(yid)] = { memberId: yid, unpaid: 0.01, paidTotal: 0, spentTotal: 0, earnedTotal: 0.01 }; return all; });
await hit('/auth?t=' + sso.mint({ memberId: 0, email: 'tank2@example.com', wallet: yw, username: 'tanker2' }));
const dy = ledger.payable().filter(x => x.memberId === yid); eq([ledger.account(yid).wallet, dy.length, dy[0] && dy[0].wallet], [yw, 1, yw], '/auth with memberId 0 stores the wallet and the sweep pays it');
await hit('/auth?t=' + sso.mint({ memberId: 0, email: 'tank2@example.com', wallet: '0x' + '78'.repeat(20), username: 'tanker2' }));
eq(ledger.account(yid).wallet, yw, 'a later hand-off never replaces the account wallet that pays');
// the member activates later: the push with the real id moves everything (wallet included) onto it
const z9 = await pushW({ email: 'tank@example.com', wallet: zw, username: 'tanker', memberId: 300 });
eq([z9.status, ledger.account(300).wallet, !!gameLib.player(zid)], [200, zw, false], 'activation later: the email-keyed history and wallet move to the on-chain id');
console.log(fails ? '\n' + fails + ' FAILED' : '\nall good');
child.kill(); fs.rmSync(DIR, { recursive: true, force: true }); process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); child.kill(); process.exit(1); });
+107
View File
@@ -0,0 +1,107 @@
// Member welcome offer + member perk (2026-10-05), on a local boot against a stub of InstantAdPay's public offer endpoint.
// Temp DATA_DIR, no faucet, no outbound. Checks: a signed-in non-member's clear carries the offer once a Central day; a
// guest and a member never see it; a member's hand-off grants one free hangar upgrade once per account; the free upgrade
// pays for exactly one purchase; the offer is skipped while InstantAdPay says off; bonus is null when the endpoint fails.
'use strict';
const { spawn } = require('child_process');
const http = require('http');
const path = require('path');
const fs = require('fs');
const PORT = 8899, STUB = 8897, DIR = path.join(__dirname, '..', 'data-test-starter');
fs.rmSync(DIR, { recursive: true, force: true });
const SECRET = 'z'.repeat(48);
let stubHits = 0, stubOn = true;
const stub = http.createServer((req, res) => {
if (req.url === '/api/starter/public') { stubHits++; res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ on: stubOn, bonus: 100, games: { driprunner: { name: 'Drip Runner', perk: 'a free hangar upgrade' } } })); }
res.writeHead(404); res.end('{}');
}).listen(STUB);
const IAPS = 'http://127.0.0.1:' + STUB;
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DIR, DR_SSO_SECRET: SECRET, ADMIN_KEY: 'adminkey123', SITE_URL: 'http://127.0.0.1:' + PORT, IAP_URL: IAPS });
delete env.CURTAIN; delete env.OUTBOUND; delete env.DR_WALLET_KEY; delete env.DR_RPC; delete env.DR_SIGNUPS; delete env.NODE_ENV;
const child = spawn(process.execPath, [path.join(__dirname, '..', 'server.js')], { env, stdio: ['ignore', 'pipe', 'pipe'] });
let serverErr = ''; child.stderr.on('data', d => { serverErr += d; process.stderr.write(d); });
let fails = 0;
const eq = (a, b, m) => { const ok = JSON.stringify(a) === JSON.stringify(b); console.log((ok ? ' ok ' : ' FAIL ') + m + (ok ? '' : ' -> got ' + JSON.stringify(a) + ' want ' + JSON.stringify(b))); if (!ok) fails++; };
const B = 'http://127.0.0.1:' + PORT;
const sleep = ms => new Promise(r => setTimeout(r, ms));
const spawnLib = require('../lib/spawn');
const hit = async (p, opt = {}, ck = '') => { const r = await fetch(B + p, Object.assign({ redirect: 'manual' }, opt, { headers: Object.assign({ Cookie: ck, 'Content-Type': 'application/json' }, opt.headers || {}) })); const set = r.headers.getSetCookie ? r.headers.getSetCookie() : []; let body = null; try { body = await r.json(); } catch (e) {} return { status: r.status, body, set, loc: r.headers.get('location') }; };
const jarAdd = (ck, set) => { const parts = ck ? ck.split('; ') : []; for (const c of set) { const m = /^([^=]+)=([^;]*)/.exec(c); if (!m) continue; const i = parts.findIndex(x => x.startsWith(m[1] + '=')); if (i >= 0) parts.splice(i, 1); if (m[2]) parts.push(m[1] + '=' + m[2]); } return parts.join('; '); };
const post = (p, b, ck) => hit(p, { method: 'POST', body: JSON.stringify(b || {}) }, ck);
const admin = (p, b) => hit(p, Object.assign({ headers: { 'X-Admin-Key': 'adminkey123' } }, b ? { method: 'POST', body: JSON.stringify(b) } : {}));
const players = () => JSON.parse(fs.readFileSync(path.join(DIR, 'players.json'), 'utf8'));
const W = 390, H = 760;
// play one run to the next chapter clear (claims timed to the schedule, start backdated so the wall check passes)
async function clearOne(ck) {
const r = (await post('/api/run/start', { W, H }, ck)).body; const gen = spawnLib.drips(r.seed, W, H); const cl = []; let T = 0;
while (cl.length < r.goal) { const g = gen(); for (const d of g.drips) if (cl.length < r.goal) { T = spawnLib.arrival(g.t, d.x0, W, r.speed) + 0.1; cl.push({ k: 'd', i: d.i, t: Math.round(T * 1000) / 1000 }); } }
const runs = JSON.parse(fs.readFileSync(path.join(DIR, 'runs.json'), 'utf8')); runs[r.runId].startedAt = Date.now() - (T + 5) * 1000; fs.writeFileSync(path.join(DIR, 'runs.json'), JSON.stringify(runs));
const ev = (await post('/api/run/events', { runId: r.runId, t: T + 0.2, events: cl, goal: true }, ck)).body;
await post('/api/run/end', { runId: r.runId }, ck);
return ev;
}
async function signIn(claims, ck) { const a = await hit('/auth?t=' + sso.mint(claims), {}, ck || ''); return { ck: jarAdd(ck || '', a.set), a }; }
let sso;
(async () => {
for (let i = 0; i < 60; i++) { try { await fetch(B + '/health'); break; } catch (e) { await sleep(250); } }
process.env.DR_SSO_SECRET = SECRET; sso = require('../lib/sso');
await admin('/api/admin/settings', { signups: 'open' });
// ---- non-member (InstantAdPay memberId 0): the offer after a win, once a Central day ----
let { ck: nm, a } = await signIn({ memberId: 0, email: 'nonmember@example.com', wallet: null, username: 'nonmem' });
eq(a.loc, '/play', 'a non-member signs in');
const nmMe = (await hit('/api/me', {}, nm)).body; eq([nmMe.me.memberId < 0, nmMe.perk, nmMe.player.freeUpgrades], [true, null, 0], 'non-member: temporary id, no perk, no free upgrade');
const c1 = await clearOne(nm);
eq([c1.cleared && c1.cleared.chapter, c1.starterOffer], [1, { bonus: 100, perk: 'a free hangar upgrade', url: IAPS + '/my?from=driprunner#buy' }], 'first clear of the day carries starterOffer {bonus 100, perk, url}');
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
eq(players()[String(nmMe.me.memberId)].starterShown, today, 'shown today is recorded on the player (Central day key ' + today + ')');
const c2 = await clearOne(nm); eq([c2.cleared && c2.cleared.chapter, c2.starterOffer === undefined], [2, true], 'second clear the same day: no offer');
const runEnd = await post('/api/run/start', { W, H }, nm); const crash = (await post('/api/run/events', { runId: runEnd.body.runId, t: 1, events: [] }, nm)).body; eq(crash.starterOffer === undefined, true, 'a sync without a clear never carries the offer');
await post('/api/run/end', { runId: runEnd.body.runId }, nm);
// tomorrow (Central): move the recorded day back
const ps = players(); ps[String(nmMe.me.memberId)].starterShown = '2000-01-01'; fs.writeFileSync(path.join(DIR, 'players.json'), JSON.stringify(ps));
const c3 = await clearOne(nm); eq([c3.cleared && c3.cleared.chapter, !!c3.starterOffer], [3, true], 'next Central day: the offer shows again, once');
eq(stubHits, 1, 'the public endpoint was fetched once (10-minute cache)');
// ---- a guest never sees it ----
await admin('/api/admin/settings', {}); let g = '';
const gs = await post('/api/guest', {}, g); g = jarAdd(g, gs.set); const gc = await clearOne(g);
eq([gc.cleared && gc.cleared.reason, gc.starterOffer === undefined], ['guest', true], 'a guest clear: no offer');
// ---- member: the perk, once per account ----
let { ck: mb } = await signIn({ memberId: 55, email: 'member@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'member55' });
const p55 = players()['55']; eq([p55.freeUpgrades, typeof p55.perkAt, p55.perkNotice], [1, 'number', true], 'member hand-off grants one free upgrade, perkAt timestamp set');
const m1 = (await hit('/api/me', {}, mb)).body; eq([m1.perk, m1.player.freeUpgrades], ['Member perk: a free hangar upgrade. Thanks for joining InstantAdPay!', 1], '/api/me carries the one-time perk message');
const m2 = (await hit('/api/me', {}, mb)).body; eq(m2.perk, null, 'the message shows once (next load has none)');
const perkAt1 = players()['55'].perkAt;
({ ck: mb } = await signIn({ memberId: 55, email: 'member@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'member55' }, mb));
eq([players()['55'].freeUpgrades, players()['55'].perkAt, (await hit('/api/me', {}, mb)).body.perk], [1, perkAt1, null], 'signing in again grants nothing more');
const mc = await clearOne(mb); eq([mc.cleared && mc.cleared.chapter, mc.starterOffer === undefined], [1, true], 'a member clear: no offer');
const bank0 = players()['55'].bank;
const buy1 = await post('/api/hangar/buy', { item: 'ship' }, mb); // 600 drips, they have ~20
eq([buy1.status, buy1.body.free, buy1.body.player.items.ship, buy1.body.player.freeUpgrades, buy1.body.player.bank], [200, true, true, 0, bank0], 'the free upgrade buys the Courier Mk II (600 drips) for nothing, token used');
const buy2 = await post('/api/hangar/buy', { item: 'magnet' }, mb); eq(buy2.status, 400, 'the next purchase costs again (magnet refused on ~20 drips)');
const st = (await admin('/api/admin/state')).body; eq([st.pool.spends, st.spends.length], [0, 0], 'the free upgrade moved no POL (pool spends 0, no spend rows)');
// ---- a free POL item ----
({ ck: nm } = await signIn({ memberId: 91, email: 'nonmember@example.com', wallet: '0x' + 'cd'.repeat(20), username: 'nonmem' }, nm)); // the non-member buys and comes back as #91
const p91 = players()['91']; eq([p91 && p91.chapter, p91 && p91.freeUpgrades, !!(p91 && p91.perkAt)], [4, 1, true], 'non-member turned member: progress moved to #91 and the perk is granted');
const sh = await post('/api/hangar/buy', { item: 'shield' }, nm); eq([sh.status, sh.body.free, sh.body.balance.unpaid, sh.body.player.items.shield], [200, true, 0, true], 'free upgrade on a POL item (shield) with a 0 balance: armed, no POL taken');
const nc = await clearOne(nm); eq(nc.starterOffer === undefined, true, 'once a member, no more offers');
// ---- in process: InstantAdPay says off; the endpoint is down ----
process.env.DATA_DIR = DIR; const store = require('../lib/store'); store.init(DIR);
const game = require('../lib/game');
game.updPlayer(-123, x => { x.email = 'x@example.com'; });
stubOn = false; process.env.IAP_URL = IAPS; delete require.cache[require.resolve('../lib/starter')]; let starter = require('../lib/starter');
eq(await starter.offerFor({ memberId: -123 }), null, 'offer skipped while InstantAdPay reports on:false');
eq(game.player(-123).starterShown, undefined, '...and not recorded as shown');
process.env.IAP_URL = 'http://127.0.0.1:1'; delete require.cache[require.resolve('../lib/starter')]; starter = require('../lib/starter');
const down = await starter.offerFor({ memberId: -123 }); eq([down && down.bonus, down && down.perk], [null, 'a free hangar upgrade'], 'endpoint down: offer still shows, bonus null');
eq(/Error|TypeError/.test(serverErr), false, 'no server errors logged');
console.log(fails ? '\n' + fails + ' FAILED' : '\nall good');
child.kill(); stub.close(); fs.rmSync(DIR, { recursive: true, force: true }); process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); child.kill(); stub.close(); process.exit(1); });
+25
View File
@@ -0,0 +1,25 @@
# Cross-promo strip (Marty, 2026-10-03): "More games" in the lobby, from InstantAdPay's shared list.
ROOT = 'D:/Projects/HighRisk/drip-runner/'
def edit(path, pairs):
b = open(ROOT + path, 'rb').read(); crlf = b.count(b'\r\n') > b.count(b'\n') // 2
s = b.decode('utf-8').replace('\r\n', '\n')
for a, r in pairs:
if s.count(a) != 1: raise SystemExit('%s anchor %d: %s' % (path, s.count(a), a[:70]))
s = s.replace(a, r)
if crlf: s = s.replace('\n', '\r\n')
open(ROOT + path, 'wb').write(s.encode('utf-8')); print('patched', path)
edit('server.js', [("img-src 'self' data:; connect-src", "img-src 'self' data: https:; connect-src")]) # other games' share art in the strip
edit('public/play.html', [
('<div class="member" style="margin-top:6px"><a id="lIap"',
'<div id="moreGames" class="moreGames" hidden></div>\n <div class="member" style="margin-top:6px"><a id="lIap"'),
('<script src="https://instantadpay.com/assets/game-signin.js?v=20261003a" async></script>',
'<script src="https://instantadpay.com/assets/game-signin.js?v=20261003a" async></script>\n<script src="https://instantadpay.com/assets/game-strip.js?v=20261003a"></script>'),
('[hidden]{display:none!important}', '.moreGames{margin-top:16px;--gs-ink:var(--ink);--gs-muted:var(--ink2);--gs-card:var(--panel2);--gs-line:var(--line);--gs-hot:var(--gold);--gs-font:var(--body)}\n[hidden]{display:none!important}'),
])
edit('public/play.js', [
(" [['lIap', 'overview'], ['bLevel', 'buy']].forEach(",
" if (window.IAPGames && !$('moreGames').dataset.done) { $('moreGames').dataset.done = 1; IAPGames.strip($('moreGames'), { current: 'driprunner', title: 'More games that pay POL' }); } // cross-promo strip (2026-10-03)\n"
" [['lIap', 'overview'], ['bLevel', 'buy']].forEach("),
])
print('ok')
+49
View File
@@ -0,0 +1,49 @@
# Paid-traffic source tracking (Marty, 2026-10-03): ?src=&cid= on the landing pages -> dr.src cookie; counts per source
# (visits, guests, runs, players, sign-ins, new accounts); BeMob postback on a new account; /api/admin/srcstats.
ROOT = 'D:/Projects/HighRisk/drip-runner/'
def edit(path, pairs):
b = open(ROOT + path, 'rb').read(); crlf = b.count(b'\r\n') > b.count(b'\n') // 2
s = b.decode('utf-8').replace('\r\n', '\n')
for a, r in pairs:
if s.count(a) != 1: raise SystemExit('%s anchor %d: %s' % (path, s.count(a), a[:70]))
s = s.replace(a, r)
if crlf: s = s.replace('\n', '\r\n')
open(ROOT + path, 'wb').write(s.encode('utf-8')); print('patched', path)
edit('server.js', [
("const tips = require('./lib/tips');", "const srctrack = require('./lib/srctrack'); // paid-traffic sources (2026-10-03)\nconst tips = require('./lib/tips');"),
# landing pages remember the source and count the visit
(" // ---- static + pages ----\n",
" // ---- static + pages ----\n"
" // a paid-traffic landing (?src=adsterra&cid=<click id>): remember it (dr.src) and count the visit (2026-10-03)\n"
" let srcHdr = null; if (req.method === 'GET' && ['/', '/index.html', '/play', '/signin'].includes(p)) { const t = srctrack.fromQuery(u); if (t) { srcHdr = { 'Set-Cookie': srctrack.cookieHeader(t, IS_PROD) }; srctrack.bump(t.src, 'visits'); } }\n"),
("{ if (curtained(req, res, u)) return; return sendFile(res, path.join(PUBLIC_DIR, 'index.html')); }",
"{ if (curtained(req, res, u)) return; return sendFile(res, path.join(PUBLIC_DIR, 'index.html'), srcHdr); }"),
(" if (p === '/play') return sendFile(res, path.join(PUBLIC_DIR, 'play.html'));\n",
" if (p === '/play') return sendFile(res, path.join(PUBLIC_DIR, 'play.html'), srcHdr);\n"),
(" if (p === '/signin') return sendFile(res, path.join(PUBLIC_DIR, 'signin.html'));",
" if (p === '/signin') return sendFile(res, path.join(PUBLIC_DIR, 'signin.html'), srcHdr);"),
# guest started
(" const g = sso.startGuest(refCookie(req)); return json(res, 200, { ok: true }, { 'Set-Cookie': sso.guestCookie(g.gid) });",
" 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) });"),
# run started
(" if (p === '/api/run/start' && req.method === 'POST') { const { body } = await readBody(req);",
" 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); }"),
# sign-in through the hand-off: count it, a NEW InstantAdPay account fires the tracker postback once
(" if (first) notify('signin', {",
" { const t = srctrack.fromRequest(req); if (t) {\n"
" srctrack.bump(t.src, 'signins', r.claims.memberId); game.updPlayer(r.claims.memberId, x => { if (!x.src) x.src = t.src; });\n"
" 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(() => {}); } } }\n"
" if (first) notify('signin', {"),
# admin report
(" if (p === '/api/admin/faucet/tick' && req.method === 'POST')",
" if (p === '/api/admin/srcstats' && req.method === 'GET') return json(res, 200, srctrack.summary(Number(u.searchParams.get('days')) || 30));\n"
" if (p === '/api/admin/faucet/tick' && req.method === 'POST')"),
])
# the in-game sign-in carries the source to InstantAdPay (account joinedRef = driprunner.app/<src>)
edit('public/signin.js', [
(" IAPSignin.mount(box, { game: 'driprunner', ref: m ? decodeURIComponent(m[1]) : '',",
" var s = /(?:^|;\\s*)dr\\.src=([^;]+)/.exec(document.cookie || ''); // paid-traffic source, if any (2026-10-03)\n"
" IAPSignin.mount(box, { game: 'driprunner', src: s ? decodeURIComponent(s[1]).split('|')[0] : '', ref: m ? decodeURIComponent(m[1]) : '',"),
])
print('ok')