// My Stack POL checks (2026-11-19): node qa/my.test.mjs // No network, no production data: boots server.js twice on a temp DATA_DIR (no DOCSTORE_URL) with a stand-in hub and a stand-in // InstantAdPay switch interface. Checks: the silent check and the "not signed in anywhere" answer, the hub sign-in callback (a good // token signs in, a replayed or wrong-state or wrong-key token does not), /my for a member with a live page + Pro + payouts, one switched // off with payouts, one with nothing yet, the switch (IAP gets the signed call, /my and the public page follow at once, a cross-site // post is refused), the copy of IAP's switch when the interface is off (a link to Promo tools, the state from the snapshot), the // wallet match when the network username differs, sign-out (the old cookie stops working) and the public pages without a sign-in. import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import http from 'node:http'; import crypto from 'node:crypto'; import { spawn } from 'node:child_process'; const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); let pass = 0, fail = 0; const ok = (c, m) => { if (c) pass++; else { fail++; console.log('FAIL', m); } }; const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36'; const HUB_SECRET = crypto.randomBytes(24).toString('hex'), SWITCH_KEY = crypto.randomBytes(24).toString('hex'); const W = { a1: '0x' + 'a1'.repeat(20), a2: '0x' + 'a2'.repeat(20), b1: '0x' + 'b1'.repeat(20) }; const TX = n => '0x' + String(n).repeat(64).slice(0, 64); // ---- the snapshot the indexer would push (tools/indexer.py shape, `my` included) const now = Date.now(); const aliceRows = [{ k: 'iap', pol: 12.5, tx: TX(1), ts: now - 3600e3 }, { k: 'ph', pol: 0.3333, tx: TX(2), ts: now - 7200e3 }, { k: 'iap', pol: 1, tx: TX(3), ts: now - 86400e3 }]; const bobRows = [{ k: 'ls', pol: 4.25, tx: TX(4), ts: now - 5000e3 }]; const snap = { v: 1, at: now - 60e3, network: { pol: 18.0833, payments: 4, wallets: 2 }, last7: { pol: 18.0833, payments: 4 }, programs: { iap: { pol: 13.5, payments: 2, wallets: 1 }, ph: { pol: 0.3333, payments: 1, wallets: 1 }, ls: { pol: 4.25, payments: 1, wallets: 1 } }, recent: aliceRows.map(r => Object.assign({ u: 'alice', pub: true }, r)).concat(bobRows.map(r => Object.assign({ u: 'bob', pub: false }, r))), progRecent: {}, stacks: { alice: { total: 13.8333, payments: 3, since: now - 86400e3, byProg: { iap: { pol: 13.5, payments: 2 }, ph: { pol: 0.3333, payments: 1 } }, recent: aliceRows, pro: { spins: [], links: [{ code: 'abc123', name: 'My offer' }] } } }, my: { members: { alice: { total: 13.8333, payments: 3, since: now - 86400e3, byProg: { iap: { pol: 13.5, payments: 2 }, ph: { pol: 0.3333, payments: 1 } }, rows: aliceRows, wallets: [W.a1, W.a2], page: true }, bob: { total: 4.25, payments: 1, since: now - 5000e3, byProg: { ls: { pol: 4.25, payments: 1 } }, rows: bobRows, wallets: [W.b1], page: false } }, switch: { bob: false }, pro: ['alice'] } }; // ---- stand-in hub: /sso/check answers for whoever `hubUser` is let hubUser = null; const hubCalls = []; const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); function hubToken(o, secret) { const t = { iss: 'hub', aud: o.aud || 'stackpol', to: o.to || '/my', iat: o.iat || Date.now(), exp: (o.iat || Date.now()) + 60000, n: crypto.randomBytes(16).toString('hex'), email: o.email, st: o.st }; if (o.wallet) t.wallet = o.wallet; if (o.name) t.name = o.name; const body = b64u(JSON.stringify(t)); return 'h1.' + body + '.' + b64u(crypto.createHmac('sha256', secret || HUB_SECRET).update('hubsso.v1.' + body).digest()); } let SP = ''; // the Stack POL base the hub sends people back to (set per server) const hub = http.createServer((req, res) => { let raw = ''; req.on('data', c => { raw += c; }); req.on('end', () => { const u = new URL(req.url, 'http://x'); hubCalls.push(u.pathname); const send = (code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); }; if (u.pathname === '/health') return send(200, { ok: true }); if (u.pathname === '/sso/check') { const st = u.searchParams.get('st'), to = u.searchParams.get('to') || '/', m = u.searchParams.get('m') === 'go' ? 'go' : 'check'; const loc = hubUser ? SP + '/sso/in?h=' + hubToken(Object.assign({ st, to }, hubUser)) : SP + '/sso/in?none=1&hub=1&m=' + m + '&to=' + encodeURIComponent(to); res.writeHead(302, { Location: loc }); return res.end(); } if (u.pathname === '/sso/set') { res.writeHead(302, { Location: SP + '/' }); return res.end(); } if (u.pathname === '/v1/sso/signout') return send(200, { ok: true, ended: 1 }); return send(404, { error: 'not here' }); }); }); await new Promise(r => hub.listen(0, '127.0.0.1', r)); const HUB = 'http://127.0.0.1:' + hub.address().port; // ---- stand-in InstantAdPay: the switch interface iapswitch.js documents const iap = { 'alice@example.com': { un: 'alice', on: true, pro: true }, 'bob@example.com': { un: 'bob', on: false, pro: false }, 'carol@example.com': { un: 'carol', on: true, pro: false } }; const iapCalls = []; let iapDown = false; const iapSrv = http.createServer((req, res) => { let raw = ''; req.on('data', c => { raw += c; }); req.on('end', () => { const send = (code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); }; if (req.url !== '/api/partner/stackpol/switch' || req.method !== 'POST') return send(404, { error: 'no' }); if (iapDown) return send(503, { error: 'down' }); const ts = String(req.headers['x-stack-ts'] || ''), sig = String(req.headers['x-stack-sig'] || ''); const want = crypto.createHmac('sha256', SWITCH_KEY).update(ts + '\n' + raw).digest('hex'); if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want)) || Math.abs(Date.now() - Number(ts)) > 300000) return send(401, { error: 'bad signature' }); const b = JSON.parse(raw); const a = iap[b.email]; iapCalls.push(b); if (!a) return send(404, { error: 'no account' }); if (typeof b.on === 'boolean') a.on = b.on; return send(200, { on: a.on, username: a.un, pro: a.pro }); }); }); await new Promise(r => iapSrv.listen(0, '127.0.0.1', r)); const IAP = 'http://127.0.0.1:' + iapSrv.address().port; // ---- boot a Stack POL server on its own temp data dir const kids = []; async function boot(extra) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'stackpol-my-')); fs.writeFileSync(path.join(dir, 'stack-index.json'), JSON.stringify(Object.assign({}, snap, { at: undefined }))); fs.writeFileSync(path.join(dir, 'stack-index-at.json'), JSON.stringify({ at: snap.at })); const port = 20000 + Math.floor(Math.random() * 20000); const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, SITE_URL: 'http://127.0.0.1:' + port, HUB_SSO: 'on', HUB_URL: HUB, HUB_SECRET, HUB_SITE: 'stackpol', NETKB: '0', HUB_ACTIVITY: '0', IAP_URL: IAP, STACK_INGEST_KEY: 'test-ingest-key' }, extra || {}); delete env.DOCSTORE_URL; delete env.NETWORK_SSO_SECRET; delete env.OPENROUTER_API_KEY; for (const k of Object.keys(extra || {})) if (extra[k] == null) delete env[k]; const kid = spawn(process.execPath, [path.join(ROOT, 'server.js')], { env, stdio: ['ignore', 'pipe', 'pipe'] }); kids.push(kid); let log = ''; kid.stdout.on('data', d => { log += d; }); kid.stderr.on('data', d => { log += d; }); const base = 'http://127.0.0.1:' + port; for (let i = 0; i < 100; i++) { try { const r = await fetch(base + '/health'); if (r.ok) break; } catch (e) {} await new Promise(r => setTimeout(r, 100)); } return { base, dir, log: () => log }; } // ---- a browser: one cookie jar for the Stack POL server, follows redirects across the stand-ins function browser(base) { const jar = new Map(); const cookieHeader = () => [...jar].map(([k, v]) => k + '=' + v).join('; '); const take = r => { for (const c of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv, ...attrs] = c.split(';'); const i = kv.indexOf('='); const k = kv.slice(0, i).trim(), v = kv.slice(i + 1).trim(); const age = attrs.map(a => a.trim()).find(a => /^max-age=/i.test(a)); if (age && Number(age.split('=')[1]) <= 0) jar.delete(k); else jar.set(k, v); } }; async function go(url, opts) { opts = opts || {}; let hops = []; let r; for (let i = 0; i < 12; i++) { const mine = url.startsWith(base); const headers = Object.assign({ 'User-Agent': UA }, opts.headers || {}); if (mine && jar.size) headers.Cookie = cookieHeader(); r = await fetch(url, { method: i === 0 ? opts.method || 'GET' : 'GET', headers, body: i === 0 ? opts.body : undefined, redirect: 'manual' }); if (mine) take(r); hops.push(r.status + ' ' + url.replace(base, '').replace(HUB, 'HUB').slice(0, 90)); const loc = r.headers.get('location'); if (!loc || r.status < 300 || r.status >= 400 || opts.noFollow) break; url = new URL(loc, url).toString(); } const text = await r.text(); return { status: r.status, text, url, hops, location: r.headers.get('location') }; } const post = (p, form, headers) => go(base + p, { method: 'POST', body: new URLSearchParams(form).toString(), headers: Object.assign({ 'Content-Type': 'application/x-www-form-urlencoded', Origin: base }, headers || {}) }); return { go, post, jar }; } const signIn = async (b, who) => { hubUser = who; const r = await b.go(SP + '/sso/start?mode=go&to=%2Fmy'); hubUser = null; return r; }; try { // ===== server 1: hub sign-in + the switch interface on const s1 = await boot({ STACKPOL_SWITCH_KEY: SWITCH_KEY }); SP = s1.base; // signed out: one silent check, then the sign-in page saying this browser is not signed in anywhere const anon = browser(s1.base); let r = await anon.go(s1.base + '/my'); ok(r.hops[0].startsWith('303 /my'), 'signed-out /my starts one silent check: ' + r.hops[0]); ok(r.hops.some(h => h.includes('HUB/sso/check')), 'the silent check goes through the hub'); ok(r.status === 200 && /signin=none/.test(r.url), 'nobody on the hub: back to /my?signin=none (' + r.url + ')'); ok(/Sign in with your network account/.test(r.text) && /not signed in anywhere in the network/.test(r.text), 'sign-in page with the not-signed-in note'); ok(/href="\/sso\/start\?mode=go&to=%2Fmy"/.test(r.text), 'the sign-in button starts a deliberate hub sign-in'); r = await anon.go(s1.base + '/my'); ok(r.hops.length === 1 && r.status === 200, 'no second silent check (loop guard)'); ok(!anon.jar.has('sp.sid'), 'no session without a sign-in'); // sign-in callback: alice const alice = browser(s1.base); r = await signIn(alice, { email: 'alice@example.com', wallet: W.a1, name: 'alice' }); ok(r.status === 200 && r.url === s1.base + '/my', 'alice lands on /my after the hub sign-in (' + r.hops.join(' > ') + ')'); ok(alice.jar.has('sp.sid') && alice.jar.get('sp.in') === '1', 'session cookie + header hint set'); ok(/@alice/.test(r.text), '/my names @alice'); ok(/On<\/span>/.test(r.text) && /Live now/.test(r.text), 'page switch shows On and live'); ok(r.text.includes('value="' + s1.base + '/alice"'), 'page link ready to copy'); ok(/Pro<\/span>/.test(r.text) && /1 spin link/.test(r.text), 'Pro status shown with what is on the page'); ok(r.text.includes('value="https://instantadpay.com/join/alice"') && r.text.includes('value="https://linkspin.app/join/alice"'), 'join links carry alice'); ok(r.text.includes('instantadpay.com/g/polhunter?ref=alice') || r.text.includes('ref=alice'), 'game join links carry alice'); ok(r.text.includes('13.83') && r.text.includes('>3payments'), 'payout total 13.83 POL in 3 payments, as the ledger has it'); ok(r.text.includes('polygonscan.com/tx/' + TX(1)) && r.text.includes('polygonscan.com/tx/' + TX(3)), 'payout rows link to Polygonscan'); ok(!r.text.includes(TX(4)), "bob's payout is not on alice's page"); ok(r.text.includes('polygonscan.com/address/' + W.a2), 'both of alice\'s wallets listed'); ok(/\/qr\/alice\.svg/.test(r.text) && /og-stackpol-1200x630\.jpg/.test(r.text), 'share kit: QR (Pro) and the share image'); ok(/Switch my page off/.test(r.text) && /same switch as InstantAdPay Promo tools/.test(r.text), 'the switch is there'); ok(!/[–—]/.test(r.text), 'no em or en dashes on /my'); // the callback refuses a replayed token, a wrong state and a token signed with another key { const st = crypto.randomBytes(16).toString('hex'); const evil = browser(s1.base); await evil.go(s1.base + '/sso/start?mode=go&to=%2Fmy', { noFollow: true }); // gets a real state cookie const real = evil.jar.get('nsso.st'); const good = hubToken({ email: 'alice@example.com', st: real }); r = await evil.go(s1.base + '/sso/in?h=' + good, { noFollow: true }); ok(r.status === 302 && r.location === '/my' && evil.jar.has('sp.sid'), 'a good token signs in'); const ev2 = browser(s1.base); await ev2.go(s1.base + '/sso/start?mode=go&to=%2Fmy', { noFollow: true }); ev2.jar.set('nsso.st', real); r = await ev2.go(s1.base + '/sso/in?h=' + good, { noFollow: true }); ok(!ev2.jar.has('sp.sid'), 'the same token a second time is refused'); const ev3 = browser(s1.base); await ev3.go(s1.base + '/sso/start?mode=go&to=%2Fmy', { noFollow: true }); r = await ev3.go(s1.base + '/sso/in?h=' + hubToken({ email: 'alice@example.com', st }), { noFollow: true }); ok(!ev3.jar.has('sp.sid'), 'a token for another state is refused'); const ev4 = browser(s1.base); await ev4.go(s1.base + '/sso/start?mode=go&to=%2Fmy', { noFollow: true }); r = await ev4.go(s1.base + '/sso/in?h=' + hubToken({ email: 'alice@example.com', st: ev4.jar.get('nsso.st') }, crypto.randomBytes(24).toString('hex')), { noFollow: true }); ok(!ev4.jar.has('sp.sid'), 'a token signed with another key is refused'); const ev5 = browser(s1.base); ev5.jar.set('sp.sid', 'v1.' + b64u(JSON.stringify({ e: 'alice@example.com', iat: Date.now(), exp: Date.now() + 1e6 })) + '.' + b64u(crypto.randomBytes(32))); r = await ev5.go(s1.base + '/my?signin=none'); ok(!/@alice/.test(r.text), 'a forged session cookie is not a session'); } // the switch: off from Stack POL, IAP gets it, /my and the public page follow at once ok((await fetch(s1.base + '/alice')).status === 200, 'alice public page is up before the switch'); const before = iapCalls.length; r = await alice.post('/api/my/switch', { on: '0' }); ok(/sw=ok/.test(r.url) && iapCalls.length > before && iapCalls.some(c => c.email === 'alice@example.com' && c.on === false), 'switch off sent to IAP signed (' + r.url + ')'); ok(iap['alice@example.com'].on === false, 'IAP now has alice off'); ok(/Off<\/span>/.test(r.text) && /Switched off/.test(r.text) && /Switch my page on/.test(r.text), '/my shows Off'); ok((await fetch(s1.base + '/alice')).status === 404, 'public page hidden right away'); ok((await fetch(s1.base + '/qr/alice.svg')).status === 404, 'QR hidden with it'); r = await alice.post('/api/my/switch', { on: '1' }); ok(iap['alice@example.com'].on === true && /pill on">On/.test(r.text), 'switch back on'); ok((await fetch(s1.base + '/alice')).status === 200, 'public page back'); // a switch made in IAP itself shows on /my (one place for the switch) iap['alice@example.com'].on = false; r = await alice.go(s1.base + '/my'); ok(/pill off">Off/.test(r.text), 'a switch made in IAP shows on /my'); iap['alice@example.com'].on = true; // cross-site post refused; IAP down = nothing changed, said so r = await alice.post('/api/my/switch', { on: '0' }, { Origin: 'https://evil.example' }); ok(r.status === 403 && iap['alice@example.com'].on === true, 'cross-site switch refused'); iapDown = true; r = await alice.post('/api/my/switch', { on: '0' }); iapDown = false; ok(/sw=err/.test(r.url) && /did not go through/.test(r.text), 'IAP down: switch error shown, nothing changed'); ok((await fetch(s1.base + '/alice')).status === 200, 'IAP down: public page untouched'); const nobody = browser(s1.base); r = await nobody.post('/api/my/switch', { on: '0' }); ok(iap['alice@example.com'].on === true, 'no session: no switch'); // bob: switched off, has payouts, no Pro const bob = browser(s1.base); r = await signIn(bob, { email: 'bob@example.com', wallet: W.b1, name: 'bob' }); ok(/@bob/.test(r.text) && /pill off">Off/.test(r.text) && /Switch my page on/.test(r.text), 'bob: page Off, switch offered'); ok(/pill off">Not yet/.test(r.text) && /\$10 or more/.test(r.text), 'bob: not Pro, how Pro unlocks'); ok(r.text.includes('4.25') && r.text.includes('polygonscan.com/tx/' + TX(4)) && !r.text.includes(TX(1)), 'bob: his own payouts only'); ok((await fetch(s1.base + '/bob')).status === 404, 'bob: no public page'); // carol: nothing yet const carol = browser(s1.base); r = await signIn(carol, { email: 'carol@example.com', name: 'carol' }); ok(/@carol/.test(r.text) && /goes live with your first payout/.test(r.text) && /No payouts on the ledger for @carol yet/.test(r.text), 'carol: no page yet, no payouts yet'); ok(r.text.includes('value="https://instantadpay.com/join/carol"'), 'carol: join links ready'); ok(!/\/qr\/carol\.svg/.test(r.text), 'carol: no QR (not Pro)'); // sign out: cookies cleared, the old cookie stops working, no silent re-sign-in const oldSid = alice.jar.get('sp.sid'); r = await alice.post('/api/my/signout', {}); ok(/\/my\?out=1$/.test(r.url) && /You are signed out of Stack POL/.test(r.text), 'sign-out lands on the signed-out page'); ok(!alice.jar.has('sp.sid') && !alice.jar.has('sp.in') && alice.jar.get('nsso.off') === '1', 'session and header hint cleared, silent check paused'); const thief = browser(s1.base); thief.jar.set('sp.sid', oldSid); r = await thief.go(s1.base + '/my?signin=none'); ok(!/@alice/.test(r.text) && /Sign in with your network account/.test(r.text), 'the cookie from before the sign-out no longer works'); r = await alice.go(s1.base + '/my'); ok(r.hops.length === 1 && !/@alice/.test(r.text), 'after sign-out /my does not sign back in by itself'); r = await bob.post('/api/my/signout', { everywhere: '1' }); ok(hubCalls.includes('/v1/sso/signout'), 'sign out of the whole network asks the hub'); // public pages: no sign-in needed, header entry in the site look for (const p of ['/', '/ledger', '/programs', '/blog', '/earn/instantadpay']) { const x = await fetch(s1.base + p); const t = await x.text(); ok(x.status === 200 && /id="spmy" href="\/my"[^>]*>Sign in<\/a>/.test(t), p + ' is public and has the Sign in entry'); } const robots = await (await fetch(s1.base + '/robots.txt')).text(); ok(/Disallow: \/my/.test(robots), 'robots keeps /my out'); // ===== server 2: no switch interface (IAP not changed yet): /my links to Promo tools; wallet match when the network name differs const s2 = await boot({ STACKPOL_SWITCH_KEY: null }); SP = s2.base; const b2 = browser(s2.base); r = await signIn(b2, { email: 'bob@example.com', wallet: W.b1, name: 'bobby' }); ok(/@bob\b/.test(r.text) && !/@bobby/.test(r.text), 'wallet match: the network name bobby resolves to the Stack POL member bob'); ok(/pill off">Off/.test(r.text), 'state from the snapshot: bob switched off in IAP'); ok(/Change it in InstantAdPay/.test(r.text) && r.text.includes(IAP + '/my#promo?s=stackpol') && !/Switch my page on/.test(r.text), 'no interface: a link to IAP Promo tools, no switch button'); const calls = iapCalls.length; r = await b2.post('/api/my/switch', { on: '1' }); ok(/sw=err/.test(r.url) && iapCalls.length === calls, 'no interface: a post changes nothing and calls nobody'); const a2 = browser(s2.base); r = await signIn(a2, { email: 'alice@example.com', wallet: W.a2, name: 'alice' }); ok(/pill on">On/.test(r.text) && /pill on">Pro/.test(r.text), 'no interface: alice On + Pro from the snapshot'); const n2 = browser(s2.base); r = await signIn(n2, { email: 'new@example.com', name: 'new.person' }); ok(/Pick a username first/.test(r.text), 'no Stack POL username: asked to pick one in IAP'); // ingest still works and keeps `my` const ing = await fetch(s2.base + '/api/ingest', { method: 'POST', headers: { Authorization: 'Bearer test-ingest-key', 'Content-Type': 'application/json' }, body: JSON.stringify(Object.assign({}, snap, { at: Date.now() })) }); ok(ing.status === 200, 'ingest accepts the snapshot with `my`'); r = await a2.go(s2.base + '/my'); ok(/13\.83/.test(r.text), '/my reads the pushed snapshot'); } catch (e) { fail++; console.log('FAIL threw', e.stack); } finally { for (const k of kids) k.kill(); hub.close(); iapSrv.close(); } console.log(pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);