// 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, // house ads when the street is empty (RM Circle first, then the next program with the player's ref; credits 0, counted), // "nobody's home" only with doorHouseAds = [] (none=1, door not counted), cap (cap=1), the door/refuel/earn caps staying separate, bad tokens, // the Games card + Promo tools card season window, and door packs + Golden Doors (placement 'doors'/'golden': prices, golden first, // door pack second, once per player per Central day, credits/golden/bonus in open + callback + receipt, never on Earn or refuels in // season, ordinary visits from sdSeasonEnd, advertiser door stats). 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: 'πŸŒ™', pumpkin: 'πŸŽƒ', ghost: 'πŸ‘»', bat: 'πŸ¦‡', candy: '🍬', spider: 'πŸ•·οΈ', skull: 'πŸ’€', lollipop: '🍭', witch: 'πŸ§™', 'spider web': 'πŸ•ΈοΈ', 'full moon': 'πŸŒ•', chocolate: '🍫' }; // door check = Halloween set 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('member page

hello

'); }); }); 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='); 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. the only pack is visited and there are no videos: a house ad (one of Marty's programs) for a smaller treat const n2 = crypto.randomBytes(12).toString('hex'); const o2 = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, username: 'qadoor', nonce: n2, ret: SD + '/play?door=' + n2 })))).j; ok(o2 && o2.mode === 'visit' && o2.house === true && o2.program === 'RM Circle' && o2.host === null && o2.target === 'https://rmcircle.team/' && o2.dwell === 2, 'nothing to serve -> a house ad (RM Circle, plain url)', JSON.stringify(o2)); ok(o2 && o2.doors && o2.doors.used === 1, 'house door shows the door count', JSON.stringify(o2 && o2.doors)); await sleep(2200); const hch = (await api('/api/door/challenge?n=' + n2)).j; const d2 = (await api('/api/door/done', { n: n2, answer: hch.options.indexOf(CAP[hch.prompt]) })).j; ok(d2 && d2.ok && d2.posted === true && d2.house === true && d2.program === 'RM Circle' && d2.host === null, 'house door done + callback posted', JSON.stringify(d2 && { ok: d2.ok, posted: d2.posted, house: d2.house, program: d2.program })); const hr = d2 && verify(new URL(d2.ret).searchParams.get('r')); ok(hr && hr.kind === 'door-receipt' && hr.nonce === n2 && hr.memberId === 77 && hr.house === true && hr.credits === 0 && hr.host === null && hr.campaignId === 0 && hr.program === 'RM Circle', 'house receipt {house: true, credits: 0, host: null, campaignId: 0, program}', JSON.stringify(hr && { house: hr.house, credits: hr.credits, host: hr.host, campaignId: hr.campaignId, program: hr.program })); const hb = callbacks[1] && JSON.parse(callbacks[1].raw); ok(hb && hb.nonce === n2 && hb.house === true && hb.credits === 0 && hb.host === null && hb.program === 'RM Circle' && Object.keys(hb).sort().join() === 'campaignId,credits,host,house,memberId,nonce,program', 'house callback body adds {house, program}', callbacks[1] && callbacks[1].raw); const camps = (await api('/api/admin/campaigns', null, adminH)).j; const pack = camps && (camps.campaigns || []).find(x => x.id === cid); ok(pack && pack.imps === 1, 'house door does not touch the pack imps', pack && String(pack.imps)); // next house door: not the same program twice in a row, and the player's username rides along as the program's own ref link const n2c = crypto.randomBytes(12).toString('hex'); const o2c = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n2c, ret: SD + '/play?door=' + n2c })))).j; ok(o2c && o2c.house && o2c.program === 'Drip Runner' && o2c.target === 'https://driprunner.app/r/qadoor' && o2c.doors.used === 2, 'next house door rotates (Drip Runner, /r/) and the first one counted', JSON.stringify(o2c && { program: o2c.program, target: o2c.target, doors: o2c.doors })); // doorHouseAds = [] turns house doors off: nobody's home again, and the door is not counted await api('/api/admin/rates', { method: 'PATCH', data: { doorHouseAds: [] } }, adminH); const n2e = crypto.randomBytes(12).toString('hex'); const o2e = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n2e, ret: SD + '/play?door=' + n2e })))).j; ok(o2e && o2e.none && o2e.why === 'empty' && o2e.ret === SD + '/play?door=' + n2e + '&none=1', 'doorHouseAds [] + nothing to serve -> ret&none=1', JSON.stringify(o2e)); // 2b. doors may repeat a campaign after doorRepeatDays (0 here = no cooldown): the same pack is served again await api('/api/admin/rates', { method: 'PATCH', data: { doorRepeatDays: 0 } }, adminH); const n2b = crypto.randomBytes(12).toString('hex'); const o2b = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n2b, ret: SD + '/play?door=' + n2b })))).j; ok(o2b && o2b.mode === 'visit', 'after the cooldown a door repeats an already-visited pack', JSON.stringify(o2b)); await api('/api/admin/rates', { method: 'PATCH', data: { doorRepeatDays: 7 } }, adminH); // 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'); const pA = (await api('/api/my/spookydoors/promo', null, { Cookie: adminCookie })).j, pM = (await api('/api/my/spookydoors/promo', null, { Cookie: playerCookie })).j; if (today < '2026-10-04') { ok(sdA && sdA.preview && sdA.season && sdA.season.start === '2026-10-04' && sdA.season.ends === 'Oct 31' && /opens Oct 4/.test(sdA.previewNote || ''), 'before the season (starts Oct 4): 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'); ok(pA && pA.show && pA.preview && pA.base === SD && pA.image === SD + '/og-spookydoors.jpg' && pM && pM.show === false, 'Promo tools card: admin preview before the season, hidden for members', JSON.stringify({ pA, pM })); } 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'); ok(pA && pA.show && !pA.preview && pM && pM.show && !pM.preview && pM.image === SD + '/og-spookydoors.jpg', 'Promo tools card: shown to members in season', JSON.stringify({ pA, pM })); } else { ok(!sdA && !sdM, 'after the season: nobody sees the card'); ok(pA && pA.show === false && pM && pM.show === false, 'Promo tools card: hidden after the season'); } // 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=', 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: }'); 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'); // 8. door packs + Golden Doors (launch pack A, 2026-10-02) const rt0 = (await api('/api/admin/rates', null, adminH)).j.rates; ok(rt0.visitCostPerVisit === 3 && rt0.doorPackCost === 4 && rt0.goldenDoorCost === 6 && rt0.goldenBonusCandy === 2 && rt0.sdSeasonEnd === '2026-11-01', 'rates: visit 3, door pack 4, Golden Door 6, golden bonus 2, season end 2026-11-01', JSON.stringify({ v: rt0.visitCostPerVisit, d: rt0.doorPackCost, g: rt0.goldenDoorCost, b: rt0.goldenBonusCandy, e: rt0.sdSeasonEnd })); await api('/api/admin/rates', { method: 'PATCH', data: { sdSeasonEnd: '2099-01-01', doorCapPerDay: 15, doorRepeatDays: 7 } }, adminH); // in season whatever today is const mkPack = async (title, placement) => { let x = await api('/api/admin/campaigns', { type: 'visits', name: title, targetUrl: SD + '/' + placement, title, count: 20, placement }, adminH); if (!(x.j && x.j.ok)) x = await api('/api/admin/campaigns', { type: 'visits', name: title, targetUrl: 'https://rmcircle.team/contract', title, count: 20, placement }, adminH); return x.j; }; const gp = await mkPack('QA golden door', 'golden'), dp = await mkPack('QA door pack', 'doors'); ok(gp && gp.ok && gp.campaign.placement === 'golden' && gp.campaign.budget === 120 && gp.campaign.doorOnly === true, 'Golden Door pack: 20 doors = 120 credits, placement golden', JSON.stringify(gp && gp.campaign && { pl: gp.campaign.placement, budget: gp.campaign.budget, doorOnly: gp.campaign.doorOnly })); ok(dp && dp.ok && dp.campaign.placement === 'doors' && dp.campaign.budget === 80, 'door pack: 20 doors = 80 credits, placement doors', JSON.stringify(dp && dp.campaign && { pl: dp.campaign.placement, budget: dp.campaign.budget })); const badPl = await api('/api/admin/campaigns', { type: 'visits', name: 'x', targetUrl: 'https://rmcircle.team/contract', title: 'x', count: 20, placement: 'roof' }, adminH); ok(badPl.status === 400 && /Pick where/.test(badPl.j && badPl.j.error || ''), 'unknown placement refused'); // a member buys a door pack with their own credits (charged up front, 4 a door) and tops it up at the door price const before = (await api('/api/my/campaigns', null, { Cookie: playerCookie })).j; let mp = await api('/api/my/campaigns', { type: 'visits', name: 'QA member doors', targetUrl: SD + '/member-doors', title: 'QA member doors', count: 20, placement: 'doors', budget: 80 }, { Cookie: playerCookie }); if (!(mp.j && mp.j.ok)) mp = await api('/api/my/campaigns', { type: 'visits', name: 'QA member doors', targetUrl: 'https://rmcircle.team/contract', title: 'QA member doors', count: 20, placement: 'doors', budget: 80 }, { Cookie: playerCookie }); const mpc = mp.j && mp.j.campaign; const after = (await api('/api/my/campaigns', null, { Cookie: playerCookie })).j; ok(mpc && mpc.placement === 'doors' && mpc.budget === 80 && before.availableCredits - after.availableCredits === 80, 'member door pack charged 80 up front', JSON.stringify({ c: mpc && { pl: mpc.placement, budget: mpc.budget }, err: mp.j && mp.j.error, avail: [before.availableCredits, after.availableCredits] })); const tu = (await api('/api/my/campaigns/' + (mpc && mpc.id) + '/topup', { credits: 12 }, { Cookie: playerCookie })).j; ok(tu && tu.ok && tu.visits === 3 && tu.added === 12 && tu.total === 23, 'door pack top-up buys doors at 4 credits', JSON.stringify(tu)); const T_GOLD = gp.campaign.id, T_DOORS = [dp.campaign.id, mpc && mpc.id]; // a fresh player knocks: golden first, then door packs, then the existing chain; each pack once per Central day const knocker = 'qa-knock@example.com'; const knockCookie = await signIn(knocker, 'qaknock'); const cbStart = callbacks.length; async function knock(email) { const n = crypto.randomBytes(12).toString('hex'); const o = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 88, email, nonce: n, ret: SD + '/play?door=' + n })))).j; if (!o || o.mode !== 'visit') return { o }; await sleep(2200); const c2 = (await api('/api/door/challenge?n=' + n)).j; const d = (await api('/api/door/done', { n, answer: c2.options.indexOf(CAP[c2.prompt]) })).j; const rc2 = d && d.ret ? verify(new URL(d.ret).searchParams.get('r')) : null; const cbx = callbacks.map(x => JSON.parse(x.raw)).find(x => x.nonce === n) || null; return { o, d, rc: rc2, cb: cbx }; } const k1 = await knock(knocker); ok(k1.o.golden === true && k1.o.bonus === 2 && k1.o.credits === 6 && k1.o.title === 'QA golden door', 'door 1: the Golden Door first (open: golden, bonus 2, credits 6)', JSON.stringify(k1.o && { title: k1.o.title, golden: k1.o.golden, bonus: k1.o.bonus, credits: k1.o.credits })); ok(k1.cb && k1.cb.golden === true && k1.cb.bonus === 2 && k1.cb.credits === 6 && k1.cb.campaignId === T_GOLD && Object.keys(k1.cb).sort().join() === 'bonus,campaignId,credits,golden,host,memberId,nonce', 'Golden Door callback {.., credits: 6, golden: true, bonus: 2}', k1.cb && JSON.stringify(k1.cb)); ok(k1.rc && k1.rc.kind === 'door-receipt' && k1.rc.golden === true && k1.rc.bonus === 2 && k1.rc.credits === 6 && k1.rc.campaignId === T_GOLD, 'Golden Door receipt carries golden, bonus, credits 6', JSON.stringify(k1.rc && { golden: k1.rc.golden, bonus: k1.rc.bonus, credits: k1.rc.credits })); ok(k1.d && k1.d.golden === true && k1.d.bonus === 2 && k1.d.credits === 6, 'done response says golden too'); const k2 = await knock(knocker), k3 = await knock(knocker); ok(k2.cb && T_DOORS.includes(k2.cb.campaignId) && k2.cb.credits === 4 && !('golden' in k2.cb) && Object.keys(k2.cb).sort().join() === 'campaignId,credits,host,memberId,nonce' && k2.o.credits === 4 && !k2.o.golden, 'door 2: a door pack (credits 4, no golden fields)', JSON.stringify(k2.cb)); ok(k2.rc && k2.rc.credits === 4 && !('golden' in k2.rc), 'door pack receipt credits 4'); ok(k3.cb && T_DOORS.includes(k3.cb.campaignId) && k3.cb.campaignId !== k2.cb.campaignId && k3.cb.credits === 4, 'door 3: the other door pack, not the same one twice in a day', JSON.stringify(k3.cb)); const k4 = await knock(knocker); ok(k4.cb && ![T_GOLD].concat(T_DOORS).includes(k4.cb.campaignId) && k4.cb.credits === 3 && !k4.o.golden, 'door 4: packs used today, so the existing chain (a visit pack, credits 3)', JSON.stringify(k4.cb)); await api('/api/admin/rates', { method: 'PATCH', data: { doorRepeatDays: 0 } }, adminH); // ordinary packs may repeat at once; door packs still wait for tomorrow const k5 = await knock(knocker); ok(!k5.cb || ![T_GOLD].concat(T_DOORS).includes(k5.cb.campaignId), 'with no repeat cooldown, golden and door packs still once per Central day', JSON.stringify(k5.cb || k5.o)); await api('/api/admin/rates', { method: 'PATCH', data: { doorRepeatDays: 7 } }, adminH); // advertiser stats on the member's pack const mine = (await api('/api/my/campaigns', null, { Cookie: playerCookie })).j; const myPack = mine && mine.campaigns.find(c => c.id === (mpc && mpc.id)); const ds = mine && mine.doorStats && mine.doorStats[mpc && mpc.id]; ok(myPack && myPack.placement === 'doors' && myPack.doorOnly && ds && ds.doors === 1 && ds.players === 1 && myPack.imps === 1, 'campaign stats: doors opened 1, unique players 1', JSON.stringify({ ds, imps: myPack && myPack.imps })); // in season door packs never reach the Earn tab or refuels: pause every ordinary pack, then a fresh member finds nothing there const allCamps = (await api('/api/admin/campaigns', null, adminH)).j.campaigns.filter(c => c.type === 'visits' && c.status === 'active' && c.placement === 'all'); for (const c of allCamps) await api('/api/admin/campaigns/' + c.id + '/pause', {}, adminH); const earner = 'qa-earner@example.com'; const earnCookie = await signIn(earner, 'qaearner'); const ev = (await api('/api/my/visits', null, { Cookie: earnCookie })).j; ok(ev && ev.ad === null, 'in season: the Earn tab never serves a door pack or Golden Door', JSON.stringify(ev && ev.ad)); await api('/api/admin/rates', { method: 'PATCH', data: { refuelCapPerDay: 20 } }, adminH); const nrf = crypto.randomBytes(12).toString('hex'); const rfx = (await api('/api/refuel/open?t=' + encodeURIComponent(mint({ kind: 'refuel', memberId: 89, email: earner, nonce: nrf, ret: SD + '/play?refuel=' + nrf }, DRSECRET)))).j; ok(rfx && rfx.none && rfx.why === 'empty', 'in season: refuels never serve a door pack or Golden Door', JSON.stringify(rfx)); const pdl = (await api('/api/admin/campaigns', null, adminH)).j.campaigns.filter(c => c.doorOnly); ok(pdl.length >= 3, 'door-only packs are flagged doorOnly (kept off the PassiveDrip listing)', String(pdl.length)); // from sdSeasonEnd they are ordinary visits: Earn and refuels serve them, doors no longer favour them, no golden fields await api('/api/admin/rates', { method: 'PATCH', data: { sdSeasonEnd: today } }, adminH); const ev2 = (await api('/api/my/visits', null, { Cookie: earnCookie })).j; ok(ev2 && ev2.ad && ['QA golden door', 'QA door pack', 'QA member doors'].includes(ev2.ad.title), 'after sdSeasonEnd: the Earn tab serves door packs as normal visits', JSON.stringify(ev2 && ev2.ad && ev2.ad.title)); const nrf2 = crypto.randomBytes(12).toString('hex'); const rfy = (await api('/api/refuel/open?t=' + encodeURIComponent(mint({ kind: 'refuel', memberId: 89, email: earner, nonce: nrf2, ret: SD + '/play?refuel=' + nrf2 }, DRSECRET)))).j; ok(rfy && rfy.mode === 'visit' && ['QA golden door', 'QA door pack', 'QA member doors'].includes(rfy.title), 'after sdSeasonEnd: refuels serve them too', JSON.stringify(rfy && { mode: rfy.mode, title: rfy.title, why: rfy.why })); const k6 = await knock('qa-late@example.com'); ok(k6.o && k6.o.mode === 'visit' && !k6.o.golden && k6.cb && !('golden' in k6.cb) && [6, 4].includes(k6.cb.credits), 'after sdSeasonEnd: a door gets an ordinary door (no golden), credits still what the pack paid', JSON.stringify(k6.cb || k6.o)); const late = await api('/api/admin/campaigns', { type: 'visits', name: 'late', targetUrl: 'https://rmcircle.team/contract', title: 'late', count: 20, placement: 'golden' }, adminH); ok(late.status === 400 && /season is over/.test(late.j && late.j.error || ''), 'after sdSeasonEnd: new door packs refused'); const gpNow = (await api('/api/admin/campaigns', null, adminH)).j.campaigns.find(c => c.id === T_GOLD); ok(gpNow && gpNow.placement === 'golden' && gpNow.doorOnly === false, 'after sdSeasonEnd: placement kept, doorOnly false'); await api('/api/admin/rates', { method: 'PATCH', data: { sdSeasonEnd: '2026-11-01' } }, adminH); } catch (e) { fails++; console.log('FAIL exception: ' + e.message + '\n' + (e.stack || '').split('\n').slice(1, 3).join('\n')); } finally { cleanup(); } console.log(fails ? '\n' + fails + ' failure(s)' : '\nall door checks passed'); process.exit(fails ? 1 : 0);