Files
stackpol/my.js
T

211 lines
19 KiB
JavaScript

// 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.<base64url JSON {e, w, n, iat, exp}>.<HMAC-SHA256>", 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/<username> 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 = '<script>(function(){document.querySelectorAll("[data-copy]").forEach(function(b){b.addEventListener("click",function(){var t=document.getElementById(b.getAttribute("data-copy"));if(!t)return;var v=t.value||t.textContent;var done=function(){var o=b.textContent;b.textContent="Copied";setTimeout(function(){b.textContent=o;},1600);};if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(v).then(done,function(){t.select&&t.select();document.execCommand("copy");done();});}else{t.select&&t.select();document.execCommand("copy");done();}});});})();</script>';
const copyRow = (id, value, label) => '<div class="cprow">' + (label ? '<label for="' + id + '">' + D.esc(label) + '</label>' : '') + '<div class="cpbox"><input id="' + id + '" type="text" readonly value="' + D.esc(value) + '" spellcheck="false"><button type="button" class="cpb" data-copy="' + id + '">Copy</button></div></div>';
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 += '<section class="myhero"><p class="kick">My Stack POL</p><h1>Your page, your links, your payouts</h1>'
+ '<p class="lead">Sign in with the account you already use across the network (InstantAdPay, LinkSpin and the rest). No new password, nothing to set up.</p>';
if (q.out) h += '<p class="mynote ok">You are signed out of Stack POL.</p>';
if (q.signin === 'none') h += '<p class="mynote">This browser is not signed in anywhere in the network yet. Sign in on InstantAdPay and it brings you straight back here.</p>';
h += '<div class="cta"><a class="btn" href="/sso/start?mode=go&amp;to=%2Fmy" rel="nofollow">Sign in with your network account</a>'
+ '<a class="btn sec" href="https://instantadpay.com/my?return=stackpol&amp;to=%2Fmy" rel="nofollow noopener">Sign in on InstantAdPay</a></div>'
+ '<p class="fine" style="max-width:60ch;margin-top:16px">New here? <a href="https://instantadpay.com/join/martbost?src=stackpol" rel="noopener">Join InstantAdPay free</a>. Your Stack POL page lives at stackpol.com/your-username once your first payout lands.</p></section>';
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 += '<section class="myhero"><div class="myhead"><div class="who"><span class="av">' + esc((un || s.email)[0].toUpperCase()) + '</span><div><b>' + (un ? '@' + esc(un) : 'Signed in') + '</b><span>Signed in with your network account</span></div></div>'
+ '<form method="post" action="/api/my/signout" class="soform"><button class="btn sec" type="submit">Sign out</button></form></div>';
if (q.sw === 'err') h += '<p class="mynote warn">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.</p>';
if (q.sw === 'ok') h += '<p class="mynote ok">Saved in InstantAdPay. Your page ' + (v.on ? 'is switched on' : 'is switched off') + '.</p>';
h += '</section>';
if (!un) {
h += '<section class="mycard"><h2>Pick a username first</h2><p class="lead">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.</p><div class="cta"><a class="btn" href="https://instantadpay.com/my" rel="noopener">Open InstantAdPay</a></div></section>';
return h + D.tail();
}
const pageUrl = D.SITE + '/' + un;
const m = v.m;
// 1. the page and its switch
h += '<div class="mygrid"><section class="mycard"><div class="mct"><h2>Your Stack POL page</h2><span class="pill ' + (v.on ? 'on' : 'off') + '">' + (v.on ? 'On' : 'Off') + '</span></div>';
h += copyRow('pageurl', pageUrl);
if (v.pageLive) h += '<p class="mysub">Live now. <a href="/' + esc(un) + '" target="_blank" rel="noopener">Open your page</a></p>';
else if (!v.on) h += '<p class="mysub">Switched off: stackpol.com/' + esc(un) + ' shows "not switched on" and the ledger lists your payouts without a link.</p>';
else if (!m) h += '<p class="mysub">Switched on. Your page goes live with your first payout on the ledger.</p>';
else h += '<p class="mysub">Switched on. Your page shows on the next ledger refresh (every 5 minutes).</p>';
if (iapswitch.configured()) {
h += '<form method="post" action="/api/my/switch" class="swform"><input type="hidden" name="on" value="' + (v.on ? '0' : '1') + '"><button class="btn' + (v.on ? ' sec' : '') + '" type="submit">' + (v.on ? 'Switch my page off' : 'Switch my page on') + '</button></form>'
+ '<p class="fine">This is the same switch as InstantAdPay Promo tools &gt; 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.)') + '</p>';
} else {
h += '<div class="cta" style="margin-top:12px"><a class="btn sec" href="' + esc(iapswitch.promoUrl()) + '" rel="noopener">Change it in InstantAdPay</a></div><p class="fine">The switch lives in InstantAdPay Promo tools &gt; Stack POL. The state shown is from the last ledger refresh.</p>';
}
h += '</section>';
// 2. Pro
h += '<section class="mycard"><div class="mct"><h2>Stack POL Pro</h2><span class="pill ' + (v.pro ? 'on' : 'off') + '">' + (v.pro ? 'Pro' : 'Not yet') + '</span></div>';
if (v.pro) {
const pr = v.stack && v.stack.pro;
h += '<p class="mysub">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.</p>';
if (pr) h += '<p class="mysub">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') + '. <a href="https://linkspin.app/my" rel="noopener">Manage them in LinkSpin</a></p>';
if (pr) h += pr.video ? '<p class="mysub">Your videos: the Video Spin "' + esc(pr.video.name) + '" (' + fmtInt(pr.video.count) + ' video' + (pr.video.count === 1 ? '' : 's') + ') shows on your page. <a href="https://linkspin.app/links" rel="noopener">Change it in LinkSpin</a></p>'
: '<p class="mysub">No videos on your page yet. Make a video on Video App Income (the first one is free), then add it to a Video Spin in LinkSpin and it shows here. <a href="https://videoappincome.com/join?ref=' + esc(un) + '" rel="noopener">Make your first video</a></p>';
h += copyRow('refurl', D.SITE + '/?ref=' + un, 'Any Stack POL page with your referral');
} else {
h += '<p class="mysub">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.</p><div class="cta" style="margin-top:12px"><a class="btn sec" href="https://instantadpay.com/my#promo?s=stackpol" rel="noopener">See Pro in InstantAdPay</a></div>';
}
h += '</section></div>';
// 3. join links
h += '<div class="sec-head"><h2>Your join links</h2><p>The same links your public page uses. Each one credits you.</p></div><div class="jlinks">'
+ PROGRAMS.map((p, i) => '<div class="jl" style="--c:' + p.c + '"><div class="jn"><i></i><b>' + esc(p.n) + '</b><span>' + esc(p.kind) + '</span></div>' + copyRow('j' + i, p.join(un)) + '</div>').join('') + '</div>';
// 4. share kit
const share = 'Every POL payout I have stacked across the network, each one a Polygon transaction you can check: ' + pageUrl;
h += '<div class="sec-head"><h2>Share kit</h2><p>Your page link, a ready post and the Stack POL images.</p></div><div class="mygrid">';
h += '<section class="mycard">' + copyRow('kurl', pageUrl, 'Your page') + '<div class="cprow"><label for="kpost">A ready post</label><div class="cpbox"><textarea id="kpost" readonly rows="3">' + esc(share) + '</textarea><button type="button" class="cpb" data-copy="kpost">Copy</button></div></div>'
+ copyRow('kembed', '<a href="' + pageUrl + '"><img src="' + D.SITE + '/og-stackpol-1200x630.jpg" width="600" height="315" alt="Stack POL: every POL payout, stacked"></a>', 'Banner code for a site or blog')
+ (v.pro && D.qr ? '<div class="kqr"><img src="/qr/' + esc(un) + '.svg" alt="QR code for your page" width="120" height="120"><span>Your QR code. <a href="/qr/' + esc(un) + '.svg" download="stackpol-' + esc(un) + '-qr.svg">Download</a></span></div>' : '') + '</section>';
h += '<section class="mycard kimgs">' + [['/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]) => '<figure><img src="' + src + '" alt="' + esc(label) + '" loading="lazy"><figcaption>' + esc(label) + ' <a href="' + src + '" download="' + fn + '">Download</a></figcaption></figure>').join('') + '</section></div>';
// 5. payouts
h += '<div class="sec-head"><h2>Your payouts</h2><p>From the Stack POL ledger, your wallet' + (v.wallets.length === 1 ? '' : 's') + ' only.' + (D.idx() && D.idx().at ? ' Refreshed ' + D.when(D.idx().at) + '.' : '') + '</p></div>';
if (!m) {
h += '<section class="mycard"><p class="lead" style="margin:0">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.</p></section>';
} else {
const ps = PROGRAMS.filter(p => m.byProg[p.k]).sort((a, b) => m.byProg[b.k].pol - m.byProg[a.k].pol);
h += '<section class="mycard"><div class="total"><span class="n">' + fmt(m.total) + '</span><span class="u">POL</span></div><div class="stats"><div><b>' + fmtInt(m.payments) + '</b><span>payments</span></div><div><b>' + fmtInt(ps.length) + '</b><span>programs</span></div>'
+ (m.since ? '<div><b>' + new Date(m.since).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'America/Chicago' }) + '</b><span>first payout</span></div>' : '') + '</div>'
+ '<div class="keys">' + ps.map(p => '<span style="--c:' + p.c + '"><i></i>' + esc(p.n) + ' <b>' + fmt(m.byProg[p.k].pol) + '</b></span>').join('') + '</div>'
+ (v.wallets.length ? '<p class="mysub" style="margin-top:12px">Wallet' + (v.wallets.length === 1 ? '' : 's') + ': ' + v.wallets.map(w => '<a class="mono" href="https://polygonscan.com/address/' + esc(w) + '" target="_blank" rel="noopener">' + esc(w.slice(0, 6) + '…' + w.slice(-4)) + ' ↗</a>').join(' ') + '</p>' : '') + '</section>';
const rows = m.rows || [];
h += D.tableHead(false) + D.ledgerRows(rows, false) + '</tbody></table></div>';
if (rows.length < m.payments) h += '<p class="fine" style="margin-top:8px">Showing your latest ' + fmtInt(rows.length) + ' of ' + fmtInt(m.payments) + ' payments. Every one is on Polygonscan under your wallet.</p>';
}
h += '<div class="myfoot"><form method="post" action="/api/my/signout"><button class="btn sec" type="submit">Sign out</button></form><form method="post" action="/api/my/signout"><input type="hidden" name="everywhere" value="1"><button class="linkbtn" type="submit">Sign out of the whole network</button></form></div>';
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 };