// My Stack POL (Marty approved 2026-11-19: "why is there no login to get to their links and other stuff"). The signed-in member area // at /my. Sign-in is the network sign-in through the hub (networksso.js, the same file as every rebuilt site): no passwords, no local // accounts. Public pages, the ledger, totals and the blog never need it. // // Session: a signed cookie sp.sid ("v1..", 7 days, HttpOnly, SameSite=Lax) keyed off // HUB_SECRET, so there is no session table to lose. Sign out ends every Stack POL session of that member: my-signouts.json // { sha256(email): ms } (a MySQL document through docstore.js) refuses any cookie issued before it. sp.in=1 (not HttpOnly, no data) // only tells the header to say "My Stack POL" instead of "Sign in" on cached public pages. // Who the member is here: their IAP username (what stackpol.com/ and the ledger use). IAP's own answer when the switch // interface is on (iapswitch.js), else the wallet their network sign-in carries matched against the indexer's wallet list, else their // network username. // What /my shows comes from the last indexer snapshot (IDX.my, see tools/indexer.py): their own payout rows and totals exactly as the // ledger has them, their page switch, Pro (IAP's rule, mirrored in stack-optin.json pro), and their join links (programs.js, the same // links their public page uses). // The switch: iapswitch.js. A switch made here is also remembered in my-switch.json { username: { on, at } } until the next snapshot // (newer than `at`) carries IAP's answer, so a switch-off hides the public page at once, not 5 minutes later. 'use strict'; const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const iapswitch = require('./iapswitch'); let D = null; // { idx(), PROGRAMS, BY_KEY, head, tail, esc, fmt, fmtInt, when, ledgerRows, tableHead, SITE, dataDir, qr } const AGE = 7 * 86400; // seconds const NAME_RE = /^[a-z0-9_]{3,30}$/; const WALLET_RE = /^0x[0-9a-f]{40}$/; const BOOT_KEY = crypto.randomBytes(32); // local runs without HUB_SECRET: sessions last until a restart const skey = () => { const h = String(process.env.HUB_SECRET || '').trim(); return h.length >= 32 ? crypto.createHmac('sha256', h).update('stackpol.session.v1').digest() : BOOT_KEY; }; const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64'); const mac = s => crypto.createHmac('sha256', skey()).update('spsess.v1.' + s).digest(); const ehash = e => crypto.createHash('sha256').update(String(e || '').toLowerCase()).digest('hex'); const isProd = () => /^https:/.test(D ? D.SITE : ''); const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (isProd() ? '; Secure' : ''); function init(deps) { D = deps; } function cookies(req) { const out = {}; for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } return out; } // ---- documents (MySQL through docstore, files in DATA_DIR locally) ---- const docPath = n => path.join(D.dataDir, n); function readDoc(n) { try { return JSON.parse(fs.readFileSync(docPath(n), 'utf8')) || {}; } catch (e) { return {}; } } function writeDoc(n, o) { const f = docPath(n); fs.writeFileSync(f + '.tmp', JSON.stringify(o)); fs.renameSync(f + '.tmp', f); } // ---- session ---- function mintSession(o) { const now = Date.now(); const t = { e: String(o.email || '').toLowerCase(), iat: now, exp: now + AGE * 1000 }; if (o.wallet && WALLET_RE.test(String(o.wallet).toLowerCase())) t.w = String(o.wallet).toLowerCase(); if (o.name && /^[A-Za-z0-9_.-]{1,40}$/.test(String(o.name))) t.n = String(o.name); const body = b64u(JSON.stringify(t)); return ck('sp.sid', 'v1.' + body + '.' + b64u(mac(body)), AGE, true); } // -> { email, address, name, iat } or null function session(req) { const m = /^v1\.([A-Za-z0-9_-]{10,1500})\.([A-Za-z0-9_-]{43})$/.exec(cookies(req)['sp.sid'] || ''); if (!m) return null; const want = mac(m[1]), got = unb64u(m[2]); if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return null; let t; try { t = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return null; } if (!t || !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(t.e || '')) || !(Number(t.exp) > Date.now())) return null; const out = Number(readDoc('my-signouts.json')[ehash(t.e)] || 0); if (Number(t.iat) <= out) return null; // signed out after this cookie was made return { email: t.e, address: t.w || null, name: t.n || null, iat: Number(t.iat) }; } function signOut(email) { const so = readDoc('my-signouts.json'); so[ehash(email)] = Date.now(); writeDoc('my-signouts.json', so); } const clearCookies = () => [ck('sp.sid', '', 0, true), ck('sp.in', '', 0, false)]; // ---- who and what ---- let wIdx = { of: null, map: new Map() }; function walletUser(w) { const idx = D.idx(); if (!idx || !w) return null; if (wIdx.of !== idx) { const map = new Map(); for (const [un, m] of Object.entries((idx.my && idx.my.members) || {})) for (const a of m.wallets || []) if (!map.has(a)) map.set(a, un); wIdx = { of: idx, map }; } return wIdx.map.get(String(w).toLowerCase()) || null; } // the switch made on /my that the snapshot has not caught up with yet (null when the snapshot is newer) function pendingSwitch(un) { const x = readDoc('my-switch.json')[un]; const idx = D.idx(); if (!x || typeof x.on !== 'boolean') return null; if (idx && Number(idx.at) > Number(x.at)) return null; return x; } // a public page the member switched off here: hidden before the next snapshot shows it (server.js asks) const hiddenNow = un => { const x = pendingSwitch(un); return !!(x && x.on === false); }; async function view(s) { const idx = D.idx() || {}; const my = idx.my || {}; const live = iapswitch.configured() ? await iapswitch.get(s.email) : { ok: false, reason: 'off' }; const byName = s.name && NAME_RE.test(String(s.name).toLowerCase()) ? String(s.name).toLowerCase() : null; const un = (live.ok && live.username) || walletUser(s.address) || byName; if (!un) return { un: null, live }; const m = (my.members || {})[un] || null; const stack = (idx.stacks || {})[un] || null; const pend = pendingSwitch(un); const explicit = (my.switch || {})[un]; const on = live.ok ? live.on : pend ? pend.on : explicit !== false; const pro = live.ok ? live.pro : (my.pro || []).includes(un) || !!(stack && stack.pro); const pageLive = on && !!stack && !(pend && pend.on === false); return { un, m, stack, on, pro, pageLive, live, pend, wallets: m && m.wallets && m.wallets.length ? m.wallets : (s.address ? [s.address] : []) }; } // ---- the page ---- const COPY_JS = ''; const copyRow = (id, value, label) => '
' + (label ? '' : '') + '
'; function signedOutPage(q) { let h = D.head({ title: 'My Stack POL: Sign In | Stack POL', desc: 'Sign in with your network account to see your Stack POL page, your join links and your own payouts.', path: '/my', nav: '/my', noindex: true }); h += '

