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:
@@ -22,6 +22,8 @@ function enabled() { return !!key(); }
|
||||
// ---- canned answers: instant, free, always in voice ----
|
||||
const KNOWLEDGE_DATE = '2026-10-02'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const CANNED = [
|
||||
{ re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i,
|
||||
a: 'Spooky Doors (https://spookydoors.com) is the network\u2019s Halloween game. It opens on Oct 17 and closes at midnight Central at the end of Halloween night (Oct 31), and it shows in Members > Games only during the season; one tap signs you in with your InstantAdPay account. Walk the street, grab loose candy, hop the black cats and bats, and knock on doors. Every door is a short verified visit to a member\u2019s page or ad (a member video once you have visited them all), up to 15 doors a day, separate from your Earn visits and Drip Runner refuels. Most doors give a treat of 10 candy; about one door in five plays a trick, and beating it with quick taps adds a small bonus. Candy climbs a ladder that pays POL once per rung (100 candy 0.1 POL, 250 candy 0.25, 500 candy 0.5, 1,000 candy 1, 2,000 candy 2), from a season pool funded by a share of door ad spend and costume sales, so rungs pay only while the pool covers them. POL goes to the wallet on your InstantAdPay account once your game balance reaches 0.25 POL. The witch costume is free; the vampire (300 credits), bedsheet ghost (300) and Lucky caramel apple (500) are bought with your ad credits in the game\u2019s costume shop. Nothing here is a promise of income.' },
|
||||
{ re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|refuel)/i,
|
||||
a: 'Members > Games lists the network\u2019s games; one tap signs you in. Drip Runner is a runner game: tap to hop, collect gold drips, dodge the bots, clear chapters. The first clear of each chapter drips a little POL into your game balance, which is sent to your wallet once it reaches the payout line shown in the game. When a run ends you can refuel instead of restarting: a short verified visit to a member\u2019s page (or a member video when you have visited them all), up to 20 refuels a day, separate from your regular Earn visits. Refuels are paid for by advertisers, and a share of that funds the POL pool every drip is paid from, so drips depend on the pool and are small. Share your link from the game lobby: when people on your team refuel, a share of what their refuels add to the pool goes to your game balance. Nothing here is a promise of income. PolHunter and Gem Kingdom are on the same Games page; Gem Kingdom is a match-3 that pays POL for first clears of stages and bosses (its Crowns are bought with ad credits).' },
|
||||
{ re: /(gem ?kingdom|crowns?\b|match.?3|goblin king|ice queen|bog witch|ember dragon|stronghold)/i,
|
||||
@@ -169,6 +171,7 @@ FACTS:
|
||||
- Onsite SOLO ADS are live: a solo ad is a full message (subject + up to 2000 characters of formatted text + your link) delivered into members' on-site Inbox (Members > Inbox). The composer in Campaigns > Solo ad has a rich-text editor (bold, headings, lists, links), lets you ATTACH one image (PNG/JPG/WebP/GIF, up to 3MB) or one video (MP4/WebM, up to 25MB), and adds a call-to-action button with a custom label that opens the target URL. Cost 5 credits per guaranteed delivery, minimum 10 deliveries (50 credits). Each member receives a given solo at most once, and never the sender's own. Readers earn 2 credits per real read (10-second dwell on the open message, up to 5 rewarded reads/day) — claimed right from the message. Compose one in Campaigns > Solo ad.
|
||||
- Campaign target URLs are checked the moment they are submitted: the page must be reachable and must ALLOW framing (no X-Frame-Options deny/sameorigin, no blocking CSP frame-ancestors), because surf views show the real site full screen. Frame-blocking or dead URLs are rejected with the exact reason; the fix is a landing page that allows framing. Login-ad targets skip the frame check (they are click-through only).
|
||||
- SPONSOR CHAT (Members): a two-way, one-to-one chat. A member can start a conversation with their DIRECT sponsor; a sponsor can message anyone in their downline. Presence-aware — when both are online it is live, otherwise a message waits in the recipient's on-site inbox and sends an email. Each member has an availability toggle in Profile (default on; turning it off stops live chats but people can still leave a note) and can mute a specific person. This is separate from the once-a-day sponsor BROADCAST to the whole downline.
|
||||
- SPOOKY DOORS (Halloween season game, 2026-10-02): https://spookydoors.com, open 2026-10-17 through Halloween night (closes at midnight Central at the end of Oct 31); its Games tab card shows only during the season, with a "Limited time, ends Oct 31" ribbon. Members sign in with one tap from Members > Games. Walk the street, collect candy, avoid black cats and bats, knock on doors. Each door is a verified visit to a member's page or ad (a member video once every page has been visited), the advertiser is charged as for any visit, the player gets candy not credits; 15 doors per Central day, separate from the 20 Earn-tab visits and the 20 Drip Runner refuels. A treat is 10 candy; about 1 door in 5 is a trick (a ghost or skeleton you tap 5 times quickly; beat it for a 3 candy bonus, miss it for half the treat). If no ad is available the house is dark ("Nobody's home"): no candy and the door does not count. CANDY LADDER pays POL once per rung: 100 candy 0.1 POL, 250 0.25, 500 0.5, 1,000 1, 2,000 2 (Halloween 2026 badge at 500), paid from a season pool funded by a share of door ad spend and costume sales, only while the pool covers it; the game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. COSTUMES bought with ad credits like Gem Kingdom Crowns: witch free, vampire 300 credits (longer trick timer), bedsheet ghost 300 (black cats ignore you), Lucky caramel apple 500 (+2 candy per treat); no cash value. Top 20 by candy on the season leaderboard. Never promise earnings or call it income.
|
||||
- GEM KINGDOM (LIVE in the Games tab since 2026-10-02): Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon's Peak, the Sunken Reef, the Shadow Citadel), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for FIRST clears only (stages 0.02 to 0.15 POL rising by chapter; bosses 0.25, 0.5, 2, 5, 7.5 and 10 POL for the Goblin King, Ice Queen, Bog Witch, Ember Dragon, Kraken and Shadow King); replays pay nothing. The game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. Rewards come from a pool funded by a share of Crown purchases and pay only while the pool has funds; never promise earnings or call it income. No referral bonus on game clears. Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game's Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. Never promise an amount beyond the posted rewards.
|
||||
- GAMES TAB (2026-10-01): Members > Games (/my#games) shows one card per network game (PolHunter, Drip Runner and Gem Kingdom pay POL to the member's InstantAdPay wallet), with their own progress and a Play button that signs them in with one tap; new games appear there as they launch (PolHunter is one card). DRIP RUNNER (https://driprunner.app, LIVE for every member since 2026-10-01): tap-to-hop runner; gold drips, magenta bots, orange firewalls from chapter 2; each chapter has a drip goal for one run; the FIRST clear of a chapter pays a small POL drip (amount set by the admin, shown in the game) into the game balance, replays pay nothing; the balance is sent on Polygon to the member's InstantAdPay wallet once it reaches the payout line shown in the game. REFUELS: a run that ends can be refuelled with a verified visit to a member's page (a member video once every page has been visited), up to 20 a day, separate from the 20 Earn-tab visits; the advertiser is charged as for any visit, the player gets fuel not credits. The POL pool is funded ONLY by a share of refuel ad spend plus POL spent in the hangar, so drips depend on refuels and can be zero when the pool is empty; say so honestly. HANGAR: Drip Magnet and Courier Mk II cost drips (game currency); Shield Core and Slow Field cost POL from the game balance, which returns to the pool. GUESTS can try a run without signing in; their clears pay once they sign in. REFERRALS: each player's share link /r/<username>; when members whose InstantAdPay sponsor is that player refuel, a share (10 percent by default) of each refuel's pool income goes to the sponsor's game balance. Telegram posts achievement badges (chapters, unlocks, refuel milestones, payouts). Never promise amounts or income.
|
||||
- Every purchase is split by an immutable smart contract in the same transaction: 50% direct sponsor, 20% level 2, 10% level 3, 20% platform. No withdrawals exist; money lands in members' own wallets instantly.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
@@ -0,0 +1,73 @@
|
||||
/* Spooky Doors door: one verified visit (a member's page or ad), then back to the street with a signed receipt. */
|
||||
(function () {
|
||||
'use strict';
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
var q = new URLSearchParams(location.search); var tok = q.get('t') || '';
|
||||
var nonce = '', tokRet = ''; try { var claims = JSON.parse(atob(tok.split('.')[0].replace(/-/g, '+').replace(/_/g, '/'))); nonce = claims.nonce || ''; tokRet = claims.ret || ''; } catch (e) {}
|
||||
// every dead end on this page keeps a way back to the street
|
||||
var gameHome = tokRet ? tokRet.split('?')[0] : 'https://spookydoors.com/play';
|
||||
var dwell = 8, left = 8, timer = null;
|
||||
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); }
|
||||
function msg(title, text, backUrl, auto) {
|
||||
$('sdFrame').innerHTML = '<div class="dr-msg"><div class="in"><h1>' + esc(title) + '</h1><p>' + esc(text) + '</p></div></div>';
|
||||
$('sdDone').hidden = true; $('sdCheck').hidden = true; $('sdRow').hidden = true;
|
||||
var b = $('sdBack'); b.hidden = false; var to = backUrl || gameHome; b.textContent = 'Back to the street'; b.onclick = function () { location.href = to; };
|
||||
if (auto && backUrl) setTimeout(function () { location.href = backUrl; }, 2500);
|
||||
}
|
||||
function api(p, body) { return fetch(p, body ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } : {}).then(function (r) { return r.json(); }); }
|
||||
function ring() { $('sdN').textContent = left; $('sdRing').style.setProperty('--p', ((dwell - left) / dwell * 100) + '%'); }
|
||||
function tick() {
|
||||
if (document.hidden) return; // the timer only runs while the page is in front
|
||||
var vid = document.getElementById('sdVideo'); if (vid && (vid.paused || vid.ended && left > 1)) return; // a video must actually be playing
|
||||
left--; if (left > 0) return ring();
|
||||
clearInterval(timer); ring(); $('sdHint').textContent = 'One quick check to count the visit:';
|
||||
challenge();
|
||||
}
|
||||
function challenge() {
|
||||
api('/api/door/challenge?n=' + encodeURIComponent(nonce)).then(function (c) {
|
||||
if (c.early) { setTimeout(challenge, (c.wait || 1) * 1000 + 300); return; }
|
||||
if (c.error) { $('sdHint').textContent = c.error; return; }
|
||||
$('sdPrompt').textContent = 'Tap the ' + c.prompt + ':'; var w = $('sdOpts'); w.innerHTML = '';
|
||||
c.options.forEach(function (em, i) { var b = document.createElement('button'); b.type = 'button'; b.textContent = em; b.setAttribute('aria-label', 'Option ' + (i + 1)); b.addEventListener('click', function () { answer(i); }); w.appendChild(b); });
|
||||
$('sdCheck').hidden = false;
|
||||
});
|
||||
}
|
||||
function answer(i) {
|
||||
api('/api/door/done', { n: nonce, answer: i }).then(function (r) {
|
||||
if (r.error) {
|
||||
if (r.retry) return challenge();
|
||||
if (r.cap && r.ret) return msg('That is tonight’s doors', 'You have knocked on every door for today. Your candy is safe, and the doors open again at midnight Central.', r.ret, true);
|
||||
$('sdHint').textContent = r.error; $('sdCheck').hidden = true; var bb = $('sdBack'); bb.hidden = false; bb.onclick = function () { location.href = gameHome; }; return;
|
||||
}
|
||||
$('sdCheck').hidden = true; $('sdHint').textContent = r.host ? 'Visit counted. @' + r.host + ' has a treat for you.' : 'Visit counted. Someone has a treat for you.';
|
||||
var b = $('sdDone'); b.disabled = false; b.textContent = 'Back to the street'; b.onclick = function () { location.href = r.ret; };
|
||||
setTimeout(function () { location.href = r.ret; }, 1200);
|
||||
});
|
||||
}
|
||||
if (!tok) return msg('No door here', 'Open this page by knocking on a door in Spooky Doors.');
|
||||
api('/api/door/open?t=' + encodeURIComponent(tok)).then(function (r) {
|
||||
if (r.error) return msg('Door link problem', r.error);
|
||||
if (r.done) { location.href = r.ret; return; }
|
||||
if (r.none) return r.why === 'cap'
|
||||
? msg('That is tonight’s doors', 'You have knocked on every door for today. Your candy is safe, and the doors open again at midnight Central. Your regular InstantAdPay visits are not affected.', r.ret, true)
|
||||
: msg('Nobody’s home', 'The lights are out at this house: there are no member pages or videos left for you right now. No candy here, and this door does not count. Head back and try the next house.', r.ret, true);
|
||||
dwell = r.dwell || 8; left = Math.max(1, dwell - (r.elapsed || 0));
|
||||
if (r.doors && r.doors.cap) { var ch = $('sdDoors'); ch.textContent = 'Door ' + Math.min(r.doors.cap, (r.doors.used || 0) + 1) + ' of ' + r.doors.cap; ch.hidden = false; }
|
||||
var who = r.host ? '@' + r.host + '’s door' : 'A member’s door';
|
||||
if (r.mode === 'video') { // no member pages left: a member video ad instead
|
||||
$('sdTitle').textContent = who + ': ' + (r.title || 'member video'); $('sdUrl').textContent = 'video ad';
|
||||
$('sdHint').textContent = 'You have visited every member page running right now, so this door is a short member video. Keep it playing.';
|
||||
var v = document.createElement('video'); v.id = 'sdVideo'; v.src = r.video.url; v.autoplay = true; v.muted = true; v.playsInline = true; v.setAttribute('playsinline', ''); v.loop = true; v.controls = false;
|
||||
v.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#000';
|
||||
$('sdFrame').innerHTML = ''; $('sdFrame').appendChild(v);
|
||||
var un = document.createElement('button'); un.type = 'button'; un.textContent = 'Tap for sound'; un.style.cssText = 'position:absolute;right:10px;bottom:10px;z-index:2;padding:8px 12px;border-radius:8px;border:0;background:rgba(0,0,0,.6);color:#fff;font:600 12px system-ui';
|
||||
un.onclick = function () { v.muted = false; v.play().catch(function () {}); un.remove(); }; $('sdFrame').appendChild(un);
|
||||
v.play().catch(function () { $('sdHint').textContent = 'Tap the video to start it. The timer runs while it plays.'; v.onclick = function () { v.play(); }; });
|
||||
ring(); timer = setInterval(tick, 1000); return;
|
||||
}
|
||||
$('sdTitle').textContent = who + ': ' + (r.title || 'member site'); try { $('sdUrl').textContent = new URL(r.target).hostname; } catch (e) {}
|
||||
var f = document.createElement('iframe'); f.src = r.target; f.setAttribute('referrerpolicy', 'no-referrer'); f.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups'); $('sdFrame').innerHTML = ''; $('sdFrame').appendChild(f);
|
||||
var o = $('sdOpen'); o.href = r.target; o.hidden = false;
|
||||
ring(); timer = setInterval(tick, 1000);
|
||||
}).catch(function () { msg('Could not open the door', 'Check your connection and go back to the street.'); });
|
||||
})();
|
||||
+5
-1
@@ -825,6 +825,9 @@
|
||||
if (me.returnTo === 'driprunner' && !render.toGame) { render.toGame = true; location.href = '/api/my/driprunner'; return; }
|
||||
if (me.returnTo === 'gemkingdom' && !render.toGame) { render.toGame = true; location.href = '/api/my/gemkingdom'; return; } // Gem Kingdom sent them here to sign in (2026-10-01)
|
||||
if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; }
|
||||
if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02)
|
||||
if (me.returnTo === 'sdshop' && !render.toGame) { render.toGame = true; location.href = '/sd/shop/resume'; return; }
|
||||
if (me.sdShop && !document.getElementById('sdBack')) { const d = document.createElement('a'); d.id = 'sdBack'; d.href = '/sd/shop/resume'; d.textContent = 'Finish your Spooky Doors costume order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:' + (me.gkShop ? '74px' : '14px') + ';z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:#FF8A1F;color:#2a1200;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 5px 0 #C25A06,0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); }
|
||||
if (me.gkShop && !document.getElementById('gkBack')) { const d = document.createElement('a'); d.id = 'gkBack'; d.href = '/gk/shop/resume'; d.textContent = 'Finish your Gem Kingdom Crowns order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); }
|
||||
if (me.returnTo === 'passivedrip' && !render.toGame) { render.toGame = true; location.href = '/api/my/passivedrip'; return; } // PassiveDrip sent them here to sign in (2026-10-01)
|
||||
// arrived from an invite page: run the welcome tour and login ad once
|
||||
@@ -1654,7 +1657,8 @@
|
||||
let g = null; try { g = await (await fetch('/api/my/games')).json(); } catch (e) {}
|
||||
const list = (g && g.games) || [];
|
||||
if (!list.length) { el.innerHTML = '<p class="muted small">No games are open yet. Check back soon.</p>'; return; }
|
||||
el.innerHTML = list.map(x => '<div class="game-card"><img src="' + esc(x.art) + '" alt="" loading="lazy"' + (x.artPos ? ' style="object-position:' + esc(x.artPos) + ' center"' : '') + '><div class="gc-body"><span class="gc-tag">' + esc(x.tag || '') + '</span><h4>' + esc(x.name) + (x.preview ? '<span class="gc-pre">preview, not live</span>' : '') + '</h4><p class="muted small" style="margin:0">' + esc(x.blurb) + '</p>' + (x.progress && x.progress.line ? '<div class="gc-prog">' + esc(x.progress.line) + '</div>' : '') + '<p class="muted small" style="margin:0">Pays: ' + esc(x.pays || 'POL') + '</p><a class="btn" href="' + esc(x.play) + '">' + esc(x.cta || 'Play') + '</a></div></div>').join('');
|
||||
// a seasonal card (x.season, 2026-10-02) wears the pink limited-time ribbon from the Spooky Doors UI kit
|
||||
el.innerHTML = list.map(x => '<div class="game-card"><img src="' + esc(x.art) + '" alt="" loading="lazy"' + (x.artPos ? ' style="object-position:' + esc(x.artPos) + ' center"' : '') + '>' + (x.season && x.season.ends ? '<span class="gc-ribbon"><i></i>Limited time \u00b7 ends ' + esc(x.season.ends) + '</span>' : '') + '<div class="gc-body"><span class="gc-tag">' + esc(x.tag || '') + '</span><h4>' + esc(x.name) + (x.preview ? '<span class="gc-pre">' + esc(x.previewNote || 'preview, not live') + '</span>' : '') + '</h4><p class="muted small" style="margin:0">' + esc(x.blurb) + '</p>' + (x.progress && x.progress.line ? '<div class="gc-prog">' + esc(x.progress.line) + '</div>' : '') + '<p class="muted small" style="margin:0">Pays: ' + esc(x.pays || 'POL') + '</p><a class="btn" href="' + esc(x.play) + '">' + esc(x.cta || 'Play') + '</a></div></div>').join('');
|
||||
}
|
||||
async function loadReturnCard() {
|
||||
const card = $('phReturn'); if (!card) return;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<!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>Knock knock · Spooky Doors verified visit</title>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Creepster&family=Fredoka:wght@400;500;600;700&display=swap">
|
||||
<style>
|
||||
:root{--night:#140B24;--plum:#241339;--plum-2:#33204F;--line:#4A3270;--pumpkin:#FF8A1F;--pumpkin-d:#C25A06;--candy:#FF5FA2;--moon:#5FE0D2;--ghost:#F4F1FF;--muted:#B9A9D6;--display:"Creepster","Chiller",fantasy;--ui:"Fredoka","Trebuchet MS",system-ui,sans-serif}
|
||||
*{box-sizing:border-box}
|
||||
[hidden]{display:none!important}
|
||||
html,body{height:100%}
|
||||
body{margin:0;display:flex;flex-direction:column;background:var(--night);color:var(--ghost);font-family:var(--ui)}
|
||||
.dr-bar{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px 14px;background:var(--plum);border-bottom:1px solid var(--line);font-size:13px}
|
||||
.dr-bar b{color:var(--pumpkin);font-weight:600}.dr-bar .dr-url{color:var(--muted);font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;max-width:45%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.dr-frame{flex:1;min-height:0;background:var(--night) url(/assets/door-open.jpg?v=20261002) center/cover no-repeat;position:relative}
|
||||
.dr-frame iframe{position:absolute;inset:0;width:100%;height:100%;border:0;background:#fff}
|
||||
.dr-dock{padding:12px 14px calc(12px + env(safe-area-inset-bottom,0px));background:var(--plum);border-top:1px solid var(--line)}
|
||||
.dr-row{display:grid;grid-template-columns:48px 1fr;gap:12px;align-items:center}
|
||||
.dr-ring{width:48px;height:48px;border-radius:50%;background:conic-gradient(var(--pumpkin) var(--p,0%),var(--plum-2) 0);display:grid;place-items:center;font:700 14px var(--ui);position:relative}
|
||||
.dr-ring:after{content:"";position:absolute;inset:5px;border-radius:50%;background:var(--plum)}.dr-ring span{position:relative;z-index:1}
|
||||
.dr-dock p{margin:0;font-size:13px;color:var(--muted);line-height:1.4}.dr-dock p b{color:var(--ghost);font-weight:600}
|
||||
.dr-opts{display:flex;gap:8px;flex-wrap:wrap;margin-top:8px}
|
||||
.dr-opts button{font-size:24px;padding:8px 14px;border-radius:10px;border:1px solid var(--line);background:var(--plum-2);cursor:pointer}
|
||||
.dr-opts button:focus-visible,.dr-btn:focus-visible{outline:3px solid var(--moon);outline-offset:2px}
|
||||
.dr-btn{display:block;width:100%;margin-top:12px;padding:12px;border-radius:14px;border:0;font:700 16px var(--ui);color:#2a1200;background:var(--pumpkin);box-shadow:0 5px 0 var(--pumpkin-d);cursor:pointer}
|
||||
.dr-btn[disabled]{opacity:.45}
|
||||
.dr-btn.ghost{background:transparent;color:var(--ghost);box-shadow:inset 0 0 0 2px var(--line);font-size:14px;padding:10px}
|
||||
.dr-msg{position:absolute;inset:0;display:grid;place-items:center;padding:20px 16px;background:linear-gradient(rgba(20,11,36,.35),rgba(20,11,36,.85))}
|
||||
.dr-msg .in{max-width:420px;text-align:center;background:rgba(36,19,57,.92);border:1px solid var(--line);border-radius:18px;padding:18px 16px;box-shadow:0 16px 40px rgba(0,0,0,.5)}
|
||||
.dr-msg h1{font-family:var(--display);font-weight:400;font-size:40px;line-height:1;margin:0 0 8px;color:var(--pumpkin);text-shadow:0 3px 0 #5a1f00;letter-spacing:.02em}
|
||||
.dr-msg p{margin:0;color:var(--muted);line-height:1.45}
|
||||
.dr-chip{display:inline-block;margin-left:6px;padding:2px 8px;border-radius:999px;background:rgba(20,11,36,.7);border:1px solid var(--line);color:var(--moon);font-size:12px;font-weight:600}
|
||||
a.dr-open{color:var(--moon);font-size:12px}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="dr-bar"><span>InstantAdPay · verified visit · <b>Spooky Doors</b><span class="dr-chip" id="sdDoors" hidden></span></span><span class="dr-url" id="sdUrl"></span></div>
|
||||
<div class="dr-frame" id="sdFrame"><div class="dr-msg"><div class="in"><h1>Knock knock</h1><p>Opening the door...</p></div></div></div>
|
||||
<div class="dr-dock" id="sdDock">
|
||||
<div class="dr-row" id="sdRow"><div class="dr-ring" id="sdRing"><span id="sdN">…</span></div><div><p><b id="sdTitle">Someone is coming to the door…</b></p><p id="sdHint">Stay on this page. The timer only runs while it is in front.</p><a class="dr-open" id="sdOpen" href="#" target="_blank" rel="noopener" hidden>Page not showing? Open it in a new tab (the timer keeps running here).</a></div></div>
|
||||
<div id="sdCheck" hidden><p id="sdPrompt" style="margin-top:10px"></p><div class="dr-opts" id="sdOpts"></div></div>
|
||||
<button class="dr-btn" id="sdDone" type="button" disabled>Waiting…</button>
|
||||
<button class="dr-btn ghost" id="sdBack" type="button" hidden>Back to the street</button>
|
||||
</div>
|
||||
<script src="/assets/door.js?v=20261002a"></script>
|
||||
</body>
|
||||
</html>
|
||||
+7
-2
@@ -1029,7 +1029,12 @@
|
||||
.game-card .gc-prog{font-size:12px;padding:6px 8px;border-radius:8px;background:var(--mint-soft);color:var(--mint-hi)}
|
||||
.game-card h4{color:var(--ink);font-family:var(--disp)}.game-card .gc-tag{color:var(--mint)}
|
||||
.game-card .gc-pre{display:inline-block;font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;padding:2px 6px;border-radius:5px;background:#fde68a;color:#7c2d12;margin-left:6px}
|
||||
.game-card .btn{margin-top:auto;text-align:center}</style>
|
||||
.game-card .btn{margin-top:auto;text-align:center}
|
||||
.game-card{position:relative}
|
||||
.game-card .gc-ribbon{position:absolute;top:10px;left:10px;display:inline-flex;align-items:center;gap:6px;background:#FF5FA2;color:#2b0418;font-weight:700;font-size:11px;letter-spacing:.1em;text-transform:uppercase;padding:5px 10px;border-radius:6px;box-shadow:0 3px 0 #9c2a5d}
|
||||
.game-card .gc-ribbon i{width:7px;height:7px;border-radius:50%;background:#2b0418;display:inline-block;animation:gcPulse 1.4s ease-in-out infinite}
|
||||
@keyframes gcPulse{50%{opacity:.25}}
|
||||
@media (prefers-reduced-motion:reduce){.game-card .gc-ribbon i{animation:none}}</style>
|
||||
</div>
|
||||
<div class="pane" id="pane-wallet" hidden>
|
||||
<div class="card" id="faucetCard" hidden>
|
||||
@@ -1107,7 +1112,7 @@
|
||||
<script src="/assets/common.js?v=20260929b"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||
<script src="/assets/wallet.js?v=20260911a"></script>
|
||||
<script src="/assets/promo.js?v=20260929c"></script>
|
||||
<script src="/assets/my.js?v=20261002a"></script>
|
||||
<script src="/assets/my.js?v=20261002sd"></script>
|
||||
<script src="/assets/chat.js?v=20260907l"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
// Spooky Doors door flow, end to end against a LOCAL copy (2026-10-02).
|
||||
// node qa/door.mjs (or: bash qa/run.sh door)
|
||||
// Boots server.js on its own port with a throwaway DATA_DIR and throwaway SD/DR secrets, plus a mock Spooky Doors
|
||||
// game server that records the signed callbacks. Nothing touches production: SD_URL and DR_URL point at the mock.
|
||||
// Covers: open -> challenge (wrong pick, then right) -> done -> callback signature + receipt, re-open after done,
|
||||
// "nobody's home" (none=1, door not counted), cap (cap=1), the door/refuel/earn caps staying separate, bad tokens,
|
||||
// and the Games card season window. Exit code 1 on any failure.
|
||||
import http from 'node:http';
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const PORT = Number(process.env.DOOR_PORT || 8798), MOCK = PORT + 100;
|
||||
const B = 'http://127.0.0.1:' + PORT, SD = 'http://127.0.0.1:' + MOCK;
|
||||
const SECRET = crypto.randomBytes(24).toString('hex'), DRSECRET = crypto.randomBytes(24).toString('hex'); // throwaway, never printed
|
||||
const ADMIN = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com';
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-door-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||
const CAP = { rocket: '🚀', 'lightning bolt': '⚡', key: '🔑', target: '🎯', wave: '🌊', flame: '🔥', diamond: '💎', magnet: '🧲', bell: '🔔', moon: '🌙' };
|
||||
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
// -- the mock game: records door callbacks, serves a frameable page for the visit target
|
||||
const callbacks = [], shopCalls = [], refuelCalls = [];
|
||||
const mock = http.createServer((req, res) => {
|
||||
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
|
||||
if (req.url === '/api/door/callback' && req.method === 'POST') { callbacks.push({ ts: req.headers['x-sd-ts'], sig: req.headers['x-sd-sig'], raw }); res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end('{"ok":true}'); }
|
||||
if (req.url === '/api/refuel/callback' && req.method === 'POST') { refuelCalls.push(raw); res.writeHead(200); return res.end('{}'); }
|
||||
if (req.url === '/api/iap/credit' && req.method === 'POST') { shopCalls.push(raw); res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end('{"ok":true}'); }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>member page</title><p>hello</p>');
|
||||
});
|
||||
});
|
||||
await new Promise(r => mock.listen(MOCK, '127.0.0.1', r));
|
||||
|
||||
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
const mint = (claims, secret, ttl) => { const p = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttl || 900000) }, claims)); return b64u(p) + '.' + b64u(crypto.createHmac('sha256', secret || SECRET).update(p).digest()); };
|
||||
const verify = tok => { const [p, s] = String(tok).split('.'); const payload = Buffer.from(p.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); return b64u(crypto.createHmac('sha256', SECRET).update(payload).digest()) === s ? JSON.parse(payload) : null; };
|
||||
|
||||
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL, ADMIN_PASSWORD: ADMIN, SD_SSO_SECRET: SECRET, SD_URL: SD, DR_SSO_SECRET: DRSECRET, DR_URL: SD }) });
|
||||
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
|
||||
const cleanup = () => { try { srv.kill(); } catch (e) {} try { mock.close(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
|
||||
|
||||
try {
|
||||
let up = false; for (let i = 0; i < 30 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(500); } }
|
||||
if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
|
||||
const api = async (p, body, hdr) => { const r = await fetch(B + p, body ? { method: body.method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: JSON.stringify(body.data || body) } : { headers: hdr || {}, redirect: 'manual' }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j, headers: r.headers }; };
|
||||
const adminH = { Authorization: 'Bearer ' + ADMIN };
|
||||
async function signIn(email, username) {
|
||||
const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000 });
|
||||
const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
|
||||
const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
|
||||
if (username) await api('/api/my/profile', { username }, { Cookie: cookie });
|
||||
return cookie;
|
||||
}
|
||||
|
||||
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10 } }, adminH); // three test accounts from one IP
|
||||
// the house account gets a public username so the door has a host to name
|
||||
await signIn('house@instantadpay.com', 'househaunt');
|
||||
await api('/api/admin/rates', { method: 'PATCH', data: { visitDwellSeconds: 2, doorCapPerDay: 15, refuelCapPerDay: 1 } }, adminH);
|
||||
let seed = await api('/api/admin/campaigns', { type: 'visits', name: 'QA door', targetUrl: SD + '/member-page', title: 'A member page', count: 20 }, adminH);
|
||||
if (!(seed.j && seed.j.ok)) seed = await api('/api/admin/campaigns', { type: 'visits', name: 'QA door', targetUrl: 'https://rmcircle.team/contract', title: 'A member page', count: 20 }, adminH);
|
||||
ok(seed.j && seed.j.ok, 'seed a visits pack', seed.j && seed.j.ok ? '#' + seed.j.campaign.id : JSON.stringify(seed.j));
|
||||
const cid = seed.j && seed.j.campaign && seed.j.campaign.id;
|
||||
|
||||
await api('/api/admin/rates', { method: 'PATCH', data: { welcomeCredits: 1000 } }, adminH); // so the player can buy a costume
|
||||
const player = 'qa-door@example.com'; const playerCookie = await signIn(player, 'qadoor');
|
||||
await api('/api/my/dashboard', null, { Cookie: playerCookie }); // grants the welcome credits (no upline tour)
|
||||
const earn0 = (await api('/api/my/earn', null, { Cookie: playerCookie })).j;
|
||||
|
||||
// 1. a door: open -> challenge -> done
|
||||
const n1 = crypto.randomBytes(12).toString('hex'); const ret1 = SD + '/play?door=' + n1;
|
||||
const t1 = mint({ kind: 'door', memberId: 77, email: player, username: 'qadoor', nonce: n1, ret: ret1 });
|
||||
const o1 = (await api('/api/door/open?t=' + encodeURIComponent(t1))).j;
|
||||
ok(o1 && o1.mode === 'visit' && o1.dwell === 2, 'open serves a visit', JSON.stringify(o1));
|
||||
ok(o1 && o1.host === 'househaunt', 'open names the host', o1 && o1.host);
|
||||
ok(o1 && o1.doors && o1.doors.used === 0 && o1.doors.cap === 15, 'open reports doors used/cap', JSON.stringify(o1 && o1.doors));
|
||||
const early = (await api('/api/door/challenge?n=' + n1)).j; ok(early && early.early, 'challenge refuses before the dwell');
|
||||
await sleep(2200);
|
||||
let ch = (await api('/api/door/challenge?n=' + n1)).j; ok(ch && ch.prompt && ch.options.length === 5, 'challenge after the dwell', ch && ch.prompt);
|
||||
const right = ch.options.indexOf(CAP[ch.prompt]);
|
||||
const wrong = (await api('/api/door/done', { n: n1, answer: (right + 1) % 5 })).j; ok(wrong && wrong.retry, 'wrong pick asks again');
|
||||
const noCh = (await api('/api/door/done', { n: n1, answer: right })).j; ok(noCh && noCh.retry, 'done without a fresh challenge refused');
|
||||
ch = (await api('/api/door/challenge?n=' + n1)).j;
|
||||
const d1 = (await api('/api/door/done', { n: n1, answer: ch.options.indexOf(CAP[ch.prompt]) })).j;
|
||||
ok(d1 && d1.ok && d1.posted === true, 'done ok + callback posted', JSON.stringify({ ok: d1 && d1.ok, posted: d1 && d1.posted, host: d1 && d1.host }));
|
||||
const ru = new URL(d1.ret);
|
||||
ok(d1.ret.startsWith(ret1 + '&ok=1&r='), 'redirect is ret&ok=1&r=<receipt>');
|
||||
const rc = verify(ru.searchParams.get('r'));
|
||||
ok(rc && rc.kind === 'door-receipt' && rc.nonce === n1 && rc.memberId === 77 && rc.campaignId === cid && rc.credits === 3 && rc.host === 'househaunt', 'receipt signed with the right claims', JSON.stringify(rc && { kind: rc.kind, memberId: rc.memberId, campaignId: rc.campaignId, credits: rc.credits, host: rc.host }));
|
||||
ok(rc && rc.exp - rc.iat >= 24 * 3600000 - 1000, 'receipt lives 24 h');
|
||||
const cb = callbacks[0];
|
||||
const sigOk = cb && crypto.createHmac('sha256', SECRET).update(cb.ts + '\n' + cb.raw).digest('hex') === cb.sig;
|
||||
ok(sigOk && Math.abs(Date.now() - Number(cb.ts)) < 600000, 'callback X-SD-Sig = HMAC(ts + "\\n" + rawBody), ts fresh');
|
||||
const body = cb && JSON.parse(cb.raw);
|
||||
ok(body && body.nonce === n1 && body.memberId === 77 && body.campaignId === cid && body.credits === 3 && body.host === 'househaunt' && Object.keys(body).sort().join() === 'campaignId,credits,host,memberId,nonce', 'callback body {nonce, memberId, campaignId, credits, host}', cb && cb.raw);
|
||||
const again = (await api('/api/door/open?t=' + encodeURIComponent(t1))).j; ok(again && again.done && again.ret === d1.ret, 're-open after done returns the same receipt redirect');
|
||||
const twice = (await api('/api/door/done', { n: n1, answer: 0 })).j; ok(twice && twice.error, 'a door cannot be completed twice');
|
||||
|
||||
// 2. nobody's home: the only pack is visited, no videos -> none=1 and the door is not counted
|
||||
const n2 = crypto.randomBytes(12).toString('hex');
|
||||
const o2 = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n2, ret: SD + '/play?door=' + n2 })))).j;
|
||||
ok(o2 && o2.none && o2.why === 'empty' && o2.ret === SD + '/play?door=' + n2 + '&none=1', 'nothing to serve -> ret&none=1', JSON.stringify(o2));
|
||||
|
||||
// 3. the kinds stay separate: one door used, refuel cap 1 still open, Earn visits untouched
|
||||
const nr = crypto.randomBytes(12).toString('hex');
|
||||
const rf = (await api('/api/refuel/open?t=' + encodeURIComponent(mint({ kind: 'refuel', memberId: 77, email: player, nonce: nr, ret: SD + '/play?refuel=' + nr }, DRSECRET)))).j;
|
||||
ok(rf && rf.why !== 'cap', 'refuel cap not consumed by a door', JSON.stringify(rf));
|
||||
const earn1 = (await api('/api/my/earn', null, { Cookie: playerCookie })).j;
|
||||
ok(earn0 && earn1 && earn1.visitsLeft === earn0.visitsLeft, 'Earn visits left unchanged by a door', earn0 && earn1 && earn0.visitsLeft + ' -> ' + earn1.visitsLeft);
|
||||
|
||||
// 3b. a full Drip Runner refuel still works on a fresh pack, counts as a refuel (cap 1 now reached) and leaves doors alone
|
||||
const seed2 = await api('/api/admin/campaigns', { type: 'visits', name: 'QA refuel', targetUrl: 'https://rmcircle.team/contract', title: 'Another member page', count: 20 }, adminH);
|
||||
const nr2 = crypto.randomBytes(12).toString('hex');
|
||||
const rtok = mint({ kind: 'refuel', memberId: 77, email: player, nonce: nr2, ret: SD + '/play?refuel=' + nr2 }, DRSECRET);
|
||||
const ro = (await api('/api/refuel/open?t=' + encodeURIComponent(rtok))).j;
|
||||
ok(seed2.j && seed2.j.ok && ro && ro.mode === 'visit', 'refuel open serves the fresh pack', JSON.stringify(ro && { mode: ro.mode, none: ro.none, why: ro.why }));
|
||||
await sleep(2200);
|
||||
const rch = (await api('/api/refuel/challenge?n=' + nr2)).j;
|
||||
const rd = (await api('/api/refuel/done', { n: nr2, answer: rch.options.indexOf(CAP[rch.prompt]) })).j;
|
||||
ok(rd && rd.ok && rd.posted === true && refuelCalls.length === 1 && JSON.parse(refuelCalls[0]).credits === 3, 'refuel completes with its own callback', JSON.stringify(rd && { ok: rd.ok, posted: rd.posted }));
|
||||
const nr3 = crypto.randomBytes(12).toString('hex');
|
||||
const rcap = (await api('/api/refuel/open?t=' + encodeURIComponent(mint({ kind: 'refuel', memberId: 77, email: player, nonce: nr3, ret: SD + '/play?refuel=' + nr3 }, DRSECRET)))).j;
|
||||
ok(rcap && rcap.none && rcap.why === 'cap', 'refuel cap (1) reached after one refuel, not before', JSON.stringify(rcap));
|
||||
const earn2 = (await api('/api/my/earn', null, { Cookie: playerCookie })).j;
|
||||
ok(earn2 && earn2.visitsLeft === earn0.visitsLeft, 'Earn visits still untouched after a door and a refuel', String(earn2 && earn2.visitsLeft));
|
||||
|
||||
// 4. cap: doorCapPerDay 1 with one door done -> cap=1
|
||||
await api('/api/admin/rates', { method: 'PATCH', data: { doorCapPerDay: 1 } }, adminH);
|
||||
const n3 = crypto.randomBytes(12).toString('hex');
|
||||
const o3 = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n3, ret: SD + '/play?door=' + n3 })))).j;
|
||||
ok(o3 && o3.none && o3.why === 'cap' && o3.ret === SD + '/play?door=' + n3 + '&cap=1', 'cap reached -> ret&cap=1', JSON.stringify(o3));
|
||||
await api('/api/admin/rates', { method: 'PATCH', data: { doorCapPerDay: 15 } }, adminH);
|
||||
|
||||
// 5. bad tokens
|
||||
const n4 = crypto.randomBytes(12).toString('hex');
|
||||
const bad = await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n4, ret: SD + '/play?door=' + n4 }, DRSECRET)));
|
||||
ok(bad.status === 400, 'token signed with another secret refused');
|
||||
const foreign = await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n4, ret: 'https://evil.example/play?door=' + n4 })));
|
||||
ok(foreign.status === 400, 'ret outside SD_URL refused');
|
||||
const refuelTok = await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'refuel', memberId: 77, email: player, nonce: n4, ret: SD + '/play?door=' + n4 })));
|
||||
ok(refuelTok.status === 400, 'a non-door token refused');
|
||||
|
||||
// 6. sign-in hand-off + games card season window
|
||||
const ho = await fetch(B + '/api/my/spookydoors', { headers: { Cookie: playerCookie }, redirect: 'manual' });
|
||||
const loc = ho.headers.get('location') || ''; const sso = verify(new URL(loc).searchParams.get('t'));
|
||||
ok(ho.status === 302 && loc.startsWith(SD + '/auth?t=') && sso && sso.kind === 'sso' && sso.email === player && sso.username === 'qadoor', 'hand-off mints an sso token to SD_URL/auth');
|
||||
const anon = await fetch(B + '/api/my/spookydoors?ref=qadoor', { redirect: 'manual' });
|
||||
ok(anon.status === 302 && anon.headers.get('location') === '/my?ref=qadoor' && /iap\.return=spookydoors/.test(anon.headers.get('set-cookie') || ''), 'signed out -> /my?ref with iap.return=spookydoors');
|
||||
const adminCookie = await signIn(ADMIN_EMAIL);
|
||||
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
const gA = (await api('/api/my/games', null, { Cookie: adminCookie })).j; const sdA = gA && (gA.games || []).find(g => g.slug === 'spookydoors');
|
||||
const gM = (await api('/api/my/games', null, { Cookie: playerCookie })).j; const sdM = gM && (gM.games || []).find(g => g.slug === 'spookydoors');
|
||||
if (today < '2026-10-17') { ok(sdA && sdA.preview && sdA.season && sdA.season.ends === 'Oct 31' && /opens Oct 17/.test(sdA.previewNote || ''), 'before the season: admin sees a preview card ending Oct 31', JSON.stringify(sdA ? { preview: sdA.preview, season: sdA.season, note: sdA.previewNote } : gA)); ok(!sdM, 'before the season: members do not see the card'); }
|
||||
else if (today < '2026-11-01') { ok(sdA && sdA.season && sdA.season.ends === 'Oct 31', 'in season: admin sees the card with the ribbon date'); ok(!sdM, 'in season but not in gamesLive: members do not see it'); }
|
||||
else { ok(!sdA && !sdM, 'after the season: nobody sees the card'); }
|
||||
|
||||
// 7. costume shop: signed-out detour, confirm with CSRF, receipt + server callback, idempotent re-open, short of credits
|
||||
const order = 'qa-' + crypto.randomBytes(6).toString('hex');
|
||||
const buy = mint({ kind: 'sd-buy', aud: 'iap', order, email: player, memberId: 77, username: 'qadoor', item: 'vampire', label: 'Vampire costume', credits: 300, ret: SD + '/api/iap/receipt', cb: SD + '/api/iap/credit' }, null, 7200000);
|
||||
const so = await fetch(B + '/sd/shop?t=' + encodeURIComponent(buy), { redirect: 'manual' });
|
||||
ok(so.status === 302 && so.headers.get('location') === '/my' && /iap\.sdshop=/.test(so.headers.get('set-cookie') || '') && /iap\.return=sdshop/.test(so.headers.get('set-cookie') || ''), 'shop signed out -> /my, order remembered (iap.sdshop + iap.return=sdshop)');
|
||||
const sp = await fetch(B + '/sd/shop?t=' + encodeURIComponent(buy), { headers: { Cookie: playerCookie }, redirect: 'manual' }); const html = await sp.text();
|
||||
const csrf = (/name="csrf" value="([^"]+)"/.exec(html) || [])[1];
|
||||
ok(sp.status === 200 && /Costume shop/.test(html) && /Spend 300 credits/.test(html) && csrf, 'shop confirm page with CSRF', sp.status);
|
||||
ok(!/\u2014/.test(html), 'no em dashes on the shop page');
|
||||
const badCsrf = await fetch(B + '/sd/shop/confirm', { method: 'POST', headers: { Cookie: playerCookie, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ t: buy, csrf: 'nope' }).toString(), redirect: 'manual' });
|
||||
ok(badCsrf.status === 403, 'confirm with a bad CSRF refused');
|
||||
const cf = await fetch(B + '/sd/shop/confirm', { method: 'POST', headers: { Cookie: playerCookie, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ t: buy, csrf }).toString(), redirect: 'manual' }); const cfHtml = await cf.text();
|
||||
const back = ((/http-equiv="refresh" content="1;url=([^"]+)"/.exec(cfHtml) || [])[1] || '').replace(/&/g, '&');
|
||||
ok(cf.status === 200 && back.startsWith(SD + '/api/iap/receipt?t='), 'paid -> 200 meta-refresh back to ret?t=<receipt>', cf.status + ' ' + back.slice(0, 60));
|
||||
const src = back && verify(new URL(back).searchParams.get('t'));
|
||||
ok(src && src.kind === 'sd-receipt' && src.order === order && src.email === player && src.item === 'vampire' && src.credits === 300 && src.ref > 0, 'sd-receipt claims {kind, order, email, item, credits, ref}', JSON.stringify(src && { kind: src.kind, item: src.item, credits: src.credits, ref: src.ref }));
|
||||
await sleep(300);
|
||||
const scb = shopCalls[0] && JSON.parse(shopCalls[0]); const scr = scb && verify(scb.t);
|
||||
ok(scr && scr.kind === 'sd-receipt' && scr.order === order, 'cb got POST {t: <sd-receipt>}');
|
||||
const re = await fetch(B + '/sd/shop?t=' + encodeURIComponent(buy), { headers: { Cookie: playerCookie }, redirect: 'manual' });
|
||||
ok(re.status === 302 && (re.headers.get('location') || '').startsWith(SD + '/api/iap/receipt?t='), 'paid order re-opened -> straight back with the receipt (no second charge)');
|
||||
const cf2 = await fetch(B + '/sd/shop/confirm', { method: 'POST', headers: { Cookie: playerCookie, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ t: buy, csrf }).toString(), redirect: 'manual' });
|
||||
ok(cf2.status === 302 && shopCalls.length === 1, 'second confirm does not charge again');
|
||||
const big = mint({ kind: 'sd-buy', order: order + 'x', email: player, memberId: 77, item: 'apple', label: 'Lucky caramel apple', credits: 999999, ret: SD + '/api/iap/receipt', cb: SD + '/api/iap/credit' }, null, 7200000);
|
||||
const bh = await (await fetch(B + '/sd/shop?t=' + encodeURIComponent(big), { headers: { Cookie: playerCookie } })).text();
|
||||
ok(/more credits/.test(bh) && /\/sd\/shop\/topup\?t=/.test(bh), 'short of credits -> top-up offer');
|
||||
} catch (e) { fails++; console.log('FAIL exception: ' + e.message); }
|
||||
finally { cleanup(); }
|
||||
console.log(fails ? '\n' + fails + ' failure(s)' : '\nall door checks passed');
|
||||
process.exit(fails ? 1 : 0);
|
||||
@@ -4,6 +4,7 @@
|
||||
# bash qa/run.sh member # local copy: member + admin walk
|
||||
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
||||
# bash qa/run.sh all # public + member + earn
|
||||
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
|
||||
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
|
||||
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
|
||||
set -u
|
||||
@@ -30,6 +31,8 @@ if [ "$MODE" = "public" ]; then
|
||||
node qa/chatbot-sync.mjs || status=1
|
||||
elif [ "$MODE" = "member" ]; then
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||
elif [ "$MODE" = "door" ]; then
|
||||
node qa/door.mjs || status=1
|
||||
elif [ "$MODE" = "earn" ]; then
|
||||
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
|
||||
else
|
||||
|
||||
@@ -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 · 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 · 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)
|
||||
|
||||
Reference in New Issue
Block a user