My Stack POL: network sign-in through the hub + signed-in member area at /my (Marty approved 2026-11-19)

- networksso.js (shared file, same copy as IAP/LinkSpin/YPB): hub-only sign-in (HUB_SSO=on), silent check on /my, sign-out
- my.js: signed session cookie (keyed off HUB_SECRET), sign-outs in the my-signouts.json MySQL document; /my shows the page
  link + on/off, Pro, join links per program, share kit, own payout rows with Polygonscan links and totals from the ledger
- iapswitch.js: the page switch stays in IAP's stack-optin.json; Stack POL calls IAP POST /api/partner/stackpol/switch
  (signed, STACKPOL_SWITCH_KEY; spec in the file). Until IAP has it, /my links to IAP Promo tools
- tools/indexer.py: snapshot gains `my` (every paid member's rows, wallets, page flag, IAP switches, Pro list); public data unchanged
- header Sign in / My Stack POL entry; robots keeps /my and /sso/ out
- qa/my.test.mjs: 66 checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-19 06:57:11 -06:00
parent 9bc6e84f2d
commit ffa0d74c70
8 changed files with 1070 additions and 8 deletions
+45 -6
View File
@@ -40,7 +40,7 @@ const fmtInt = n => Number(n || 0).toLocaleString('en-US');
const ago = ts => { const s = Math.max(0, (Date.now() - ts) / 1000); return s < 90 ? 'just now' : s < 5400 ? Math.round(s / 60) + ' min ago' : s < 129600 ? Math.round(s / 3600) + ' h ago' : Math.round(s / 86400) + ' days ago'; };
const when = ts => new Date(ts).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'America/Chicago' }) + ' CT';
const shortTx = tx => tx ? tx.slice(0, 10) + '…' + tx.slice(-4) : '';
const RESERVED = new Set(['blog', 'ledger', 'programs', 'earn', 'api', 'img', 'sitemap', 'robots', 'favicon', 'about', 'admin', 'login', 'join', 'feed', 'www', 'static', 'assets', 'terms', 'privacy', 'disclaimer']);
const RESERVED = new Set(['blog', 'ledger', 'programs', 'earn', 'api', 'img', 'sitemap', 'robots', 'favicon', 'about', 'admin', 'login', 'join', 'feed', 'www', 'static', 'assets', 'terms', 'privacy', 'disclaimer', 'sso', 'signin', 'signout', 'logout', 'account']);
const net = () => (IDX && IDX.network) || { pol: 0, payments: 0, wallets: 0 };
const prog = k => (IDX && IDX.programs && IDX.programs[k]) || { pol: 0, payments: 0, wallets: 0 };
const live = () => IDX ? '<div class="live"><span class="dot"></span>Ledger refreshed ' + ago(IDX.at) + '</div>' : '<div class="live"><span class="dot" style="background:var(--gold)"></span>Ledger warming up</div>';
@@ -169,7 +169,7 @@ function sitemap() {
+ Object.keys((IDX && IDX.stacks) || {}).map(x => '<url><loc>' + SITE + '/' + x + '</loc><changefreq>daily</changefreq><priority>0.5</priority></url>').join('');
return '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + u + '</urlset>';
}
const robots = () => 'User-agent: *\nAllow: /\nDisallow: /api/\n\nSitemap: ' + SITE + '/sitemap.xml\n';
const robots = () => 'User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /my\nDisallow: /sso/\n\nSitemap: ' + SITE + '/sitemap.xml\n';
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.jpg': 'image/jpeg', '.png': 'image/png', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.webmanifest': 'application/manifest+json', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
function send(req, res, code, type, body, cache) {
@@ -196,12 +196,51 @@ function staticFile(req, res, p) {
const chatbot = require('./chatbot');
const legal = require('./legal');
const chatJson = (res, code, obj, extra) => { res.writeHead(code, Object.assign({ 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }, extra || {})); res.end(JSON.stringify(obj)); };
// My Stack POL (Marty approved 2026-11-19): the network sign-in through the hub (networksso.js, the shared file; HUB_SSO=on with
// HUB_URL, HUB_SECRET, HUB_SITE=stackpol) and the signed-in area at /my (my.js). Nothing public needs it. Hub only: no
// NETWORK_SSO_SECRET here, so the old pairwise IAP/LinkSpin path stays off (and no `from`: members are emails, like the hub's).
const networksso = require('./networksso');
const my = require('./my');
const IAP_BASE = String(process.env.IAP_URL || 'https://instantadpay.com').trim().replace(/\/+$/, '');
my.init({ idx: () => IDX, PROGRAMS, BY_KEY, head, tail, esc, fmt, fmtInt, when, ledgerRows, tableHead, SITE, dataDir: DATA_DIR, qr: !!QR });
networksso.init({ self: 'stackpol', peer: 'iap', peerBase: () => IAP_BASE, isProd: /^https:/.test(SITE), dataDir: DATA_DIR, defaultPath: '/my',
member: async req => { const s = my.session(req); return s ? { email: s.email, address: s.address } : null; },
accept: async email => (email ? { ok: true } : { fallback: 'no email' }), // the hub vouches for a network member; Stack POL keeps no accounts
signIn: async (email, req, v) => my.mintSession({ email, wallet: v && v.wallet, name: v && v.name }),
landing: to => to, signinPath: () => '/my?signin=none' });
const formBody = req => new Promise(resolve => { const ch = []; let n = 0; req.on('data', c => { n += c.length; if (n <= 4096) ch.push(c); }); req.on('end', () => resolve(new URLSearchParams(n <= 4096 ? Buffer.concat(ch).toString('utf8') : ''))); req.on('error', () => resolve(new URLSearchParams())); });
const sameSite = req => { const o = req.headers.origin; if (req.headers['sec-fetch-site'] === 'cross-site') return false; if (!o) return true; try { return new URL(o).origin === new URL(SITE).origin; } catch (e) { return false; } };
const seeOther = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(303, h); res.end(); };
async function myPost(req, res, p) {
if (!sameSite(req)) { res.writeHead(403, { 'Content-Type': 'text/plain' }); return res.end('Forbidden'); }
const b = await formBody(req); const s = my.session(req);
if (p === '/api/my/signout') {
const set = my.clearCookies().concat(networksso.offCookie());
if (s) { my.signOut(s.email); if (b.get('everywhere') === '1') await networksso.signOutEverywhere(s).catch(() => null); }
return seeOther(res, '/my?out=1', set);
}
if (!s) return seeOther(res, '/my');
const r = await my.doSwitch(s, b.get('on') === '1').catch(e => ({ ok: false, reason: e.message }));
if (!r.ok) console.error('[stackpol] my switch', r.reason);
return seeOther(res, '/my?sw=' + (r.ok ? 'ok' : 'err'));
}
const chatBody = req => new Promise(resolve => { const ch = []; let n = 0; req.on('data', c => { n += c.length; if (n <= 32768) ch.push(c); }); req.on('end', () => { try { resolve(n && n <= 32768 ? JSON.parse(Buffer.concat(ch).toString('utf8')) : {}); } catch (e) { resolve({}); } }); req.on('error', () => resolve({})); });
const server = http.createServer((req, res) => {
const server = http.createServer(async (req, res) => {
let u; try { u = new URL(req.url, SITE); } catch (e) { res.writeHead(400); return res.end(); }
const p = decodeURIComponent(u.pathname);
let p; try { p = decodeURIComponent(u.pathname); } catch (e) { res.writeHead(400); return res.end(); }
if ((req.headers.host || '').startsWith('www.')) { res.writeHead(301, { Location: SITE + req.url }); return res.end(); }
try {
// network sign-in + My Stack POL (2026-11-19)
if (req.method === 'GET' && await networksso.page(req, res, u)) return;
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
if (req.method === 'POST' && (p === '/api/my/signout' || p === '/api/my/switch')) return await myPost(req, res, p);
if ((p === '/my' || p === '/my/') && (req.method === 'GET' || req.method === 'HEAD')) {
const c = my.cookies(req);
if (!my.session(req) && !c['nsso.tried'] && !c['nsso.off'] && !u.searchParams.has('signin') && !u.searchParams.has('out') && !networksso.isBot(req) && (networksso.hubOn() || networksso.enabled())) return seeOther(res, '/sso/start?mode=check&to=%2Fmy'); // one silent check through the hub
const r = await my.render(req, { out: u.searchParams.has('out'), signin: u.searchParams.get('signin'), sw: u.searchParams.get('sw') });
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'X-Robots-Tag': 'noindex', ...(r.set.length ? { 'Set-Cookie': r.set } : {}) });
return res.end(req.method === 'HEAD' ? undefined : r.body);
}
if (p === '/api/ingest' && req.method === 'POST') {
if (!KEY || req.headers.authorization !== 'Bearer ' + KEY) { res.writeHead(401); return res.end(); }
const chunks = []; let n = 0;
@@ -221,7 +260,7 @@ const server = http.createServer((req, res) => {
const pc = refSt && refSt.pro ? { who: refName, st: refSt } : null;
const page = body => pc ? personalize(body, pc.who, pc.st) : body;
const q = /^\/qr\/([a-z0-9_]{3,30})\.svg$/.exec(p);
if (q) { const st = IDX && IDX.stacks && IDX.stacks[q[1]]; if (!QR || !st || !st.pro) return html(req, res, 404, notFound()); return qrSvg(q[1]).then(svg => send(req, res, 200, 'image/svg+xml', svg, 'public, max-age=86400')).catch(() => html(req, res, 500, notFound())); }
if (q) { const st = IDX && IDX.stacks && IDX.stacks[q[1]]; if (!QR || !st || !st.pro || my.hiddenNow(q[1])) return html(req, res, 404, notFound()); return qrSvg(q[1]).then(svg => send(req, res, 200, 'image/svg+xml', svg, 'public, max-age=86400')).catch(() => html(req, res, 500, notFound())); }
if (p === '/') return html(req, res, 200, page(home()), 'public, max-age=120');
if (legal.PATHS.includes(p)) return html(req, res, 200, page(legal.render(p)), 'public, max-age=3600'); // Terms / Privacy / Disclaimer (2026-11-17)
if (p === '/network' || p === '/how-it-works') return staticFile(req, res, '/network.html') || html(req, res, 404, notFound()); // the one-page network explainer (Marty 2026-11-17)
@@ -239,7 +278,7 @@ const server = http.createServer((req, res) => {
m = /^\/@?([a-z0-9_]{3,30})\/?$/i.exec(p);
if (m && !RESERVED.has(m[1].toLowerCase())) {
const name = m[1].toLowerCase(), st = IDX && IDX.stacks && IDX.stacks[name];
if (st) return html(req, res, 200, st.pro ? personalize(stackPage(name, st), name, st) : stackPage(name, st), 'public, max-age=120');
if (st && !my.hiddenNow(name)) return html(req, res, 200, st.pro ? personalize(stackPage(name, st), name, st) : stackPage(name, st), 'public, max-age=120');
return html(req, res, 404, notFound('@' + name + ' has not switched on a Stack POL page yet. Members turn it on in InstantAdPay Promo tools.'));
}
return html(req, res, 404, notFound());