My Stack POL

Your page, your links, your payouts

' + '

Sign in with the account you already use across the network (InstantAdPay, LinkSpin and the rest). No new password, nothing to set up.

'; if (q.out) h += '

You are signed out of Stack POL.

'; if (q.signin === 'none') h += '

This browser is not signed in anywhere in the network yet. Sign in on InstantAdPay and it brings you straight back here.

'; h += '' + '

New here? Join InstantAdPay free. Your Stack POL page lives at stackpol.com/your-username once your first payout lands.

'; return h + D.tail(); } function memberPage(s, v, q) { const { esc, fmt, fmtInt, PROGRAMS, BY_KEY } = D; let h = D.head({ title: 'My Stack POL | Stack POL', desc: 'Your Stack POL page, join links, share kit and payouts.', path: '/my', nav: '/my', noindex: true }); const un = v.un; h += '
' + esc((un || s.email)[0].toUpperCase()) + '
' + (un ? '@' + esc(un) : 'Signed in') + 'Signed in with your network account
' + '
'; if (q.sw === 'err') h += '

That switch did not go through. InstantAdPay did not answer; nothing changed. Try again in a minute, or use the switch in InstantAdPay Promo tools.

'; if (q.sw === 'ok') h += '

Saved in InstantAdPay. Your page ' + (v.on ? 'is switched on' : 'is switched off') + '.

'; h += '
'; if (!un) { h += '

Pick a username first

Your Stack POL page lives at stackpol.com/your-username, the username on your InstantAdPay account. This account does not have one we can see yet.

'; return h + D.tail(); } const pageUrl = D.SITE + '/' + un; const m = v.m; // 1. the page and its switch h += '

Your Stack POL page

' + (v.on ? 'On' : 'Off') + '
'; h += copyRow('pageurl', pageUrl); if (v.pageLive) h += '

Live now. Open your page

'; else if (!v.on) h += '

Switched off: stackpol.com/' + esc(un) + ' shows "not switched on" and the ledger lists your payouts without a link.

'; else if (!m) h += '

Switched on. Your page goes live with your first payout on the ledger.

'; else h += '

Switched on. Your page shows on the next ledger refresh (every 5 minutes).

'; if (iapswitch.configured()) { h += '
' + '

This is the same switch as InstantAdPay Promo tools > Stack POL. Change it in either place.' + (v.live.ok ? '' : ' (InstantAdPay did not answer just now; the state shown is from the last ledger refresh.)') + '

