// 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: 'πŸŒ™', 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. 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)); // 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'); 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=', 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'); } 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);