Spooky Doors (Halloween season game): hand-off, door visits, costume shop, seasonal Games card

- SD_SSO_SECRET / SD_URL (default https://spookydoors.com); sdMint/sdOpen same token shape as Drip Runner
- GET /api/my/spookydoors sign-in hand-off (?ref pass-through; iap.return spookydoors + sdshop whitelisted)
- /door page (Halloween copy of /refuel, door art backdrop) + /api/door/open|challenge|done as visit kind 'door';
  signed callback to SD_URL/api/door/callback (X-SD-Ts/X-SD-Sig) + 24 h door-receipt on ret&ok=1&r=;
  ret&none=1 when nothing to serve, ret&cap=1 at the daily cap; host = campaign owner's username
- /sd/shop (+ topup/resume/confirm) costume checkout via ads.gamePurchase('Spooky Doors: <label>'), sd-receipt
- Games tab: generic season window (Central days, admin preview before start, hidden after end) + pink
  limited-time ribbon; progress from SD_URL/api/partner/player (signed); my.js ?v bumped
- Chatbot canned answer + prompt facts; qa/door.mjs (bash qa/run.sh door) end-to-end on a throwaway local copy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-02 09:40:08 -05:00
parent b6850d4342
commit 27c9d51fde
9 changed files with 534 additions and 7 deletions
+205 -4
View File
@@ -1286,9 +1286,62 @@ async function gkCallback(cbUrl, receipt) {
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('gemkingdom callback', e.message); return false; }
}
// -- Spooky Doors (2026-10-02, the Halloween season game): sign-in hand-off, door visits and the costume shop. Same token
// shape as Drip Runner and Gem Kingdom under its own secret SD_SSO_SECRET (also set on the game, at least 32 characters).
// A door is a verified visit of its own kind ('door', own daily cap doorCapPerDay, never touching refuel or Earn counts).
// The game hears about it twice: a signed server-to-server callback AND a signed receipt on the redirect back, whichever
// lands first. Costumes are bought with ad credits through ads.gamePurchase, exactly like Gem Kingdom Crowns.
const SD_SECRET = () => String(process.env.SD_SSO_SECRET || '').trim();
const SD_URL = () => String(process.env.SD_URL || 'https://spookydoors.com').replace(/\/+$/, '');
const SD_SEASON = { start: '2026-10-17', end: '2026-11-01' }; // Central days, end exclusive (through Halloween night)
const sdSign = p => drB64u(crypto.createHmac('sha256', SD_SECRET()).update(p).digest());
function sdMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + sdSign(payload); }
function sdOpen(token, expiredMsg) {
if (SD_SECRET().length < 32) return { error: 'Spooky Doors is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = sdSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: expiredMsg || 'That link has expired. Go back to Spooky Doors and try again.' };
return { ok: true, claims: c };
}
const doorTokens = persistedMap('door'); // nonce -> { kind, email, memberId, id, title, target|videoUrl, host, ts, ret, challenge, done, doneRet }
const sdOrders = persistedMap('sdorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts }
const sdIsGameUrl = x => String(x || '').startsWith(SD_URL() + '/');
const sdJoin = (ret, q) => ret + (String(ret).includes('?') ? '&' : '?') + q; // ret is SD_URL/play?door=<nonce>, so this appends &...
async function sdCallback(body) { // door done: POST {nonce, memberId, campaignId, credits, host}, X-SD-Sig = hex HMAC(secret, ts + "\n" + rawBody)
const raw = JSON.stringify(body); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', SD_SECRET()).update(ts + '\n' + raw).digest('hex');
try { const r = await fetch(SD_URL() + '/api/door/callback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SD-Ts': ts, 'X-SD-Sig': sig }, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; }
catch (e) { console.warn('spookydoors callback', e.message); return false; }
}
async function sdShopCallback(cbUrl, receipt) {
if (!sdIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('spookydoors shop callback', e.message); return false; }
}
// the visited campaign owner's public username ("+12 candy from @host"); null for house ads or members without one
async function sdHost(campaignId) {
try { const c = await ads.campaignById(campaignId); if (!c || !c.owner) return null; const a = await accounts.byEmail(String(c.owner).toLowerCase()); return (a && a.username) || null; } catch (e) { return null; }
}
function sdPage(res, code, title, inner) {
res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }));
res.end('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>' + gkEsc(title) + ' | InstantAdPay</title>'
+ '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Creepster&family=Fredoka:wght@400;600;700&display=swap">'
+ '<style>body{margin:0;background:#140B24 linear-gradient(rgba(20,11,36,.72),rgba(20,11,36,.92)),url(/assets/door-open.jpg?v=20261002) center/cover fixed;color:#F4F1FF;font:16px/1.5 Fredoka,"Trebuchet MS",system-ui,sans-serif;min-height:100vh;display:grid;place-items:center;padding:24px 16px;box-sizing:border-box}'
+ '.card{width:100%;max-width:440px;background:rgba(36,19,57,.95);border:1px solid #4A3270;border-radius:18px;box-shadow:0 16px 40px rgba(0,0,0,.55);padding:26px 22px;text-align:center;box-sizing:border-box}'
+ 'h1{font:400 40px/1.05 Creepster,Chiller,fantasy;color:#FF8A1F;text-shadow:0 3px 0 #5a1f00;margin:0 0 8px;letter-spacing:.02em}.sub{color:#5FE0D2;font-weight:600;font-size:13px;letter-spacing:.12em;text-transform:uppercase;margin:0 0 12px}.big{font:400 40px/1 Creepster,Chiller,fantasy;color:#FF5FA2;margin:8px 0 14px}'
+ '.row{display:flex;justify-content:space-between;gap:12px;padding:8px 0;border-bottom:1px solid rgba(185,169,214,.25);font-weight:600}.row span:first-child{color:#B9A9D6}'
+ '.btn{display:block;width:100%;box-sizing:border-box;margin-top:16px;padding:13px;border:0;border-radius:14px;background:#FF8A1F;color:#2a1200;font:700 17px Fredoka,system-ui,sans-serif;text-decoration:none;cursor:pointer;box-shadow:0 5px 0 #C25A06}'
+ '.btn.blue{background:transparent;color:#F4F1FF;box-shadow:inset 0 0 0 2px #4A3270}.alt{display:inline-block;margin-top:14px;color:#B9A9D6;font-weight:600}.warn{color:#FF5FA2;font-weight:700}.fine{font-size:13px;color:#B9A9D6;margin-top:14px}</style></head>'
+ '<body><main class="card">' + inner + '</main></body></html>');
}
// -- the games registry (2026-10-01). Add a game here; launch it by adding its slug to site config gamesLive.
function GAMES() {
return [
{ slug: 'spookydoors', name: 'Spooky Doors', tag: 'Halloween \u00b7 Oct 17 to 31', blurb: 'Trick or treat! Walk the street, knock on doors and fill your candy bucket. Every door is a short visit to a member\u2019s page or ad, and candy climbs a ladder with POL at set levels. Gone after Halloween night.',
art: SD_URL() + '/og-spookydoors.jpg', play: '/api/my/spookydoors', pays: 'POL at set candy levels', season: { start: SD_SEASON.start, end: SD_SEASON.end }, progress: sdProgress },
{ slug: 'driprunner', name: 'Drip Runner', tag: 'Arcade runner', blurb: 'Hop the network, dodge the bots, clear chapters. Each first clear drips POL into your game balance, and a refuel on a member\u2019s page keeps your run alive.',
art: DR_URL() + '/og-driprunner.jpg?v=20261002', artPos: 'left', play: '/api/my/driprunner', pays: 'POL to your wallet at 0.25', progress: drProgress },
{ slug: 'gemkingdom', name: 'Gem Kingdom', tag: 'Fantasy match-3', blurb: 'Match gems to battle monsters with three heroes, earn stars and rebuild your village. Crowns for instant upgrades come from your ad credits.',
@@ -1318,6 +1371,16 @@ async function drProgress(memberId) {
return { line: 'Chapter ' + j.chapter + ' \u00b7 ' + Number(j.unpaid).toFixed(3) + ' POL in your game balance' + (j.paidTotal ? ' \u00b7 ' + Number(j.paidTotal).toFixed(3) + ' POL paid out' : '') };
}
// the player's own line on the Spooky Doors card, read from the game with a signed request (same scheme as Drip Runner)
async function sdProgress(memberId) {
if (SD_SECRET().length < 32) return null;
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SD_SECRET()).update('player:' + memberId + ':' + ts).digest('hex');
const r = await fetch(SD_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) });
if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' };
const cap = ads.rates().doorCapPerDay || 15;
return { line: Number(j.candy || 0).toLocaleString('en-US') + ' candy \u00b7 ' + Number(j.doorsToday || 0) + ' of ' + cap + ' doors today' + (Number(j.polEarned) ? ' \u00b7 ' + Number(j.polEarned).toFixed(2) + ' POL earned' : '') };
}
const server = http.createServer(async (req, res) => {
try {
const u = new URL(req.url, 'http://x');
@@ -1688,7 +1751,7 @@ const server = http.createServer(async (req, res) => {
let memberId = 0;
if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} }
const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId });
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
}
// -- wallet auth: link-to-account when an email session exists, or
@@ -1767,7 +1830,7 @@ const server = http.createServer(async (req, res) => {
const _defSpon = Number(siteConfig().defaultSponsorId) || 1;
if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor)
if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {});
const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : null, sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : null, sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
address: s.address || (acct && acct.address) || null, memberId,
username: (acct && acct.username) || null,
refCode: (acct && acct.code) || null, sponsorId,
@@ -2575,6 +2638,78 @@ const server = http.createServer(async (req, res) => {
res.setHeader('Set-Cookie', gkCookie('iap.gkshop', '', 0));
return gkPage(res, 200, 'Crowns added', '<meta http-equiv="refresh" content="1;url=' + back + '"><p class="sub">Gem Kingdom · Crown Shop</p><h1>Paid!</h1><div class="big">+' + Number(c.crowns).toLocaleString('en-US') + ' Crowns</div><p class="sub">Taking you back to your kingdom...</p><a class="btn" href="' + back + '">Back to Gem Kingdom</a>');
}
// -- Spooky Doors hand-off (2026-10-02): sign the member across; the game verifies with SD_SSO_SECRET
if (p === '/api/my/spookydoors' && req.method === 'GET') {
const s = await auth.fromRequest(req);
// a newcomer from a Spooky Doors post carries the poster's ?ref through to /my, where the viral-link rule sets the sponsor
const sdRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (sdRef ? '?ref=' + encodeURIComponent(sdRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'spookydoors', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (SD_SECRET().length < 32) return json(res, 503, { error: 'Spooky Doors is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = sdMint({ kind: 'sso', memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || s.address || null,
sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }, 5 * 60000);
res.writeHead(302, { Location: SD_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- the Spooky Doors costume shop checkout: the Crown shop flow with a Halloween coat (confirm, spend, signed receipt back)
if (p === '/sd/shop' && req.method === 'GET') {
const t = u.searchParams.get('t') || ''; const r = sdOpen(t, 'That order has expired. Go back to Spooky Doors and open the costume shop again.');
if (r.error) return sdPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="warn">' + gkEsc(r.error) + '</p><a class="btn blue" href="' + SD_URL() + '/play?open=shop">Back to Spooky Doors</a>');
const c = r.claims; if (c.kind !== 'sd-buy' || !c.order || !c.item || !(Number(c.credits) > 0) || !c.email) return sdPage(res, 400, 'Order problem', '<h1>That is not a costume order</h1><a class="btn blue" href="' + SD_URL() + '/play?open=shop">Back to Spooky Doors</a>');
const label = String(c.label || c.item).slice(0, 60);
const done = sdOrders.get(c.order);
if (done && done.status === 'paid') { const rc = sdMint({ kind: 'sd-receipt', order: c.order, email: String(c.email).toLowerCase(), item: String(c.item), credits: Number(c.credits), ref: done.campaignId }, 24 * 3600000); const ret = sdIsGameUrl(c.ret) ? c.ret : SD_URL() + '/api/iap/receipt'; res.writeHead(302, { Location: ret + '?t=' + rc, 'Cache-Control': 'no-store' }); return res.end(); }
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.sdshop', t, 7200), gkCookie('iap.return', 'sdshop', 1800)] }); return res.end(); }
if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return sdPage(res, 403, 'Different account', '<h1>Different account</h1><p>This order was started by the Spooky Doors player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account in both places.</p><a class="btn blue" href="' + SD_URL() + '/play">Back to Spooky Doors</a>');
const { ids } = await myMemberIds(s); const bal = await ads.balances(ids, s.email);
const free = (bal.earned || 0) + (bal.credited || 0); const best = (bal.per || []).slice().sort((a, b) => b.avail - a.avail)[0] || { avail: 0 };
const can = free >= c.credits || best.avail >= c.credits; const usable = Math.max(free, best.avail);
const dollars = '$' + (c.credits / 100).toFixed(c.credits % 100 ? 2 : 0);
const head = '<p class="sub">Spooky Doors &middot; Costume shop</p><h1>' + gkEsc(label) + '</h1>'
+ '<div class="row"><span>Price</span><span>' + Number(c.credits).toLocaleString('en-US') + ' ad credits (' + dollars + ')</span></div>'
+ '<div class="row"><span>Your available credits</span><span>' + Number(bal.available || 0).toLocaleString('en-US') + '</span></div>';
if (can) {
const csrf = sdSign('csrf:' + c.order + ':' + String(s.email).toLowerCase());
return sdPage(res, 200, 'Confirm your costume', head + '<form method="post" action="/sd/shop/confirm"><input type="hidden" name="t" value="' + gkEsc(t) + '"><input type="hidden" name="csrf" value="' + csrf + '"><button class="btn" type="submit">Spend ' + Number(c.credits).toLocaleString('en-US') + ' credits</button></form>'
+ '<a class="alt" href="' + SD_URL() + '/play?open=shop">Cancel and go back</a><p class="fine">Costumes are game items for this Halloween season. They have no cash value and cannot be withdrawn. The credits come off your ad balance and show in your Credit activity.</p>');
}
const need = c.credits - usable;
return sdPage(res, 200, 'More credits needed', head + '<p class="warn">You need ' + need.toLocaleString('en-US') + ' more credits for this costume' + (bal.available >= c.credits ? ' (some of your credits are already budgeted to live campaigns or spread across positions)' : '') + '.</p>'
+ '<a class="btn" href="/sd/shop/topup?t=' + encodeURIComponent(t) + '">Buy a credit package</a><a class="btn blue" href="' + SD_URL() + '/play?open=shop">Back to the costume shop</a>'
+ '<p class="fine">A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.</p>');
}
if (p === '/sd/shop/topup' && req.method === 'GET') { // the detour to Buy packages, remembered for the way back
const t = u.searchParams.get('t') || ''; if (sdOpen(t).error) { res.writeHead(302, { Location: '/my#buy' }); return res.end(); }
res.writeHead(302, { Location: '/my#buy', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.sdshop', t, 7200) }); return res.end();
}
if (p === '/sd/shop/resume' && req.method === 'GET') {
const t = parseCookies(req)['iap.sdshop']; res.writeHead(302, { Location: t ? '/sd/shop?t=' + encodeURIComponent(t) : SD_URL() + '/play?open=shop', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
if (p === '/sd/shop/confirm' && req.method === 'POST') {
const f = await gkFormBody(req); const t = f.get('t') || ''; const r = sdOpen(t, 'That order has expired. Go back to Spooky Doors and open the costume shop again.');
if (r.error) return sdPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="warn">' + gkEsc(r.error) + '</p>');
const c = r.claims; if (c.kind !== 'sd-buy' || !c.order || !c.item || !(Number(c.credits) > 0)) return sdPage(res, 400, 'Order problem', '<h1>That is not a costume order</h1>');
const s = await auth.fromRequest(req);
if (!s || !s.email || String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return sdPage(res, 403, 'Sign in', '<h1>Please sign in again</h1><a class="btn blue" href="/sd/shop?t=' + encodeURIComponent(t) + '">Continue</a>');
const want = sdSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); const got = String(f.get('csrf') || '');
if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return sdPage(res, 403, 'Order problem', '<h1>That form expired</h1><a class="btn blue" href="/sd/shop?t=' + encodeURIComponent(t) + '">Try again</a>');
const prev = sdOrders.get(c.order);
if (prev && (prev.status === 'paid' || (prev.status === 'paying' && Date.now() - prev.ts < 60000))) { res.writeHead(302, { Location: '/sd/shop?t=' + encodeURIComponent(t) }); return res.end(); }
sdOrders.set(c.order, { status: 'paying', email: s.email, ts: Date.now() });
const label = String(c.label || c.item).slice(0, 60);
const { ids } = await myMemberIds(s);
const out = await ads.gamePurchase(s.email, ids, Number(c.credits), 'Spooky Doors: ' + label, SD_URL());
if (out.error) { sdOrders.delete(c.order); if (out.error === 'short') { res.writeHead(302, { Location: '/sd/shop?t=' + encodeURIComponent(t) }); return res.end(); } return sdPage(res, 500, 'Order problem', '<h1>Something went wrong</h1><p class="warn">' + gkEsc(out.error) + '</p>'); }
sdOrders.set(c.order, { status: 'paid', email: s.email, campaignId: out.campaignId, ts: Date.now() });
console.log('spookydoors costume', s.email, c.item, 'for', c.credits, 'credits, campaign', out.campaignId);
const rc = sdMint({ kind: 'sd-receipt', order: c.order, email: String(c.email).toLowerCase(), item: String(c.item), credits: Number(c.credits), ref: out.campaignId }, 24 * 3600000);
sdShopCallback(c.cb, rc); // the server copy; the redirect below is the fast path
const ret = sdIsGameUrl(c.ret) ? c.ret : SD_URL() + '/api/iap/receipt';
// a 200 page, not a 302: CSP form-action 'self' blocks a form POST from redirecting to another site
const back = gkEsc(ret + '?t=' + rc);
res.setHeader('Set-Cookie', gkCookie('iap.sdshop', '', 0));
return sdPage(res, 200, 'Costume ready', '<meta http-equiv="refresh" content="1;url=' + back + '"><p class="sub">Spooky Doors &middot; Costume shop</p><h1>Paid!</h1><div class="big">' + gkEsc(label) + '</div><p>Taking you back to the street...</p><a class="btn" href="' + back + '">Back to Spooky Doors</a>');
}
// -- PassiveDrip card on the Earn tab (Marty, 2026-10-01: "It's an earning site", not a game). Members see it when
// site config passivedripLive is 'on'; until then only the admin sees it, marked preview.
if (p === '/api/my/passivedrip/card' && req.method === 'GET') {
@@ -2654,6 +2789,66 @@ const server = http.createServer(async (req, res) => {
t.doneRet = t.ret + '&ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet });
}
// -- Spooky Doors door: a real verified visit of kind 'door' (own daily cap, advertiser charged as usual); the player gets candy, not credits
if (p === '/api/door/open' && req.method === 'GET') {
const r = sdOpen(u.searchParams.get('t'), 'That door link has expired. Go back to Spooky Doors and knock again.'); if (r.error) return json(res, 400, { error: r.error });
const c = r.claims; if (c.kind !== 'door' || !c.nonce || !c.email || !sdIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a door link.' });
for (const [n, v] of doorTokens) if (v.ts + 30 * 60000 < Date.now()) doorTokens.delete(n);
let t = doorTokens.get(c.nonce);
if (t && t.done) return json(res, 200, { done: true, ret: t.doneRet || t.ret });
const email = String(c.email).toLowerCase();
const status = await ads.visitStatus(email, 'door'); // doors have their own daily allowance
if (!t) {
if (status.count >= status.cap) return json(res, 200, { none: true, why: 'cap', ret: sdJoin(c.ret, 'cap=1') });
const ad = await ads.serveVisit(email, viewerGeo(req));
if (ad) t = { kind: 'visit', email, memberId: Number(c.memberId) || 0, id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false };
else { // every visit pack already visited: a member video ad instead, one door per video per person
const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req)));
if (!v) return json(res, 200, { none: true, why: 'empty', ret: sdJoin(c.ret, 'none=1') });
t = { kind: 'video', email, memberId: Number(c.memberId) || 0, id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false };
}
t.host = await sdHost(t.id);
doorTokens.set(c.nonce, t);
}
const doors = { used: status.count, cap: status.cap };
if (t.kind === 'video') return json(res, 200, { mode: 'video', title: t.title, host: t.host || null, doors, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) });
return json(res, 200, { mode: 'visit', title: t.title, host: t.host || null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) });
}
if (p === '/api/door/challenge' && req.method === 'GET') {
const n = String(u.searchParams.get('n') || ''); const t = doorTokens.get(n);
if (!t || t.done) return json(res, 400, { error: 'That door is no longer open.' });
const dwellMs = (t.kind === 'video' ? t.secs : (ads.rates().visitDwellSeconds || 8)) * 1000; const age = Date.now() - t.ts;
if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) });
const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); const answer = Math.floor(Math.random() * pick.length);
t.challenge = { answer }; doorTokens.set(n, t);
return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) });
}
if (p === '/api/door/done' && req.method === 'POST') {
const b = await readBody(req); const nonce = String(b.n || ''); const t = doorTokens.get(nonce);
if (!t || t.done) return json(res, 400, { error: 'That door is no longer open.' });
if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true });
if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; doorTokens.set(nonce, t); return json(res, 400, { error: 'Wrong pick.', retry: true }); }
const st = await ads.visitStatus(t.email, 'door');
if (st.count >= st.cap) return json(res, 400, { error: 'That is today\u2019s doors. More at midnight Central.', cap: true, ret: sdJoin(t.ret, 'cap=1') });
let credits;
if (t.kind === 'video') {
if (!(await ads.markRefuelVideo(t.email, t.id, 'door'))) return json(res, 400, { error: 'You already knocked on this video. Go back and try another door.' });
const tier = await ads.chargeVideoView(t.id); // the advertiser is charged one view, as on the Watch tab
if (!tier) return json(res, 400, { error: 'That video just ran out of budget. Go back and try another door.' });
await ads.markVideoSeen(t.email, t.id); credits = tier.cost;
} else {
const r = await ads.completeVisit(t.email, t.id, { reward: false, kind: 'door', note: 'Spooky Doors door' });
if (r.error) return json(res, 400, r);
credits = ads.rates().visitCostPerVisit || 3;
}
t.done = true;
const host = t.host || null;
const posted = await sdCallback({ nonce, memberId: t.memberId, campaignId: t.id, credits, host });
const receipt = sdMint({ kind: 'door-receipt', nonce, memberId: t.memberId, campaignId: t.id, credits, host }, 24 * 3600000);
t.doneRet = sdJoin(t.ret, 'ok=1&r=' + encodeURIComponent(receipt));
doorTokens.set(nonce, t);
return json(res, 200, { ok: true, posted, host, ret: t.doneRet });
}
// -- Games hub (2026-10-01): the registry is here, the live list is site config (gamesLive)
if (p === '/api/my/games' && req.method === 'GET') {
const s = await auth.fromRequest(req);
@@ -2661,10 +2856,15 @@ const server = http.createServer(async (req, res) => {
const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean));
const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL);
const acct = await accounts.byEmail(s.email); const memberId = (acct && acct.memberId) || s.memberId || 0;
const out = [];
const out = []; const day = todayCT();
const dayLabel = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); };
for (const g of GAMES()) {
// a seasonal game (2026-10-02) shows only while today (Central) is in [start, end); before start the admin sees a preview, after end nobody
let seasonPreview = false;
if (g.season) { if (day >= g.season.end) continue; if (day < g.season.start) { if (!admin) continue; seasonPreview = true; } }
const isLive = live.has(g.slug); if (!isLive && !admin) continue;
const card = Object.assign({}, g, { live: isLive, preview: !isLive });
const card = Object.assign({}, g, { live: isLive, preview: !isLive || seasonPreview });
if (g.season) { card.season = Object.assign({}, g.season, { opens: dayLabel(g.season.start), ends: dayLabel(g.season.end, true) }); if (seasonPreview) card.previewNote = 'preview, opens ' + card.season.opens; }
if (g.progress && (memberId || g.slug === 'passivedrip')) { try { card.progress = await g.progress(memberId, s.email); } catch (e) {} }
out.push(card);
}
@@ -3772,6 +3972,7 @@ const server = http.createServer(async (req, res) => {
if (p === '/friday') return sendFile(res, path.join(PUBLIC_DIR, 'friday.html'));
if (p === '/wednesday') return sendFile(res, path.join(PUBLIC_DIR, 'wednesday.html'));
if (p === '/refuel') return sendFile(res, path.join(PUBLIC_DIR, 'refuel.html')); // Drip Runner refuel visit (2026-09-30)
if (p === '/door') return sendFile(res, path.join(PUBLIC_DIR, 'door.html')); // Spooky Doors door visit (2026-10-02)
// per-partner kit pages (Marty, 2026-09-29): /partners/<slug> serves public/kits/<slug>.html, one file per reviewer or site owner
{ const mk = p.match(/^\/partners\/([a-z0-9-]{2,40})$/); if (mk) { const f = path.join(PUBLIC_DIR, 'kits', mk[1] + '.html'); if (fs.existsSync(f)) return sendFile(res, f); } }
if (p === '/plan-lab') return sendFile(res, path.join(PUBLIC_DIR, 'plan-lab.html')); // Reach Ladder simulator for Marty's planning group: unlisted, shared by link (2026-09-27)