'; } else { h += '

The switch lives in InstantAdPay Promo tools > Stack POL. The state shown is from the last ledger refresh.

'; } h += '
'; // 2. Pro h += '

Stack POL Pro

' + (v.pro ? 'Pro' : 'Not yet') + '
'; if (v.pro) { const pr = v.stack && v.stack.pro; h += '

Your page shows your own LinkSpin Banner Spins in the ad spots and your spin links, with your QR code. Any page opened with ?ref=' + esc(un) + ' carries your referral.

'; if (pr) h += '

On your page now: ' + fmtInt((pr.spins || []).length) + ' Banner Spin' + ((pr.spins || []).length === 1 ? '' : 's') + ', ' + fmtInt((pr.links || []).length) + ' spin link' + ((pr.links || []).length === 1 ? '' : 's') + '. Manage them in LinkSpin

'; h += copyRow('refurl', D.SITE + '/?ref=' + un, 'Any Stack POL page with your referral'); } else { h += '

Pro unlocks one time with any InstantAdPay ad package of $10 or more: your banners in the ad spots, your links and your QR code on your page.

'; } h += '
'; // 3. join links h += '

Your join links

The same links your public page uses. Each one credits you.

'; // 4. share kit const share = 'Every POL payout I have stacked across the network, each one a Polygon transaction you can check: ' + pageUrl; h += '

Share kit

Your page link, a ready post and the Stack POL images.

'; h += '
' + copyRow('kurl', pageUrl, 'Your page') + '
' + copyRow('kembed', 'Stack POL: every POL payout, stacked', 'Banner code for a site or blog') + (v.pro && D.qr ? '
QR code for your pageYour QR code. Download
' : '') + '
'; h += '
' + [['/og-stackpol-1200x630.jpg', 'Share image 1200x630', 'stackpol-share-1200x630.jpg'], ['/stackpol-hero-poster.jpg', 'Coin stack still', 'stackpol-coins.jpg']] .map(([src, label, fn]) => '
' + esc(label) + '
' + esc(label) + ' Download
').join('') + '
'; // 5. payouts h += '

Your payouts

From the Stack POL ledger, your wallet' + (v.wallets.length === 1 ? '' : 's') + ' only.' + (D.idx() && D.idx().at ? ' Refreshed ' + D.when(D.idx().at) + '.' : '') + '

'; if (!m) { h += '

No payouts on the ledger for @' + esc(un) + ' yet. Payouts from any program in the network show here within 5 minutes of landing in your wallet.

'; } else { const ps = PROGRAMS.filter(p => m.byProg[p.k]).sort((a, b) => m.byProg[b.k].pol - m.byProg[a.k].pol); h += '
' + fmt(m.total) + 'POL
' + fmtInt(m.payments) + 'payments
' + fmtInt(ps.length) + 'programs
' + (m.since ? '
' + new Date(m.since).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'America/Chicago' }) + 'first payout
' : '') + '
' + '
' + ps.map(p => '' + esc(p.n) + ' ' + fmt(m.byProg[p.k].pol) + '').join('') + '
' + (v.wallets.length ? '

Wallet' + (v.wallets.length === 1 ? '' : 's') + ': ' + v.wallets.map(w => '' + esc(w.slice(0, 6) + '…' + w.slice(-4)) + ' ↗').join(' ') + '

' : '') + '
'; const rows = m.rows || []; h += D.tableHead(false) + D.ledgerRows(rows, false) + ''; if (rows.length < m.payments) h += '

Showing your latest ' + fmtInt(rows.length) + ' of ' + fmtInt(m.payments) + ' payments. Every one is on Polygonscan under your wallet.

'; } h += '
'; return h + D.tail(COPY_JS); } async function render(req, q) { const s = session(req); if (!s) return { body: signedOutPage(q), set: cookies(req)['sp.in'] ? clearCookies() : [] }; const v = await view(s); return { body: memberPage(s, v, q), set: cookies(req)['sp.in'] === '1' ? [] : [ck('sp.in', '1', AGE, false)] }; } // POST /api/my/switch (form: on=1|0). -> { ok, on } or { ok: false, reason } async function doSwitch(s, on) { if (!iapswitch.configured()) return { ok: false, reason: 'off' }; const r = await iapswitch.set(s.email, on); if (!r.ok) return r; const un = r.username; if (!un) return { ok: false, reason: 'no username' }; const doc = readDoc('my-switch.json'); doc[un] = { on: r.on, at: Date.now() }; writeDoc('my-switch.json', doc); return { ok: true, on: r.on, username: un }; } module.exports = { init, session, mintSession, signOut, clearCookies, render, doSwitch, hiddenNow, view, cookies, NAME_RE };