Member welcome offer + member perk: after a chapter clear, a signed-in non-member (IAP memberId 0) sees a dismissible "Become an InstantAdPay member" card once per Central day (bonus from IAP /api/starter/public, cached 10 min, skipped when off); a member's first hand-off grants one free hangar upgrade (token on the player, next purchase costs nothing, no POL moved), with a one-time lobby message

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-05 06:24:20 -05:00
parent 4fa68b2745
commit 09692de8c6
8 changed files with 218 additions and 13 deletions
+1
View File
@@ -1,5 +1,6 @@
node_modules/
data/
data-test/
data-test-starter/
*.log
.env
+6 -1
View File
@@ -27,7 +27,7 @@ function updPlayer(memberId, fn) {
function view(me) {
const p = player(me.memberId) || updPlayer(me.memberId, () => {});
const s = ledger.settings();
return { bank: p.bank, chapter: p.chapter, cleared: p.cleared, items: p.items, best: p.runs ? p.best : 0, runs: p.runs,
return { bank: p.bank, chapter: p.chapter, cleared: p.cleared, items: p.items, best: p.runs ? p.best : 0, runs: p.runs, freeUpgrades: Number(p.freeUpgrades) || 0,
goal: spawn.goalFor(p.chapter), prices: { pol: s.itemPol, drips: s.itemDrips }, dripPol: Number(s.dripPol) };
}
@@ -112,18 +112,23 @@ function end(me, runId) {
function refuelled(me, runId) { return updRun(runId, x => { x.refuels++; }); }
// hangar
// a free upgrade token (the member perk, lib/starter.js) pays for the next purchase whatever it is: no drips, no POL moved
function useFree(me, item) { updPlayer(me.memberId, x => { x.freeUpgrades = Math.max(0, (Number(x.freeUpgrades) || 0) - 1); x.items[item] = true; }); return { ok: true, free: true, paid: 'free upgrade' }; }
function buy(me, item) {
const s = ledger.settings(); const p = player(me.memberId) || updPlayer(me.memberId, () => {});
const free = Number(p.freeUpgrades) > 0;
if (s.itemDrips[item] != null) {
const cost = Number(s.itemDrips[item]);
if (item === 'ship' && p.items.ship) return { error: 'You already own the Courier Mk II.' };
if (p.items[item] && item !== 'ship') return { error: 'That one is already armed for your next run.' };
if (free) return useFree(me, item);
if (p.bank < cost) return { error: 'Not enough drips. You have ' + p.bank + ', it costs ' + cost + '.' };
updPlayer(me.memberId, x => { x.bank -= cost; x.items[item] = true; });
return { ok: true, paid: cost + ' drips' };
}
if (s.itemPol[item] != null) {
if (p.items[item]) return { error: 'That one is already armed for your next run.' };
if (free) return useFree(me, item);
const r = ledger.spend(me, item, Number(s.itemPol[item])); if (r.error) return r;
updPlayer(me.memberId, x => { x.items[item] = true; });
return { ok: true, paid: r.pol + ' POL' };
+60
View File
@@ -0,0 +1,60 @@
// Member welcome offer (Marty, 2026-10-05): turn players into InstantAdPay members through the $5 package.
//
// After a chapter clear, a signed-in player with no InstantAdPay member id yet (the hand-off carried memberId 0, so they
// play on the negative email id) gets one card a Central day: "Become an InstantAdPay member". Never a guest, never
// during a run. InstantAdPay owns the purchase and its bonus credits; the bonus number comes from its public endpoint
// (cached ten minutes) and the offer stays off while InstantAdPay says it is off. If the endpoint cannot be read the
// card still shows, without a number.
//
// The perk here: the first time a member (memberId > 0) comes through the hand-off, one free hangar upgrade. It is a
// token on the player (freeUpgrades) that makes the next hangar purchase cost nothing, drips or POL. A free POL item
// moves no POL: nothing leaves the pool and nothing is paid out, so Marty's "no POL the game did not earn" rule holds.
//
// Player record fields: starterShown (the Central day the card last showed), perkAt (ms, granted once, never again),
// freeUpgrades (tokens left), perkNotice (the one-time lobby message is still to be shown).
'use strict';
const game = require('./game');
const ledger = require('./ledger');
const IAP = () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
const PERK = 'a free hangar upgrade';
const NOTICE = 'Member perk: a free hangar upgrade. Thanks for joining InstantAdPay!';
let cache = { at: 0, v: null };
// InstantAdPay's public offer numbers: { on, bonus } or null when unreadable (a failure is remembered for a minute)
async function publicOffer() {
if (Date.now() - cache.at < 10 * 60000) return cache.v;
try {
const r = await fetch(IAP() + '/api/starter/public', { signal: AbortSignal.timeout(5000) }); if (!r.ok) throw new Error('http ' + r.status);
const j = await r.json(); const b = Number(j.bonus);
cache = { at: Date.now(), v: { on: j.on !== false, bonus: isFinite(b) && b > 0 ? Math.round(b) : null } };
} catch (e) { cache = { at: Date.now() - 9 * 60000, v: null }; }
return cache.v;
}
// the card for this clear, or null. Counts as shown the moment it is handed out.
async function offerFor(me) {
if (!me || me.guest || Number(me.memberId) > 0) return null;
const p = game.player(me.memberId); const today = ledger.ctDay();
if (!p || p.starterShown === today) return null;
const pub = await publicOffer();
if (pub && pub.on === false) return null;
let fresh = false; game.updPlayer(me.memberId, x => { if (x.starterShown !== today) { x.starterShown = today; fresh = true; } });
if (!fresh) return null;
return { bonus: pub ? pub.bonus : null, perk: PERK, url: IAP() + '/my?from=driprunner#buy' };
}
// the hand-off: a member's first visit as a member gets the free upgrade, once per account
function grantPerk(memberId) {
if (!(Number(memberId) > 0)) return false; let granted = false;
game.updPlayer(memberId, x => { if (!x.perkAt) { x.perkAt = Date.now(); x.freeUpgrades = (Number(x.freeUpgrades) || 0) + 1; x.perkNotice = true; granted = true; } });
return granted;
}
// the one-time lobby message: handed out once, then cleared
function takeNotice(memberId) {
const p = game.player(memberId); if (!p || !p.perkNotice) return null;
game.updPlayer(memberId, x => { delete x.perkNotice; });
return NOTICE;
}
module.exports = { publicOffer, offerFor, grantPerk, takeNotice, PERK };
+16 -2
View File
@@ -90,6 +90,15 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
.shr{margin-top:10px;padding:10px 12px;border-radius:10px;border:1px solid var(--line);background:rgba(14,23,45,.6);font-size:11px;color:var(--muted);text-align:center}.shr b{color:var(--gold)}.shr .btn{margin-top:8px}
.toast{position:absolute;left:50%;bottom:calc(70px + env(safe-area-inset-bottom,0px));transform:translateX(-50%);z-index:20;background:var(--panel2);border:1px solid var(--line);color:var(--ink);font-size:12px;padding:8px 12px;border-radius:10px;opacity:0;transition:opacity .2s;pointer-events:none;max-width:92%;text-align:center}
.toast.on{opacity:1}
/* member welcome offer (2026-10-05): an extra card under the chapter-clear result, never during a run, never blocking */
.offer{margin-top:12px;background:linear-gradient(180deg,rgba(40,32,12,.96),rgba(14,23,45,.98));border:1px solid rgba(255,194,75,.45);border-radius:16px;padding:16px 16px 12px;text-align:center;box-shadow:0 20px 50px -20px rgba(0,0,0,.9),0 0 40px -18px rgba(255,194,75,.45);animation:offerIn .4s ease-out .7s backwards}
.offer .eyebrow{font:700 10px var(--body);letter-spacing:.2em;text-transform:uppercase;color:var(--gold)}
.offer h4{font:900 17px/1.15 var(--display);letter-spacing:.05em;text-transform:uppercase;margin:6px 0 4px}
.offer p{font-size:13px;color:var(--ink2);margin:4px 0 0}.offer p b{color:var(--gold)}
.offer .btn{text-decoration:none;text-align:center;font-size:13px;padding:12px}
@keyframes offerIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
.free{padding:9px 12px;border-radius:10px;background:rgba(255,194,75,.1);border:1px solid rgba(255,194,75,.45);font-size:12px;color:var(--gold2);text-align:left}.free b{color:var(--gold)}
.buy.free{border-color:rgba(255,194,75,.7);background:rgba(255,194,75,.2);color:var(--gold2)}
.tapdesk{position:absolute;bottom:calc(14px + env(safe-area-inset-bottom,0px));left:14px;z-index:5;font:600 10px var(--body);letter-spacing:.14em;text-transform:uppercase;color:var(--muted);pointer-events:none}
</style>
</head>
@@ -117,6 +126,7 @@ 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>
<div class="pool" id="lPool"></div>
<div class="free" id="lPerk" hidden></div>
<div class="tip" id="lTip" hidden></div>
<button class="btn" id="bPlay" type="button">Play</button>
<div class="row2"><button class="btn ghost" id="bHangar" type="button">Hangar</button><button class="btn ghost" id="bBalance" type="button">Balance</button></div>
@@ -137,7 +147,10 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
<div class="tip" id="cTip" hidden></div>
<button class="btn gold" id="bNext" type="button">Next chapter</button>
<div class="row2"><button class="btn ghost" id="bShareClear" type="button" hidden>Share this</button><a class="btn ghost" id="bClearSignin" href="#" hidden style="text-decoration:none;text-align:center">Sign in to collect</a></div><button class="btn ghost" id="bLobby1" type="button">Back to lobby</button>
</div></div>
</div>
<div class="offer" id="cOffer" hidden><div class="eyebrow">Member welcome offer</div><h4>Become an InstantAdPay member</h4><p id="cOfferText"></p>
<a class="btn gold" id="cOfferGo" href="https://instantadpay.com/my?from=driprunner#buy">Get the $5 package</a><button class="btn ghost" id="cOfferNo" type="button">Not now</button></div>
</div>
<div class="ov" id="ovOver" hidden><div class="card">
<div class="eyebrow" id="oEyebrow">Out of fuel</div><h2 id="oTitle">Run over</h2><p id="oText"></p>
@@ -148,6 +161,7 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
<div class="ov" id="ovHangar" hidden><div class="sheet">
<h3>Hangar <span class="bal" id="hgBal"></span></h3>
<div class="free" id="hgFree" hidden><b>Free upgrade ready.</b> Your member perk: your next hangar purchase costs nothing. Pick any item below.</div>
<div class="item" id="itMagnet"><div class="ic gold"><i></i></div><div><b>Drip magnet</b><small>pulls drips toward you, whole next run</small></div><button class="buy" data-buy="magnet" type="button"></button></div>
<div class="item" id="itShip"><div class="ic"><i></i></div><div><b>Courier Mk II</b><small>lighter hull, tighter hops, gold trail</small></div><button class="buy" data-buy="ship" type="button"></button></div>
<div class="item" id="itShield"><div class="ic sig"><i></i></div><div><b>Shield core</b><small>survive one hit next run · paid from your POL balance</small></div><button class="buy pol" data-buy="shield" type="button"></button></div>
@@ -167,6 +181,6 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
<script src="https://instantadpay.com/assets/game-signin.js?v=20261003a" async></script>
<script src="https://instantadpay.com/assets/game-strip.js?v=20261003a"></script>
<script src="/spawn.js"></script>
<script src="/play.js"></script>
<script src="/play.js?v=20261005a"></script>
</body>
</html>
+19 -6
View File
@@ -45,7 +45,7 @@ function f3(n) { return Number(n || 0).toFixed(3); }
/* ---------- lobby / me ---------- */
var ME_EXTRA = {};
function loadMe() { return api('/api/me').then(function (r) { if (r._status !== 200) throw r; ME = r.me; P = r.player; BAL = r.balance; POOL = r.pool; IAP = r.iap || IAP; TIPS = r.tips || []; ME_EXTRA = { signin: r.signin, share: r.share, referrals: r.referrals }; return r; }); }
function loadMe() { return api('/api/me').then(function (r) { if (r._status !== 200) throw r; ME = r.me; P = r.player; BAL = r.balance; POOL = r.pool; IAP = r.iap || IAP; TIPS = r.tips || []; ME_EXTRA = { signin: r.signin, share: r.share, referrals: r.referrals, perk: r.perk || ME_EXTRA.perk || null }; return r; }); } // perk: the one-time member message, kept for this page load
// share: the phone's share sheet where there is one, else copy the link
function share(text) {
var url = ME_EXTRA.share; if (!url) return toast('Set a username on InstantAdPay to get a share link.');
@@ -59,6 +59,8 @@ function lobby() {
$('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>';
$('lIap').href = IAP + '/my'; $('bLevel').href = IAP + '/my#buy'; tip('lTip');
$('lPerk').hidden = !ME_EXTRA.perk; $('lPerk').textContent = ME_EXTRA.perk || ''; // member perk (2026-10-05)
$('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]); } }); } });
@@ -136,7 +138,7 @@ function over(title, why) {
setTimeout(function () { if (!R) return; $('oEyebrow').textContent = title; $('oTitle').textContent = 'Run over at ' + R.drips; $('oText').textContent = why + ' Refuel with a sponsor visit and keep this run, drips and chapter progress intact.'; $('bRefuel').hidden = false; $('oChip').hidden = false; tip('oTip'); show('ovOver'); }, 450);
}
function cleared() {
R.paused = true; pill('Verifying…');
R.paused = true; pill('Verifying…'); $('cOffer').hidden = true;
flush(true).then(function (r) {
if (!R) return;
if (!r.cleared) { R.paused = false; if (r.short) toast('Server count says ' + r.short + ' more to go'); return; }
@@ -149,9 +151,20 @@ function cleared() {
$('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';
R.chapter = c.next; R.goal = c.nextGoal; R.chapDrips = 0; if (r.pool != null) POOL.available = r.pool;
tip('cTip'); setTimeout(function () { show('ovClear'); }, 500);
tip('cTip'); setTimeout(function () { show('ovClear'); if (r.starterOffer) starterOffer(r.starterOffer); }, 500); // the offer card fades in under the result (CSS delay)
});
}
/* member welcome offer (2026-10-05): the server sends it after a clear, at most once a Central day, to signed-in players who are
not InstantAdPay members yet. Dismissible, never blocks the next chapter. In a frame the link opens a new tab. */
function starterOffer(o) {
var b = Number(o.bonus) > 0 ? '+' + Number(o.bonus).toLocaleString() + ' bonus ad credits' : 'bonus ad credits';
$('cOfferText').innerHTML = 'Your first $5 package comes with <b>' + esc(b) + '</b>, and ' + esc(o.perk || 'a free hangar upgrade') + ' here in Drip Runner.';
var a = $('cOfferGo'); a.href = o.url || (IAP + '/my?from=driprunner#buy');
var framed = false; try { framed = window.self !== window.top; } catch (e) { framed = true; }
if (framed) { a.target = '_blank'; a.rel = 'noopener'; } else { a.removeAttribute('target'); a.removeAttribute('rel'); }
$('cOffer').hidden = false;
}
$('cOfferNo').addEventListener('click', function () { $('cOffer').hidden = true; });
$('bNext').addEventListener('click', function () { if (!R) return; R.paused = false; R.inv = 1.5; hideAll(); });
$('bShareClear').addEventListener('click', function () { share(this.dataset.text || 'Play Drip Runner with me:'); });
$('bShare').addEventListener('click', function () { share('I am playing Drip Runner, a game that pays in POL. Hop the network, dodge the bots:'); });
@@ -193,15 +206,15 @@ function tryResume(q) {
/* ---------- hangar / balance ---------- */
function hangar() {
show('ovHangar'); $('hgBal').textContent = P.bank.toLocaleString() + ' drips · ' + f3(BAL.unpaid) + ' POL';
var pr = P.prices;
var pr = P.prices, free = P.freeUpgrades > 0; $('hgFree').hidden = !free; // the member perk: the next purchase costs nothing
set('itMagnet', 'magnet', P.items.magnet, P.bank >= pr.drips.magnet, pr.drips.magnet + ' drips', 'armed');
set('itShip', 'ship', P.items.ship, P.bank >= pr.drips.ship, pr.drips.ship + ' drips', 'owned');
set('itShield', 'shield', P.items.shield, BAL.unpaid >= pr.pol.shield, f3(pr.pol.shield) + ' POL', 'armed');
set('itSlow', 'slow', P.items.slow, BAL.unpaid >= pr.pol.slow, f3(pr.pol.slow) + ' POL', 'armed');
function set(id, key, own, can, label, ownLabel) { var it = $(id), b = it.querySelector('.buy'); it.classList.toggle('owned', !!own); b.className = 'buy' + (/POL/.test(label) ? ' pol' : '') + (own ? ' own' : (can ? '' : ' no')); b.textContent = own ? ownLabel : label; }
function set(id, key, own, can, label, ownLabel) { var it = $(id), b = it.querySelector('.buy'); it.classList.toggle('owned', !!own); b.className = 'buy' + (/POL/.test(label) ? ' pol' : '') + (own ? ' own' : (free ? ' free' : (can ? '' : ' no'))); b.textContent = own ? ownLabel : (free ? 'Free' : label); }
}
$('ovHangar').addEventListener('click', function (e) { var b = e.target.closest('[data-buy]'); if (!b) return; b.disabled = true;
api('/api/hangar/buy', { item: b.dataset.buy }).then(function (r) { b.disabled = false; if (r._status !== 200) return toast(r.error || 'Could not buy that.'); P = r.player; BAL = r.balance; sfx.buy(); toast('Paid ' + r.paid); hangar(); }); });
api('/api/hangar/buy', { item: b.dataset.buy }).then(function (r) { b.disabled = false; if (r._status !== 200) return toast(r.error || 'Could not buy that.'); P = r.player; BAL = r.balance; sfx.buy(); toast(r.free ? 'Free upgrade used. Enjoy the run!' : 'Paid ' + r.paid); hangar(); }); });
function balance() {
show('ovBal'); api('/api/balance').then(function (b) { BAL = b;
$('bPol').textContent = f3(b.unpaid); var pct = Math.min(100, b.unpaid / b.threshold * 100); $('bProg').style.width = pct + '%';
+7 -3
View File
@@ -25,6 +25,7 @@ const spawn = require('./lib/spawn');
const badge = require('./lib/badge');
const srctrack = require('./lib/srctrack'); // paid-traffic sources (2026-10-03)
const tips = require('./lib/tips'); // facts you learn as you play, priced from the live IAP catalog
const starter = require('./lib/starter'); // member welcome offer + the member perk (2026-10-05)
const PORT = Number(process.env.PORT || 3000);
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
@@ -199,6 +200,7 @@ const server = http.createServer(async (req, res) => {
const first = !existedBefore;
game.updPlayer(r.claims.memberId, x => { x.email = String(r.claims.email).toLowerCase(); x.username = r.claims.username || x.username || null; x.wallet = r.claims.wallet ? String(r.claims.wallet).toLowerCase() : x.wallet || null; x.lastSeen = Date.now(); });
game.updPlayer(r.claims.memberId, x => { if (!x.sponsorRef && r.claims.sponsorRef) x.sponsorRef = String(r.claims.sponsorRef).toLowerCase(); if (r.claims.joinedRef && !x.joinedRef) x.joinedRef = r.claims.joinedRef; });
starter.grantPerk(r.claims.memberId); // a member (memberId > 0) gets one free hangar upgrade, once per account (2026-10-05)
const meNow = { memberId: Number(r.claims.memberId), username: r.claims.username || null, wallet: r.claims.wallet ? String(r.claims.wallet).toLowerCase() : null };
for (const ch of pendingClears) { const g = ledger.chapterDrip(meNow, ch, true); if (g.pol) announceChapter(meNow, ch, g.pol); } // clears made as a guest pay now
{ const t = srctrack.fromRequest(req); if (t) {
@@ -290,7 +292,7 @@ const server = http.createServer(async (req, res) => {
const accounts = store.read('accounts', {}); const players = store.read('players', {});
return json(res, 200, { settings: ledger.settings(), pool: ledger.pool(), usdPerPol: await ledger.usdPerPol(), faucet: faucet.state(),
refuels: store.read('refuels', []).slice(-100).reverse(), drips: store.read('drips', []).slice(-100).reverse(), spends: store.read('spends', []).slice(-100).reverse(), payouts: store.read('payouts', []).slice(-100).reverse(),
accounts: Object.values(accounts), players: Object.values(players).map(x => ({ memberId: x.memberId, username: x.username, email: x.email, wallet: x.wallet, chapter: x.chapter, bank: x.bank, best: x.best, runs: x.runs, lastSeen: x.lastSeen, items: x.items })), runs: game.recent(60), site: SITE, iap: IAP, curtain: CURTAIN ? SITE + '/?k=' + CURTAIN : SITE });
accounts: Object.values(accounts), players: Object.values(players).map(x => ({ memberId: x.memberId, username: x.username, email: x.email, wallet: x.wallet, chapter: x.chapter, bank: x.bank, best: x.best, runs: x.runs, lastSeen: x.lastSeen, items: x.items, perkAt: x.perkAt || null, freeUpgrades: Number(x.freeUpgrades) || 0 })), runs: game.recent(60), site: SITE, iap: IAP, curtain: CURTAIN ? SITE + '/?k=' + CURTAIN : SITE });
}
if (p === '/api/admin/settings' && req.method === 'POST') {
const { body } = await readBody(req); const patch = {};
@@ -343,11 +345,13 @@ async function memberApi(req, res, u, p, me) {
const pl = ledger.pool();
const refs = me.guest ? [] : game.referralsOf(me);
return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet, guest: !!me.guest }, player: game.view(me), balance: ledger.balance(me.memberId), pool: { available: pl.available, capLeft: pl.capLeft, dripPol: Number(ledger.settings().dripPol) }, iap: IAP, site: SITE, tips: await tips.list(ledger.settings()),
signin: me.guest ? signinUrl(req) : null, share: (!me.guest && me.username) ? SITE + '/r/' + encodeURIComponent(me.username) : null, referrals: { count: refs.length, clicks: (store.read('share-hits', {})[String(me.username || '').toLowerCase()] || 0), earned: ledger.balance(me.memberId).refTotal, pct: Number(ledger.settings().refSharePct) || 0 } });
signin: me.guest ? signinUrl(req) : null, share: (!me.guest && me.username) ? SITE + '/r/' + encodeURIComponent(me.username) : null, referrals: { count: refs.length, clicks: (store.read('share-hits', {})[String(me.username || '').toLowerCase()] || 0), earned: ledger.balance(me.memberId).refTotal, pct: Number(ledger.settings().refSharePct) || 0 },
perk: me.guest ? null : starter.takeNotice(me.memberId) }); // the member perk's one-time message (2026-10-05)
}
if (p === '/api/balance' && req.method === 'GET') return json(res, 200, ledger.balance(me.memberId));
if (p === '/api/run/start' && req.method === 'POST') { const { body } = await readBody(req); { const t = srctrack.fromRequest(req); if (t) srctrack.bump(t.src, 'runs', me.memberId); } const r = game.start(me, body.W, body.H); return json(res, 200, { runId: r.id, seed: r.seed, W: r.W, H: r.H, speed: r.speed, chapter: r.chapter, goal: r.goal, armed: r.armed, ship: r.ship }); }
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 = game.events(me, String(body.runId || ''), body.t, body.events, !!body.goal); if (r.cleared) { r.pool = ledger.pool().available; if (r.cleared.first && !me.guest) announceChapter(me, r.cleared.chapter, r.cleared.pol); const so = await starter.offerFor(me); if (so) r.starterOffer = so; } return json(res, r.error ? 400 : 200, r); }
if (p === '/api/run/end' && req.method === 'POST') { const { body } = await readBody(req); return json(res, 200, game.end(me, String(body.runId || ''))); }
// refuel: hand the player to IAP for a verified visit; the run resumes when IAP confirms
if (p === '/api/refuel/start' && req.method === 'POST') {
+2 -1
View File
@@ -31,7 +31,7 @@ const sleep = ms => new Promise(r => setTimeout(r, ms));
const spawnLib = require('../lib/spawn');
(async () => {
await sleep(1200);
for (let i = 0; i < 60; i++) { try { await fetch(B + '/health'); break; } catch (e) { await sleep(250); } }
process.env.DR_SSO_SECRET = SECRET; const sso = require('../lib/sso');
const h = await call('/health'); eq([h.body.sso, h.body.faucet, h.body.signups], [true, false, 'testers'], 'posture: sso on, faucet off, testers mode');
@@ -81,6 +81,7 @@ const spawnLib = require('../lib/spawn');
// a replay of chapter 1 pays nothing; the hangar sink works; the sweep makes a payout row
const r2 = (await post('/api/run/start', { W, H })).body; eq(r2.chapter, 3, 'a new run starts on chapter 3 (progress kept)');
await post('/api/run/end', { runId: r2.runId });
const perkBuy = await post('/api/hangar/buy', { item: 'ship' }); eq([perkBuy.status, perkBuy.body.free], [200, true], 'the member perk (one free upgrade, 2026-10-05) pays for the first purchase'); // test/starter.js covers it in full
const buyNo = await post('/api/hangar/buy', { item: 'shield' }); eq(buyNo.status, 400, 'shield (0.05 POL) refused on a 0.01 balance');
await admin('/api/admin/settings', { itemPol: { slow: 0.005 } });
const buy = await post('/api/hangar/buy', { item: 'slow' }); eq([buy.status, buy.body.paid, buy.body.balance.unpaid], [200, '0.005 POL', 0.005], 'slow field bought from the POL balance');
+107
View File
@@ -0,0 +1,107 @@
// Member welcome offer + member perk (2026-10-05), on a local boot against a stub of InstantAdPay's public offer endpoint.
// Temp DATA_DIR, no faucet, no outbound. Checks: a signed-in non-member's clear carries the offer once a Central day; a
// guest and a member never see it; a member's hand-off grants one free hangar upgrade once per account; the free upgrade
// pays for exactly one purchase; the offer is skipped while InstantAdPay says off; bonus is null when the endpoint fails.
'use strict';
const { spawn } = require('child_process');
const http = require('http');
const path = require('path');
const fs = require('fs');
const PORT = 8899, STUB = 8897, DIR = path.join(__dirname, '..', 'data-test-starter');
fs.rmSync(DIR, { recursive: true, force: true });
const SECRET = 'z'.repeat(48);
let stubHits = 0, stubOn = true;
const stub = http.createServer((req, res) => {
if (req.url === '/api/starter/public') { stubHits++; res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ on: stubOn, bonus: 100, games: { driprunner: { name: 'Drip Runner', perk: 'a free hangar upgrade' } } })); }
res.writeHead(404); res.end('{}');
}).listen(STUB);
const IAPS = 'http://127.0.0.1:' + STUB;
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DIR, DR_SSO_SECRET: SECRET, ADMIN_KEY: 'adminkey123', SITE_URL: 'http://127.0.0.1:' + PORT, IAP_URL: IAPS });
delete env.CURTAIN; delete env.OUTBOUND; delete env.DR_WALLET_KEY; delete env.DR_RPC; delete env.DR_SIGNUPS; delete env.NODE_ENV;
const child = spawn(process.execPath, [path.join(__dirname, '..', 'server.js')], { env, stdio: ['ignore', 'pipe', 'pipe'] });
let serverErr = ''; child.stderr.on('data', d => { serverErr += d; process.stderr.write(d); });
let fails = 0;
const eq = (a, b, m) => { const ok = JSON.stringify(a) === JSON.stringify(b); console.log((ok ? ' ok ' : ' FAIL ') + m + (ok ? '' : ' -> got ' + JSON.stringify(a) + ' want ' + JSON.stringify(b))); if (!ok) fails++; };
const B = 'http://127.0.0.1:' + PORT;
const sleep = ms => new Promise(r => setTimeout(r, ms));
const spawnLib = require('../lib/spawn');
const hit = async (p, opt = {}, ck = '') => { const r = await fetch(B + p, Object.assign({ redirect: 'manual' }, opt, { headers: Object.assign({ Cookie: ck, 'Content-Type': 'application/json' }, opt.headers || {}) })); const set = r.headers.getSetCookie ? r.headers.getSetCookie() : []; let body = null; try { body = await r.json(); } catch (e) {} return { status: r.status, body, set, loc: r.headers.get('location') }; };
const jarAdd = (ck, set) => { const parts = ck ? ck.split('; ') : []; for (const c of set) { const m = /^([^=]+)=([^;]*)/.exec(c); if (!m) continue; const i = parts.findIndex(x => x.startsWith(m[1] + '=')); if (i >= 0) parts.splice(i, 1); if (m[2]) parts.push(m[1] + '=' + m[2]); } return parts.join('; '); };
const post = (p, b, ck) => hit(p, { method: 'POST', body: JSON.stringify(b || {}) }, ck);
const admin = (p, b) => hit(p, Object.assign({ headers: { 'X-Admin-Key': 'adminkey123' } }, b ? { method: 'POST', body: JSON.stringify(b) } : {}));
const players = () => JSON.parse(fs.readFileSync(path.join(DIR, 'players.json'), 'utf8'));
const W = 390, H = 760;
// play one run to the next chapter clear (claims timed to the schedule, start backdated so the wall check passes)
async function clearOne(ck) {
const r = (await post('/api/run/start', { W, H }, ck)).body; const gen = spawnLib.drips(r.seed, W, H); const cl = []; let T = 0;
while (cl.length < r.goal) { const g = gen(); for (const d of g.drips) if (cl.length < r.goal) { T = spawnLib.arrival(g.t, d.x0, W, r.speed) + 0.1; cl.push({ k: 'd', i: d.i, t: Math.round(T * 1000) / 1000 }); } }
const runs = JSON.parse(fs.readFileSync(path.join(DIR, 'runs.json'), 'utf8')); runs[r.runId].startedAt = Date.now() - (T + 5) * 1000; fs.writeFileSync(path.join(DIR, 'runs.json'), JSON.stringify(runs));
const ev = (await post('/api/run/events', { runId: r.runId, t: T + 0.2, events: cl, goal: true }, ck)).body;
await post('/api/run/end', { runId: r.runId }, ck);
return ev;
}
async function signIn(claims, ck) { const a = await hit('/auth?t=' + sso.mint(claims), {}, ck || ''); return { ck: jarAdd(ck || '', a.set), a }; }
let sso;
(async () => {
for (let i = 0; i < 60; i++) { try { await fetch(B + '/health'); break; } catch (e) { await sleep(250); } }
process.env.DR_SSO_SECRET = SECRET; sso = require('../lib/sso');
await admin('/api/admin/settings', { signups: 'open' });
// ---- non-member (InstantAdPay memberId 0): the offer after a win, once a Central day ----
let { ck: nm, a } = await signIn({ memberId: 0, email: 'nonmember@example.com', wallet: null, username: 'nonmem' });
eq(a.loc, '/play', 'a non-member signs in');
const nmMe = (await hit('/api/me', {}, nm)).body; eq([nmMe.me.memberId < 0, nmMe.perk, nmMe.player.freeUpgrades], [true, null, 0], 'non-member: temporary id, no perk, no free upgrade');
const c1 = await clearOne(nm);
eq([c1.cleared && c1.cleared.chapter, c1.starterOffer], [1, { bonus: 100, perk: 'a free hangar upgrade', url: IAPS + '/my?from=driprunner#buy' }], 'first clear of the day carries starterOffer {bonus 100, perk, url}');
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
eq(players()[String(nmMe.me.memberId)].starterShown, today, 'shown today is recorded on the player (Central day key ' + today + ')');
const c2 = await clearOne(nm); eq([c2.cleared && c2.cleared.chapter, c2.starterOffer === undefined], [2, true], 'second clear the same day: no offer');
const runEnd = await post('/api/run/start', { W, H }, nm); const crash = (await post('/api/run/events', { runId: runEnd.body.runId, t: 1, events: [] }, nm)).body; eq(crash.starterOffer === undefined, true, 'a sync without a clear never carries the offer');
await post('/api/run/end', { runId: runEnd.body.runId }, nm);
// tomorrow (Central): move the recorded day back
const ps = players(); ps[String(nmMe.me.memberId)].starterShown = '2000-01-01'; fs.writeFileSync(path.join(DIR, 'players.json'), JSON.stringify(ps));
const c3 = await clearOne(nm); eq([c3.cleared && c3.cleared.chapter, !!c3.starterOffer], [3, true], 'next Central day: the offer shows again, once');
eq(stubHits, 1, 'the public endpoint was fetched once (10-minute cache)');
// ---- a guest never sees it ----
await admin('/api/admin/settings', {}); let g = '';
const gs = await post('/api/guest', {}, g); g = jarAdd(g, gs.set); const gc = await clearOne(g);
eq([gc.cleared && gc.cleared.reason, gc.starterOffer === undefined], ['guest', true], 'a guest clear: no offer');
// ---- member: the perk, once per account ----
let { ck: mb } = await signIn({ memberId: 55, email: 'member@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'member55' });
const p55 = players()['55']; eq([p55.freeUpgrades, typeof p55.perkAt, p55.perkNotice], [1, 'number', true], 'member hand-off grants one free upgrade, perkAt timestamp set');
const m1 = (await hit('/api/me', {}, mb)).body; eq([m1.perk, m1.player.freeUpgrades], ['Member perk: a free hangar upgrade. Thanks for joining InstantAdPay!', 1], '/api/me carries the one-time perk message');
const m2 = (await hit('/api/me', {}, mb)).body; eq(m2.perk, null, 'the message shows once (next load has none)');
const perkAt1 = players()['55'].perkAt;
({ ck: mb } = await signIn({ memberId: 55, email: 'member@example.com', wallet: '0x' + 'ab'.repeat(20), username: 'member55' }, mb));
eq([players()['55'].freeUpgrades, players()['55'].perkAt, (await hit('/api/me', {}, mb)).body.perk], [1, perkAt1, null], 'signing in again grants nothing more');
const mc = await clearOne(mb); eq([mc.cleared && mc.cleared.chapter, mc.starterOffer === undefined], [1, true], 'a member clear: no offer');
const bank0 = players()['55'].bank;
const buy1 = await post('/api/hangar/buy', { item: 'ship' }, mb); // 600 drips, they have ~20
eq([buy1.status, buy1.body.free, buy1.body.player.items.ship, buy1.body.player.freeUpgrades, buy1.body.player.bank], [200, true, true, 0, bank0], 'the free upgrade buys the Courier Mk II (600 drips) for nothing, token used');
const buy2 = await post('/api/hangar/buy', { item: 'magnet' }, mb); eq(buy2.status, 400, 'the next purchase costs again (magnet refused on ~20 drips)');
const st = (await admin('/api/admin/state')).body; eq([st.pool.spends, st.spends.length], [0, 0], 'the free upgrade moved no POL (pool spends 0, no spend rows)');
// ---- a free POL item ----
({ ck: nm } = await signIn({ memberId: 91, email: 'nonmember@example.com', wallet: '0x' + 'cd'.repeat(20), username: 'nonmem' }, nm)); // the non-member buys and comes back as #91
const p91 = players()['91']; eq([p91 && p91.chapter, p91 && p91.freeUpgrades, !!(p91 && p91.perkAt)], [4, 1, true], 'non-member turned member: progress moved to #91 and the perk is granted');
const sh = await post('/api/hangar/buy', { item: 'shield' }, nm); eq([sh.status, sh.body.free, sh.body.balance.unpaid, sh.body.player.items.shield], [200, true, 0, true], 'free upgrade on a POL item (shield) with a 0 balance: armed, no POL taken');
const nc = await clearOne(nm); eq(nc.starterOffer === undefined, true, 'once a member, no more offers');
// ---- in process: InstantAdPay says off; the endpoint is down ----
process.env.DATA_DIR = DIR; const store = require('../lib/store'); store.init(DIR);
const game = require('../lib/game');
game.updPlayer(-123, x => { x.email = 'x@example.com'; });
stubOn = false; process.env.IAP_URL = IAPS; delete require.cache[require.resolve('../lib/starter')]; let starter = require('../lib/starter');
eq(await starter.offerFor({ memberId: -123 }), null, 'offer skipped while InstantAdPay reports on:false');
eq(game.player(-123).starterShown, undefined, '...and not recorded as shown');
process.env.IAP_URL = 'http://127.0.0.1:1'; delete require.cache[require.resolve('../lib/starter')]; starter = require('../lib/starter');
const down = await starter.offerFor({ memberId: -123 }); eq([down && down.bonus, down && down.perk], [null, 'a free hangar upgrade'], 'endpoint down: offer still shows, bonus null');
eq(/Error|TypeError/.test(serverErr), false, 'no server errors logged');
console.log(fails ? '\n' + fails + ' FAILED' : '\nall good');
child.kill(); stub.close(); fs.rmSync(DIR, { recursive: true, force: true }); process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); child.kill(); stub.close(); process.exit(1); });