Compare commits
22 Commits
dd00cb1b57
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 63e8012b16 | |||
| f002222b25 | |||
| b69086aaac | |||
| 4d8dde2ad2 | |||
| b70ecf6f75 | |||
| eb2cb822ac | |||
| cc3db3833f | |||
| c9515e16eb | |||
| fe61842525 | |||
| 1bace54bc2 | |||
| 7c2d6b7467 | |||
| 3aa5698c8a | |||
| 11d6f46950 | |||
| 09692de8c6 | |||
| 4fa68b2745 | |||
| 75ba7ba388 | |||
| 08e70d6a16 | |||
| 60f1148efa | |||
| 305bd435fa | |||
| 19b4bf8fbb | |||
| 84b520bcd7 | |||
| 9c693fcf63 |
@@ -1,5 +1,6 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
data/
|
data/
|
||||||
data-test/
|
data-test/
|
||||||
|
data-test-starter/
|
||||||
*.log
|
*.log
|
||||||
.env
|
.env
|
||||||
|
|||||||
@@ -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 = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'", ''': "'", ' ': ' ' };
|
||||||
|
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
@@ -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 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 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); }
|
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)); } }
|
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; }
|
function address() { return wallet ? wallet.address : null; }
|
||||||
async function balance() { if (!provider || !wallet) return null; return Number(ethers.formatEther(await provider.getBalance(wallet.address))); }
|
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', {})); }
|
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;
|
ticking = true; let paid = 0, would = 0;
|
||||||
try {
|
try {
|
||||||
for (const p of store.read('payouts', []).filter(x => x.status === 'sent' && x.tx)) {
|
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();
|
const due = ledger.payable();
|
||||||
let bal = null; try { bal = await balance(); } catch (e) {}
|
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 } }));
|
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 };
|
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) {
|
for (const p of due) {
|
||||||
if (bal != null && bal < p.pol + 0.005) { await lowOnce(notify, bal, p.pol); break; }
|
if (bal != null && bal < p.pol + 0.005) { await lowOnce(notify, bal, p.pol); break; }
|
||||||
try {
|
try {
|
||||||
const tx = await wallet.sendTransaction({ to: p.wallet, value: ethers.parseEther(String(p.pol)) });
|
const tx = await wallet.sendTransaction({ to: p.wallet, value: ethers.parseEther(String(p.pol)), nonce });
|
||||||
ledger.mark(p.id, { status: 'sent', tx: tx.hash });
|
ledger.mark(p.id, { status: 'sent', tx: tx.hash, sentAt: Date.now() }); nonce++; keepNonce(nonce);
|
||||||
let rc = null;
|
let rc = null;
|
||||||
try { rc = await tx.wait(1, 90000); } catch (e) { if (e && e.code === 'TIMEOUT') continue; throw e; }
|
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; }
|
if (await settle(Object.assign({}, p, { tx: tx.hash }), rc, notify)) { paid++; if (bal != null) bal -= p.pol; }
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = String(e.message || e);
|
const msg = String(e.message || e);
|
||||||
if (/insufficient funds/i.test(msg)) { ledger.mark(p.id, { status: 'due', error: null }); break; }
|
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);
|
const cur = store.read('payouts', []).find(x => x.id === p.id);
|
||||||
if (cur && cur.status === 'sent' && cur.tx) continue;
|
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; }
|
if (TRANSIENT.test(msg)) { ledger.mark(p.id, { status: 'due', error: 'node: ' + msg.slice(0, 120) }); rotate(msg); break; }
|
||||||
|
|||||||
+17
-9
@@ -27,7 +27,7 @@ function updPlayer(memberId, fn) {
|
|||||||
function view(me) {
|
function view(me) {
|
||||||
const p = player(me.memberId) || updPlayer(me.memberId, () => {});
|
const p = player(me.memberId) || updPlayer(me.memberId, () => {});
|
||||||
const s = ledger.settings();
|
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) };
|
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++; });
|
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
|
// 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; });
|
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 };
|
// 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
|
||||||
updPlayer(me.memberId, x => { delete x.items.magnet; delete x.items.shield; delete x.items.slow; }); // one-run items are consumed now
|
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,
|
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,
|
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: [] };
|
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
|
// 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);
|
const r = run(runId);
|
||||||
if (!r || r.memberId !== Number(me.memberId)) return { error: 'That run is not yours or no longer exists.' };
|
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 };
|
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; }
|
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 ch = out.chapter; const p = player(me.memberId);
|
||||||
const first = !(p.cleared || {})[ch];
|
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 (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; });
|
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); });
|
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;
|
return res;
|
||||||
}
|
}
|
||||||
@@ -112,18 +114,23 @@ function end(me, runId) {
|
|||||||
function refuelled(me, runId) { return updRun(runId, x => { x.refuels++; }); }
|
function refuelled(me, runId) { return updRun(runId, x => { x.refuels++; }); }
|
||||||
|
|
||||||
// hangar
|
// 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) {
|
function buy(me, item) {
|
||||||
const s = ledger.settings(); const p = player(me.memberId) || updPlayer(me.memberId, () => {});
|
const s = ledger.settings(); const p = player(me.memberId) || updPlayer(me.memberId, () => {});
|
||||||
|
const free = Number(p.freeUpgrades) > 0;
|
||||||
if (s.itemDrips[item] != null) {
|
if (s.itemDrips[item] != null) {
|
||||||
const cost = Number(s.itemDrips[item]);
|
const cost = Number(s.itemDrips[item]);
|
||||||
if (item === 'ship' && p.items.ship) return { error: 'You already own the Courier Mk II.' };
|
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 (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 + '.' };
|
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; });
|
updPlayer(me.memberId, x => { x.bank -= cost; x.items[item] = true; });
|
||||||
return { ok: true, paid: cost + ' drips' };
|
return { ok: true, paid: cost + ' drips' };
|
||||||
}
|
}
|
||||||
if (s.itemPol[item] != null) {
|
if (s.itemPol[item] != null) {
|
||||||
if (p.items[item]) return { error: 'That one is already armed for your next run.' };
|
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;
|
const r = ledger.spend(me, item, Number(s.itemPol[item])); if (r.error) return r;
|
||||||
updPlayer(me.memberId, x => { x.items[item] = true; });
|
updPlayer(me.memberId, x => { x.items[item] = true; });
|
||||||
return { ok: true, paid: r.pol + ' POL' };
|
return { ok: true, paid: r.pol + ' POL' };
|
||||||
@@ -131,7 +138,8 @@ function buy(me, item) {
|
|||||||
return { error: 'No such 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).
|
// 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) {
|
function adopt(fromId, toId) {
|
||||||
fromId = Number(fromId); toId = Number(toId); if (!fromId || fromId === toId) return { moved: false, pending: [] };
|
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: [] };
|
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;
|
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; });
|
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('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; });
|
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 };
|
return { moved: true, pending };
|
||||||
|
|||||||
+77
-6
@@ -25,6 +25,10 @@ const DEFAULTS = {
|
|||||||
itemPol: { shield: 0.05, slow: 0.03 }, // hangar items paid from the POL balance (the sink)
|
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)
|
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
|
refSharePct: 10, // the referrer's slice of each refuel's pool income (their referrals' refuels), paid into the referrer's game balance
|
||||||
|
// 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'
|
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
|
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'
|
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 --------------------------------------------------------------------
|
// ---- refuels: the income --------------------------------------------------------------------
|
||||||
async function refuel(me, info) {
|
async function refuel(me, info) {
|
||||||
const s = settings();
|
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 usd = credits * Number(s.usdPerCredit);
|
||||||
const share = usd * Number(s.poolSharePct) / 100;
|
const share = usd * Number(s.poolSharePct) / 100;
|
||||||
const rate = await usdPerPol();
|
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 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)]; }
|
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) {
|
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 (!eligible) return { pol: 0, reason: 'replay' };
|
||||||
|
if (!(pol > 0)) return { pol: 0, reason: 'none' };
|
||||||
const p = pool();
|
const p = pool();
|
||||||
if (p.capLeft < pol) return { pol: 0, reason: 'cap' };
|
if (p.capLeft < pol) return { pol: 0, reason: 'cap' };
|
||||||
if (p.available < pol) return { pol: 0, reason: 'pool' };
|
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; });
|
store.update('drips', [], all => { all.push(row); return all; });
|
||||||
poolAdd('out', pol);
|
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; });
|
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
|
// 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 };
|
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 ----------------------------------------------------------------------------------
|
// ---- payouts ----------------------------------------------------------------------------------
|
||||||
// a member whose unpaid balance reached the threshold gets one payout row for the whole amount;
|
// 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
|
// 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) {
|
function balance(memberId) {
|
||||||
const a = account(memberId); const s = settings();
|
const a = account(memberId); const s = settings();
|
||||||
const hist = []
|
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('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('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 })))
|
.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 };
|
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
@@ -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 };
|
||||||
@@ -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 };
|
||||||
@@ -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
@@ -7,7 +7,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node server.js",
|
"start": "node server.js",
|
||||||
"dev": "node --watch server.js",
|
"dev": "node --watch server.js",
|
||||||
"test": "node test/run.js"
|
"test": "node test/gamepass.js && node test/run.js"
|
||||||
},
|
},
|
||||||
"engines": { "node": ">=20" },
|
"engines": { "node": ">=20" },
|
||||||
"dependencies": { "ethers": "^6.13.0" }
|
"dependencies": { "ethers": "^6.13.0" }
|
||||||
|
|||||||
+2
-1
@@ -23,6 +23,7 @@
|
|||||||
<form id="settings" class="card" style="max-width:none">
|
<form id="settings" class="card" style="max-width:none">
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div><label>Drip per first clear (POL)</label><input name="dripPol" type="number" step="0.001" min="0"></div>
|
<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>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>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>
|
<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>Payouts</h2><div class="scroll"><table id="payouts"></table></div>
|
||||||
<h2>Recent runs</h2><div class="scroll"><table id="runs"></table></div>
|
<h2>Recent runs</h2><div class="scroll"><table id="runs"></table></div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/admin.js"></script>
|
<script src="/admin.js?v=20261102"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -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));
|
$('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 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');
|
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.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';
|
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);
|
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) {
|
$('settings').addEventListener('submit', function (e) {
|
||||||
e.preventDefault(); var f = e.target.elements; var body = {};
|
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.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);
|
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(); });
|
api('/api/admin/settings', body).then(function (r) { $('saveOut').textContent = r.ok ? 'Saved.' : (r.error || 'Failed'); load(); });
|
||||||
|
|||||||
+6
-6
@@ -6,7 +6,7 @@
|
|||||||
<title>Drip Runner · hop the network, get paid in POL</title>
|
<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 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: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" content="https://driprunner.app/og-driprunner.jpg">
|
||||||
<meta property="og:image:width" content="1200">
|
<meta property="og:image:width" content="1200">
|
||||||
<meta property="og:image:height" content="630">
|
<meta property="og:image:height" content="630">
|
||||||
@@ -45,9 +45,9 @@
|
|||||||
<div>
|
<div>
|
||||||
<p class="logo" style="font-size:22px">Drip<span>Runner</span></p>
|
<p class="logo" style="font-size:22px">Drip<span>Runner</span></p>
|
||||||
<h1>Hop the network.<br><em>Get paid in POL.</em></h1>
|
<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">
|
<div class="cta">
|
||||||
<a class="btn" href="https://instantadpay.com/api/my/driprunner">Play with InstantAdPay</a>
|
<a class="btn" href="/signin">Play with InstantAdPay</a>
|
||||||
<a class="btn ghost" href="/play">Try a run first</a>
|
<a class="btn ghost" href="/play">Try a run first</a>
|
||||||
</div>
|
</div>
|
||||||
<p class="muted">New to InstantAdPay? The first button signs you up free with just your email, then drops you straight into the game.</p>
|
<p class="muted">New to InstantAdPay? The first button signs you up free with just your email, then drops you straight into the game.</p>
|
||||||
@@ -69,7 +69,7 @@
|
|||||||
<h2>How it plays</h2>
|
<h2>How it plays</h2>
|
||||||
<div class="cols">
|
<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">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 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>
|
</div>
|
||||||
|
|
||||||
@@ -90,10 +90,10 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="cta" style="margin-top:26px">
|
<div class="cta" style="margin-top:26px">
|
||||||
<a class="btn" href="https://instantadpay.com/api/my/driprunner">Play with InstantAdPay</a>
|
<a class="btn" href="/signin">Play with InstantAdPay</a>
|
||||||
<a class="btn ghost" href="/play">Try a run first</a>
|
<a class="btn ghost" href="/play">Try a run first</a>
|
||||||
</div>
|
</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>
|
</div>
|
||||||
<script src="/landing.js"></script>
|
<script src="/landing.js"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -10,3 +10,16 @@
|
|||||||
document.querySelectorAll('.sThresh').forEach(function (e) { if (s.thresholdPol) e.textContent = n(s.thresholdPol, 2); });
|
document.querySelectorAll('.sThresh').forEach(function (e) { if (s.thresholdPol) e.textContent = n(s.thresholdPol, 2); });
|
||||||
}).catch(function () { $('stats').hidden = true; });
|
}).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';
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|||||||
+48
-6
@@ -7,7 +7,7 @@
|
|||||||
<title>Drip Runner</title>
|
<title>Drip Runner</title>
|
||||||
<meta property="og:title" content="Drip Runner: hop the network, get paid in POL">
|
<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: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 property="og:image" content="https://driprunner.app/og-driprunner.jpg">
|
||||||
<meta name="twitter:card" content="summary_large_image">
|
<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">
|
<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>
|
<style>
|
||||||
@@ -35,7 +35,8 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
|
|||||||
@keyframes pop{0%{transform:translate(-50%,10px) scale(.7)}30%{transform:translate(-50%,0) scale(1.1)}100%{transform:translate(-50%,-30px) scale(1)}}
|
@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}
|
.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{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}
|
.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. */
|
/* 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{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))}
|
.ov.lobby{justify-content:space-between;padding-bottom:calc(28px + env(safe-area-inset-bottom,0px))}
|
||||||
@@ -87,8 +88,28 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
|
|||||||
.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}
|
.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}
|
.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}
|
.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{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}
|
.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}
|
.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>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
@@ -116,13 +137,28 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
|
|||||||
<div class="stat"><small>Balance</small><b class="ok" id="lPol">0.000</b></div>
|
<div class="stat"><small>Balance</small><b class="ok" id="lPol">0.000</b></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="pool" id="lPool"></div>
|
<div class="pool" id="lPool"></div>
|
||||||
|
<div class="free" id="lPerk" hidden></div>
|
||||||
<div class="tip" id="lTip" hidden></div>
|
<div class="tip" id="lTip" hidden></div>
|
||||||
<button class="btn" id="bPlay" type="button">Play</button>
|
<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>
|
<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 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>
|
<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" 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 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>
|
</div>
|
||||||
@@ -134,8 +170,11 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
|
|||||||
<div class="big" id="cBig">+0.010<small>POL</small></div><p id="cText"></p><span class="chip ok" id="cChip"></span>
|
<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>
|
<div class="tip" id="cTip" hidden></div>
|
||||||
<button class="btn gold" id="bNext" type="button">Next chapter</button>
|
<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 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>
|
</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="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>
|
<div class="eyebrow" id="oEyebrow">Out of fuel</div><h2 id="oTitle">Run over</h2><p id="oText"></p>
|
||||||
@@ -146,6 +185,7 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
|
|||||||
|
|
||||||
<div class="ov" id="ovHangar" hidden><div class="sheet">
|
<div class="ov" id="ovHangar" hidden><div class="sheet">
|
||||||
<h3>Hangar <span class="bal" id="hgBal"></span></h3>
|
<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="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="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="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>
|
||||||
@@ -162,7 +202,9 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
|
|||||||
<button class="btn ghost" id="bLobby4" type="button">Back</button>
|
<button class="btn ghost" id="bLobby4" type="button">Back</button>
|
||||||
</div></div>
|
</div></div>
|
||||||
</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="/spawn.js"></script>
|
||||||
<script src="/play.js"></script>
|
<script src="/play.js?v=20261102gate"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+69
-21
@@ -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); }
|
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); }
|
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); }
|
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 ---------- */
|
/* ---------- lobby / me ---------- */
|
||||||
var ME_EXTRA = {};
|
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
|
// share: the phone's share sheet where there is one, else copy the link
|
||||||
function share(text) {
|
function share(text) {
|
||||||
var url = ME_EXTRA.share; if (!url) return toast('Set a username on InstantAdPay to get a share link.');
|
var url = ME_EXTRA.share; if (!url) return toast('Set a username on InstantAdPay to get a share link.');
|
||||||
@@ -57,18 +60,31 @@ function share(text) {
|
|||||||
function lobby() {
|
function lobby() {
|
||||||
R = null; $('hud').classList.remove('on'); $('tapdesk').hidden = true;
|
R = null; $('hud').classList.remove('on'); $('tapdesk').hidden = true;
|
||||||
$('lChap').textContent = P.chapter; $('lDrips').textContent = P.bank.toLocaleString(); $('lPol').textContent = f3(BAL.unpaid);
|
$('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');
|
$('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) {
|
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 || (IAP + '/api/my/driprunner'); $('lShare').hidden = true;
|
$('bSignin').hidden = false; $('bSignin').href = ME_EXTRA.signin || '/signin'; $('lShare').hidden = true;
|
||||||
} else {
|
} 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;
|
$('bSignin').hidden = true;
|
||||||
var rf = ME_EXTRA.referrals || {};
|
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>';
|
$('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');
|
show('ovLobby');
|
||||||
}
|
}
|
||||||
@@ -133,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);
|
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() {
|
function cleared() {
|
||||||
R.paused = true; pill('Verifying…');
|
R.paused = true; pill('Verifying…'); $('cOffer').hidden = true;
|
||||||
flush(true).then(function (r) {
|
flush(true).then(function (r) {
|
||||||
if (!R) return;
|
if (!R) return;
|
||||||
if (!r.cleared) { R.paused = false; if (r.short) toast('Server count says ' + r.short + ' more to go'); return; }
|
if (!r.cleared) { R.paused = false; if (r.short) toast('Server count says ' + r.short + ' more to go'); return; }
|
||||||
@@ -141,17 +157,45 @@ function cleared() {
|
|||||||
$('cEyebrow').textContent = 'Chapter ' + c.chapter + ' cleared'; $('cTitle').textContent = 'Banked ' + (R.goal) + ' drips';
|
$('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;
|
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);
|
$('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:';
|
$('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 || (IAP + '/api/my/driprunner');
|
$('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;
|
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(); });
|
$('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:'); });
|
$('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); });
|
$('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(); }
|
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); }); });
|
['bLobby1', 'bLobby2'].forEach(function (id) { $(id).addEventListener('click', function () { endRun().then(loadMe).then(lobby); }); });
|
||||||
@@ -165,7 +209,7 @@ function snapshot(nonce) {
|
|||||||
}
|
}
|
||||||
$('bRefuel').addEventListener('click', function () {
|
$('bRefuel').addEventListener('click', function () {
|
||||||
if (!R) return;
|
if (!R) return;
|
||||||
if (ME.guest) { location.href = ME_EXTRA.signin || (IAP + '/api/my/driprunner'); return; } // guests sign in first; their progress follows them
|
if (ME.guest) { location.href = ME_EXTRA.signin || '/signin'; return; } // guests sign in first; their progress follows them
|
||||||
$('bRefuel').disabled = true;
|
$('bRefuel').disabled = true;
|
||||||
api('/api/refuel/start', { runId: R.id }).then(function (r) {
|
api('/api/refuel/start', { runId: R.id }).then(function (r) {
|
||||||
$('bRefuel').disabled = false;
|
$('bRefuel').disabled = false;
|
||||||
@@ -190,15 +234,15 @@ function tryResume(q) {
|
|||||||
/* ---------- hangar / balance ---------- */
|
/* ---------- hangar / balance ---------- */
|
||||||
function hangar() {
|
function hangar() {
|
||||||
show('ovHangar'); $('hgBal').textContent = P.bank.toLocaleString() + ' drips · ' + f3(BAL.unpaid) + ' POL';
|
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('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('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('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');
|
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;
|
$('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() {
|
function balance() {
|
||||||
show('ovBal'); api('/api/balance').then(function (b) { BAL = b;
|
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 + '%';
|
$('bPol').textContent = f3(b.unpaid); var pct = Math.min(100, b.unpaid / b.threshold * 100); $('bProg').style.width = pct + '%';
|
||||||
@@ -206,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>';
|
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>'; });
|
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;
|
$('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 { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); }
|
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); }
|
||||||
@@ -249,12 +297,12 @@ resize(); requestAnimationFrame(loop);
|
|||||||
loadMe().then(function () {
|
loadMe().then(function () {
|
||||||
var q = new URLSearchParams(location.search);
|
var q = new URLSearchParams(location.search);
|
||||||
if (q.get('resume')) { history.replaceState(null, '', '/play'); return tryResume(q); }
|
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();
|
lobby();
|
||||||
}).catch(function (r) {
|
}).catch(function (r) {
|
||||||
var b = $('loadBtn'); b.hidden = false; b.href = (r && (r.signin || r.iap)) || IAP + '/api/my/driprunner';
|
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
|
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;
|
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(); }); }); };
|
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;
|
return;
|
||||||
|
|||||||
@@ -0,0 +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=20261003b"></script>
|
||||||
|
<script src="/signin.js?v=20261005b"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
// In-game sign-in (2026-10-03): the InstantAdPay kit runs on this page, so a player signs in (or opens a free
|
||||||
|
// InstantAdPay account) without leaving Drip Runner. The kit hands back the game token; /auth opens it as before.
|
||||||
|
(function () {
|
||||||
|
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
|
||||||
|
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
@@ -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>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>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>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>
|
</ul>
|
||||||
|
|
||||||
<h2>Where the POL comes from</h2>
|
<h2>Where the POL comes from</h2>
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
// Who may sign in is a setting (admin page): 'testers' (allowlist), 'open', 'closed'.
|
// Who may sign in is a setting (admin page): 'testers' (allowlist), 'open', 'closed'.
|
||||||
'use strict';
|
'use strict';
|
||||||
const http = require('http');
|
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 fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
@@ -23,7 +24,9 @@ const ledger = require('./lib/ledger');
|
|||||||
const faucet = require('./lib/faucet');
|
const faucet = require('./lib/faucet');
|
||||||
const spawn = require('./lib/spawn');
|
const spawn = require('./lib/spawn');
|
||||||
const badge = require('./lib/badge');
|
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 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 PORT = Number(process.env.PORT || 3000);
|
||||||
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
|
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
|
||||||
@@ -39,6 +42,8 @@ const IS_PROD = process.env.NODE_ENV === 'production';
|
|||||||
store.init(DATA_DIR);
|
store.init(DATA_DIR);
|
||||||
badge.init({ publicDir: PUBLIC_DIR, dataDir: DATA_DIR });
|
badge.init({ publicDir: PUBLIC_DIR, dataDir: DATA_DIR });
|
||||||
const faucetOn = faucet.init();
|
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) -------------------------------------------------------
|
// ---- Telegram to Marty (outward: gated) -------------------------------------------------------
|
||||||
async function telegram(text) {
|
async function telegram(text) {
|
||||||
@@ -53,6 +58,7 @@ async function telegramPhoto(file, caption, general, topicOverride) {
|
|||||||
if (!outbound()) return false;
|
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;
|
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;
|
if (!tok || !chat || !file) return false;
|
||||||
|
discordRelay.mirror({ chatId: chat, threadId: topic && !general ? Number(topic) : undefined, text: caption, photo: fs.readFileSync(file) });
|
||||||
try {
|
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));
|
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');
|
fd.append('photo', new Blob([fs.readFileSync(file)], { type: 'image/jpeg' }), 'badge.jpg');
|
||||||
@@ -91,19 +97,23 @@ function announcePaid(p) { announce('paid', { memberId: p.memberId, username: p.
|
|||||||
const explorer = () => Number(process.env.DR_CHAIN_ID) === 80002 ? 'https://amoy.polygonscan.com' : 'https://polygonscan.com';
|
const explorer = () => Number(process.env.DR_CHAIN_ID) === 80002 ? 'https://amoy.polygonscan.com' : 'https://polygonscan.com';
|
||||||
async function notify(kind, p) {
|
async function notify(kind, p) {
|
||||||
const who = p && (p.username ? '@' + p.username : '#' + p.memberId);
|
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>'); }
|
// 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 === '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 === '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 === '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 === '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)');
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- helpers ---------------------------------------------------------------------------------
|
// ---- helpers ---------------------------------------------------------------------------------
|
||||||
const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.webp': 'image/webp', '.mp4': 'video/mp4' };
|
const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.webp': 'image/webp', '.mp4': 'video/mp4' };
|
||||||
const CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; form-action 'self'";
|
// instantadpay.com: the in-game sign-in kit (script), its API (connect) and the signed-in nudge form (form-action), 2026-10-03
|
||||||
const SEC = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'X-Frame-Options': 'DENY', 'Content-Security-Policy': CSP };
|
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 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) {
|
function sendFile(res, file, extra) {
|
||||||
fs.readFile(file, (err, buf) => {
|
fs.readFile(file, (err, buf) => {
|
||||||
@@ -161,6 +171,59 @@ async function creditRefuel(intent, nonce, info) {
|
|||||||
// ---- server ------------------------------------------------------------------------------------
|
// ---- server ------------------------------------------------------------------------------------
|
||||||
const server = http.createServer(async (req, res) => {
|
const server = http.createServer(async (req, res) => {
|
||||||
const u = new URL(req.url, 'http://x'); const p = u.pathname;
|
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
|
// 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.
|
// 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.
|
// The API, the IAP callback, health and the badge art answer on every host.
|
||||||
@@ -173,7 +236,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
// ---- sign-in by hand-off (passes the curtain: the member already came through IAP) ----
|
// ---- sign-in by hand-off (passes the curtain: the member already came through IAP) ----
|
||||||
if (p === '/auth') {
|
if (p === '/auth') {
|
||||||
const r = sso.verify(u.searchParams.get('t'));
|
const r = sso.verify(u.searchParams.get('t'));
|
||||||
if (r.error) return page(res, 400, 'Sign-in did not work', '<p>' + esc(r.error) + '</p><p><a class="btn" href="' + IAP + '/api/my/driprunner">Try again from InstantAdPay</a></p>');
|
if (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)) { 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>'); }
|
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);
|
const existing = sso.fromRequest(req);
|
||||||
@@ -185,20 +248,47 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const adopted = [];
|
const adopted = [];
|
||||||
const guest = sso.guestFrom(req);
|
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'); }
|
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 : [];
|
// 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);
|
if (guest) sso.endGuest(guest.gid);
|
||||||
const first = !existedBefore;
|
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 => { 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; });
|
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 };
|
starter.grantPerk(r.claims.memberId); // a member (memberId > 0) gets one free hangar upgrade, once per account (2026-10-05)
|
||||||
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 (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(() => {});
|
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();
|
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 mr = /^\/r\/([A-Za-z0-9_.-]{1,40})$/.exec(p); if (mr) {
|
||||||
const sharer = game.byUsername(mr[1]);
|
const sharer = game.byUsername(mr[1]);
|
||||||
if (!sharer) { res.writeHead(302, { Location: '/', 'Cache-Control': 'no-store' }); return res.end(); }
|
// not a Drip Runner player (yet), but maybe an InstantAdPay member: the landing keeps the name as ?ref (2026-10-05), and
|
||||||
const ck = ['dr.ref=' + encodeURIComponent(sharer.username.toLowerCase()) + '; Path=/; Max-Age=' + 30 * 86400 + '; SameSite=Lax' + (IS_PROD ? '; Secure' : '')];
|
// 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
|
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; });
|
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();
|
res.writeHead(302, { Location: '/play', 'Set-Cookie': ck, 'Cache-Control': 'no-store' }); return res.end();
|
||||||
@@ -217,9 +307,18 @@ const server = http.createServer(async (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---- static + pages ----
|
// ---- static + pages ----
|
||||||
if (p === '/' || p === '/index.html') { if (curtained(req, res, u)) return; return sendFile(res, path.join(PUBLIC_DIR, 'index.html')); }
|
// 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 === '/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 === '/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 === '/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 (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
|
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
|
||||||
@@ -257,11 +356,12 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const accounts = store.read('accounts', {}); const players = store.read('players', {});
|
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(),
|
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(),
|
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 });
|
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') {
|
if (p === '/api/admin/settings' && req.method === 'POST') {
|
||||||
const { body } = await readBody(req); const patch = {};
|
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]);
|
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.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 (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 (Array.isArray(body.testers)) patch.testers = body.testers.map(x => String(x).trim().toLowerCase()).filter(Boolean).slice(0, 500);
|
||||||
@@ -269,6 +369,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (body.itemDrips && typeof body.itemDrips === 'object') patch.itemDrips = Object.assign({}, ledger.settings().itemDrips, body.itemDrips);
|
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) });
|
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/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}
|
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 { body } = await readBody(req); const pl = game.player(Number(body.memberId)); if (!pl) return json(res, 404, { error: 'no such player' });
|
||||||
@@ -280,17 +381,17 @@ const server = http.createServer(async (req, res) => {
|
|||||||
return json(res, 400, { error: 'unknown badge id' });
|
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)
|
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' }) });
|
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' });
|
return json(res, 404, { error: 'no such admin route' });
|
||||||
}
|
}
|
||||||
if (p === '/api/guest' && req.method === 'POST') {
|
if (p === '/api/guest' && req.method === 'POST') {
|
||||||
if (me) return json(res, 200, { ok: true, already: true });
|
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.' });
|
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 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);
|
const who = me || sso.guestFrom(req);
|
||||||
if (!who) return json(res, 401, { error: 'Sign in through InstantAdPay first.', iap: IAP + '/api/my/driprunner', guestOk: !CURTAIN || hasPass(req), signin: signinUrl(req) });
|
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);
|
return memberApi(req, res, u, p, who);
|
||||||
}
|
}
|
||||||
res.writeHead(404, Object.assign({ 'Content-Type': 'text/plain' }, SEC)); res.end('Not found');
|
res.writeHead(404, Object.assign({ 'Content-Type': 'text/plain' }, SEC)); res.end('Not found');
|
||||||
@@ -299,21 +400,30 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (!res.headersSent) json(res, 500, { error: 'Something broke on our side. Try again.' });
|
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; }
|
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
|
// where a guest signs in: through the sharer's InstantAdPay join link when they came from one (new people land under the sharer), else the plain hand-off
|
||||||
function signinUrl(req) { const r = refCookie(req); return r ? IAP + '/join/' + encodeURIComponent(r) + '?from=driprunner' : IAP + '/api/my/driprunner'; }
|
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) {
|
async function memberApi(req, res, u, p, me) {
|
||||||
try {
|
try {
|
||||||
{
|
{
|
||||||
if (p === '/api/me' && req.method === 'GET') {
|
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();
|
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);
|
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()),
|
// tier (2026-11-02): guest = earns nothing, free = freeSharePct of the table (yourDrip), full = the table (Game Pass, or GAMEPASS off)
|
||||||
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 } });
|
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/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/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 }); }
|
||||||
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); }
|
// 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 || ''))); }
|
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
|
// refuel: hand the player to IAP for a verified visit; the run resumes when IAP confirms
|
||||||
if (p === '/api/refuel/start' && req.method === 'POST') {
|
if (p === '/api/refuel/start' && req.method === 'POST') {
|
||||||
@@ -345,3 +455,5 @@ async function memberApi(req, res, u, p, me) {
|
|||||||
}
|
}
|
||||||
server.listen(PORT, () => console.log('Drip Runner on', PORT, '| curtain', !!CURTAIN, '| sso', sso.enabled(), '| faucet', faucetOn, faucet.dry() ? '(DRY RUN)' : '(LIVE)', '| outbound', outbound()));
|
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); }
|
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();
|
||||||
|
|||||||
@@ -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); });
|
||||||
+44
-7
@@ -31,7 +31,7 @@ const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|||||||
const spawnLib = require('../lib/spawn');
|
const spawnLib = require('../lib/spawn');
|
||||||
|
|
||||||
(async () => {
|
(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');
|
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');
|
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 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 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');
|
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 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');
|
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');
|
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
|
// 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)');
|
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 });
|
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');
|
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 } });
|
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');
|
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,23 +101,31 @@ 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 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 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 });
|
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');
|
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);
|
let g = jarAdd('', sh.set);
|
||||||
const me401 = await hit('/api/me', {}, g); eq([me401.status, me401.body.guestOk, /join\/runner42\?from=driprunner/.test(me401.body.signin)], [401, true, true], 'a newcomer is offered guest play, sign-in goes through the sharer’s join link');
|
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)');
|
||||||
const gs = await hit('/api/guest', { method: 'POST', body: '{}' }, g); g = jarAdd(g, gs.set); eq(gs.status, 200, 'guest session starts');
|
const gs = await hit('/api/guest', { method: 'POST', body: '{}' }, g); g = jarAdd(g, gs.set); eq(gs.status, 200, 'guest session starts');
|
||||||
const gme = await hit('/api/me', {}, g); eq([gme.status, gme.body.me.guest, gme.body.player.chapter], [200, true, 1], 'guest plays chapter 1');
|
const gme = await hit('/api/me', {}, g); eq([gme.status, gme.body.me.guest, gme.body.player.chapter], [200, true, 1], 'guest plays chapter 1');
|
||||||
const gr = (await hit('/api/run/start', { method: 'POST', body: JSON.stringify({ W, H }) }, g)).body;
|
const gr = (await hit('/api/run/start', { method: 'POST', body: JSON.stringify({ W, H }) }, g)).body;
|
||||||
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 }); } }
|
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);
|
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;
|
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');
|
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 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);
|
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');
|
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], [false, 2, 20, 0.01], 'progress and the drip followed the newcomer');
|
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
|
// 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 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;
|
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' });
|
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');
|
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');
|
console.log(fails ? '\n' + fails + ' FAILED' : '\nall good');
|
||||||
child.kill(); fs.rmSync(DIR, { recursive: true, force: true }); process.exit(fails ? 1 : 0);
|
child.kill(); fs.rmSync(DIR, { recursive: true, force: true }); process.exit(fails ? 1 : 0);
|
||||||
})().catch(e => { console.error(e); child.kill(); process.exit(1); });
|
})().catch(e => { console.error(e); child.kill(); process.exit(1); });
|
||||||
|
|||||||
+107
@@ -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); });
|
||||||
@@ -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')
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# In-game sign-in (Marty, 2026-10-03): /signin is our own page running the InstantAdPay kit; every sign-in link
|
||||||
|
# points there; the CSP admits instantadpay.com for the kit script, its API calls and the nudge form.
|
||||||
|
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 CSP = \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; form-action 'self'\";",
|
||||||
|
"// instantadpay.com: the in-game sign-in kit (script), its API (connect) and the signed-in nudge form (form-action), 2026-10-03\n"
|
||||||
|
"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;"),
|
||||||
|
("function signinUrl(req) { const r = refCookie(req); return r ? IAP + '/join/' + encodeURIComponent(r) + '?from=driprunner' : IAP + '/api/my/driprunner'; }",
|
||||||
|
"function signinUrl(req) { return '/signin'; } // in-game sign-in (2026-10-03); the kit carries the dr.ref sponsor itself"),
|
||||||
|
(" 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'));\n"
|
||||||
|
" if (p === '/signin') return sendFile(res, path.join(PUBLIC_DIR, 'signin.html')); // in-game sign-in (InstantAdPay kit)\n"),
|
||||||
|
("res, 400, 'Sign-in did not work', '<p>' + esc(r.error) + '</p><p><a class=\"btn\" href=\"' + IAP + '/api/my/driprunner\">Try again from InstantAdPay</a></p>');",
|
||||||
|
"res, 400, 'Sign-in did not work', '<p>' + esc(r.error) + '</p><p><a class=\"btn\" href=\"/signin\">Try again</a></p>');"),
|
||||||
|
("return json(res, 401, { error: 'Sign in through InstantAdPay first.', iap: IAP + '/api/my/driprunner',",
|
||||||
|
"return json(res, 401, { error: 'Sign in with your InstantAdPay account first.', iap: '/signin',"),
|
||||||
|
])
|
||||||
|
edit('public/play.js', [
|
||||||
|
(" $('lIap').href = IAP + '/my'; $('bLevel').href = IAP + '/my#buy'; tip('lTip');",
|
||||||
|
" $('lIap').href = IAP + '/my'; $('bLevel').href = IAP + '/my#buy'; tip('lTip');\n"
|
||||||
|
" // signed in through the game: these open InstantAdPay already signed in (in-game sign-in pass, 2026-10-03)\n"
|
||||||
|
" [['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]); } }); } });"),
|
||||||
|
("$('bSignin').href = ME_EXTRA.signin || (IAP + '/api/my/driprunner');", "$('bSignin').href = ME_EXTRA.signin || '/signin';"),
|
||||||
|
("$('bClearSignin').href = ME_EXTRA.signin || (IAP + '/api/my/driprunner');", "$('bClearSignin').href = ME_EXTRA.signin || '/signin';"),
|
||||||
|
("location.href = ME_EXTRA.signin || (IAP + '/api/my/driprunner'); return; }", "location.href = ME_EXTRA.signin || '/signin'; return; }"),
|
||||||
|
("b.href = (r && (r.signin || r.iap)) || IAP + '/api/my/driprunner';", "b.href = (r && (r.signin || r.iap)) || '/signin';"),
|
||||||
|
])
|
||||||
|
edit('public/play.html', [
|
||||||
|
('<script src="/spawn.js"></script>', '<script src="https://instantadpay.com/assets/game-signin.js?v=20261003a" async></script>\n<script src="/spawn.js"></script>'),
|
||||||
|
])
|
||||||
|
b =open(ROOT + 'public/index.html', 'rb').read().decode('utf-8')
|
||||||
|
n = b.count('href="https://instantadpay.com/api/my/driprunner">Play with InstantAdPay</a>')
|
||||||
|
if n != 2: raise SystemExit('index anchors %d' % n)
|
||||||
|
open(ROOT + 'public/index.html', 'wb').write(b.replace('href="https://instantadpay.com/api/my/driprunner">Play with InstantAdPay</a>', 'href="/signin">Play with InstantAdPay</a>').encode('utf-8')); print('patched public/index.html')
|
||||||
|
print('ok')
|
||||||
@@ -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')
|
||||||
Reference in New Issue
Block a user