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
+1
View File
@@ -10,3 +10,4 @@ stackpol.com: every POL payout across the network, stacked. Live app since 2026-
- Standing rule (Marty 2026-11-15): every rebuilt network site is added here when it goes live: a programs.js entry, its /earn/<slug> page (automatic from the entry, plus public/img/<key>.jpg 800x420) and an indexer source for its member payouts (house/company wallets excluded). ViralAdBlitz, 5xYourTeam and DownlineHydra added 2026-11-15.
- Site assistant (2026-11-15): chat widget on every page (`public/assets/chat.js` + `chat.css`, loaded from layout.js). `chatbot.js` holds what it knows (CANNED + FACTS from this repo); `chatcore.js`, `kb.js` (kb.json is a MySQL document, see Storage) and `netkb.js` (the shared network knowledge on the hub, signed as `HUB_SITE=stackpol` with `HUB_SECRET`) are the same files as the rebuilt sites. OpenRouter key: Coolify env `OPENROUTER_API_KEY`. No admin KB editing on Stack POL. Test: `node qa/chatbot.test.mjs`.
- Storage (Marty 2026-11-16: "they should live in the database"): MySQL, Coolify `stackpol-mysql` yw404lxgfkbb5n9s3pxu1hxk (db `stackpol`, binlog expiry 3 h persisted, in core's hourly dumps). App env `DOCSTORE_URL`; `docstore.js` (same file as LinkSpin, skips unchanged writes) keeps the data documents of DATA_DIR (/app/data, no volume) in table `docs`: `stack-index.json` (the last indexer snapshot minus `at`), `stack-index-at.json` ({at}), `kb.json` (chatbot entries), `netkb-cache.json` (network knowledge cache). Loaded before the server listens, so a deploy serves the last totals at once. The ingest API is unchanged. Without DOCSTORE_URL (local only) they are plain files in DATA_DIR.
- My Stack POL (Marty approved 2026-11-19): signed-in member area at /my (my.js), "Sign in" / "My Stack POL" in the header. Network sign-in through the hub only (networksso.js, the shared file, unchanged copy of IAP's): envs HUB_SSO=on, HUB_URL, HUB_SECRET, HUB_SITE=stackpol (the last three already serve netkb). Needs stackpol in the hub's HUB_SSO_SITES. Session = signed cookie sp.sid (7 days, keyed off HUB_SECRET); sign-out writes my-signouts.json (MySQL document) so older cookies stop working. Shows the page link + switch, Pro (IAP's rule via stack-optin.json pro), join links (programs.js), share kit, and the member's own payout rows from the snapshot's `my` block (tools/indexer.py). The switch stays in IAP's stack-optin.json: iapswitch.js calls IAP POST /api/partner/stackpol/switch (spec in the file header) with STACKPOL_SWITCH_KEY; until IAP has that route and both apps have the key, /my links to IAP Promo tools instead. Test: node qa/my.test.mjs.
+52
View File
@@ -0,0 +1,52 @@
// The Stack POL page switch, read and written from stackpol.com/my (Marty approved the My Stack POL area 2026-11-19).
//
// ONE PLACE FOR THE SWITCH. The switch lives in InstantAdPay: its document stack-optin.json { users: { username: true|false },
// pro: { username: true } } (an IAP MySQL document), written by IAP's Promo tools > Stack POL toggle (POST /api/my/stackpol). The
// Stack POL indexer reads that document every 5 minutes. Stack POL never keeps a second copy: a switch made here is sent to IAP, which
// writes the same document with the same code, so the two can never disagree.
//
// THE INTERFACE IAP NEEDS (not built in IAP yet; until it is, configured() is false and /my links to IAP's Promo tools instead):
// POST <IAP_URL>/api/partner/stackpol/switch
// Headers: Content-Type: application/json
// X-Stack-Ts: milliseconds since 1970 (IAP refuses anything more than 5 minutes from its own clock)
// X-Stack-Sig: hex HMAC-SHA256(STACKPOL_SWITCH_KEY, X-Stack-Ts + "\n" + raw body)
// Body: { "email": "<the member's email, from their network sign-in>" } read only
// { "email": "...", "on": true|false } switch it
// IAP does: verify the signature and the time (timingSafeEqual), find the account by email (accounts.byEmail), refuse when there is
// none (404) or it has no username (409), then run the SAME code as /api/my/stackpol: so.users[un] = !!on when `on` is given, refresh
// so.pro[un] from gamepass.stackProView(email), write stack-optin.json atomically (tmp + rename), and answer
// 200 { "on": so.users[un] !== false, "username": un, "pro": !!pv.pro }.
// The secret is a new env on BOTH apps, the same value: STACKPOL_SWITCH_KEY (32+ characters). IAP_URL on Stack POL is optional
// (default https://instantadpay.com).
// Only Stack POL can call it (the key), only for the member signed in on Stack POL (the email comes from their verified hub token),
// and it changes nothing but the page switch.
'use strict';
const crypto = require('crypto');
const KEY = () => String(process.env.STACKPOL_SWITCH_KEY || '').trim();
const BASE = () => String(process.env.IAP_URL || 'https://instantadpay.com').trim().replace(/\/+$/, '');
const ROUTE = '/api/partner/stackpol/switch';
const configured = () => KEY().length >= 32 && /^https?:\/\/[a-z0-9.:-]+$/i.test(BASE());
const sign = (ts, raw) => crypto.createHmac('sha256', KEY()).update(ts + '\n' + raw).digest('hex');
// -> { ok: true, on, username, pro } or { ok: false, reason }
async function call(body, ms) {
if (!configured()) return { ok: false, reason: 'off' };
if (typeof fetch !== 'function') return { ok: false, reason: 'no fetch' };
const raw = JSON.stringify(body); const ts = String(Date.now());
const ac = new AbortController(); const tm = setTimeout(() => ac.abort(), ms || 3000);
try {
const r = await fetch(BASE() + ROUTE, { method: 'POST', body: raw, signal: ac.signal, headers: { 'Content-Type': 'application/json', 'X-Stack-Ts': ts, 'X-Stack-Sig': sign(ts, raw), 'User-Agent': 'stackpol-my' } });
let j = null; try { j = await r.json(); } catch (e) {}
if (r.status !== 200 || !j || typeof j.on !== 'boolean') return { ok: false, reason: 'iap ' + r.status + (j && j.error ? ': ' + String(j.error).slice(0, 120) : '') };
const un = String(j.username || '').toLowerCase();
return { ok: true, on: j.on, username: /^[a-z0-9_]{3,30}$/.test(un) ? un : null, pro: !!j.pro };
} catch (e) { return { ok: false, reason: 'iap unreachable' }; }
finally { clearTimeout(tm); }
}
const get = email => call({ email: String(email || '').toLowerCase() }, 2500);
const set = (email, on) => call({ email: String(email || '').toLowerCase(), on: !!on }, 5000);
// the deep link to IAP's own toggle (always works, needs no key)
const promoUrl = () => BASE() + '/my#promo?s=stackpol';
module.exports = { configured, get, set, promoUrl, sign, ROUTE };
+22 -1
View File
@@ -92,6 +92,24 @@ footer.site b{display:block;color:var(--ink);font:700 14px var(--display);margin
.procta{display:flex;flex-wrap:wrap;gap:12px 16px;align-items:center;border:1px solid var(--violet);border-radius:18px;padding:18px 20px;margin:30px 0;background:linear-gradient(135deg,rgba(130,71,229,.16),transparent)}
.procta div{flex:1 1 280px;min-width:0}.procta b{display:block;font:800 18px var(--display);margin-bottom:4px}.procta span{color:var(--muted)}
@media (max-width:640px){.prorow{grid-template-columns:1fr}.qr{margin:0 auto}}
/* My Stack POL (2026-11-19) */
nav.top a.mylink{color:#160b02;background:var(--gold);border-radius:999px;padding:3px 12px;margin-left:2px}nav.top a.mylink:hover,nav.top a.mylink[aria-current]{color:#160b02;background:#ffd27a}
.myhero{padding:26px 0 4px}.myhead{display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap}.soform{margin:0}
.mynote{border:1px solid var(--line);background:var(--panel);border-radius:12px;padding:10px 14px;margin:14px 0 0;max-width:72ch}.mynote.ok{border-color:rgba(74,222,128,.45)}.mynote.warn{border-color:rgba(255,194,75,.55)}
.mygrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px;margin-top:22px}@media (max-width:820px){.mygrid{grid-template-columns:1fr}}
.mycard+.tbl{margin-top:14px}.mycard{background:var(--panel);border:1px solid var(--line);border-radius:18px;padding:18px 20px;min-width:0}.mycard h2{font-size:21px}
.mct{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:12px}
.pill{font:700 12px var(--body);letter-spacing:.08em;text-transform:uppercase;border-radius:999px;padding:4px 11px;flex:none}.pill.on{background:rgba(74,222,128,.16);color:var(--ok)}.pill.off{background:var(--panel-2);color:var(--muted)}
.mysub{color:var(--muted);font-size:14px;margin:10px 0 0}.mono{font-family:var(--mono);font-size:12.5px}
.cprow{margin:0 0 10px}.cprow label{display:block;font-size:12.5px;color:var(--muted);margin:0 0 4px}
.cpbox{display:flex;gap:8px;min-width:0}.cpbox input,.cpbox textarea{flex:1;min-width:0;background:var(--ground);color:var(--ink);border:1px solid var(--line);border-radius:10px;padding:9px 11px;font:500 13px var(--mono);resize:none}
.cpb{flex:none;font:700 13px var(--body);color:var(--ink);background:var(--violet);border:0;border-radius:10px;padding:0 14px;cursor:pointer;min-height:38px}.cpb:focus-visible{outline:3px solid var(--violet-hi);outline-offset:2px}
.swform{margin:14px 0 6px}.swform .btn{cursor:pointer;border:0;font-size:15px;padding:11px 20px}.swform .btn.sec{border:1px solid var(--line)}.myhead .btn,.myfoot .btn{cursor:pointer;font-size:14px;padding:9px 16px}
.jlinks{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}@media (max-width:820px){.jlinks{grid-template-columns:1fr}}
.jl{background:var(--panel);border:1px solid var(--line);border-left:4px solid var(--c);border-radius:14px;padding:12px 14px 4px;min-width:0}.jn{display:flex;gap:8px;align-items:baseline;margin-bottom:8px;flex-wrap:wrap}.jn i{width:9px;height:9px;border-radius:3px;background:var(--c);display:inline-block}.jn b{font:700 15px var(--display)}.jn span{color:var(--muted);font-size:12.5px}
.kimgs{display:grid;grid-template-columns:1fr 1fr;gap:12px;align-content:start}.kimgs figure{margin:0}.kimgs img{width:100%;border-radius:10px;border:1px solid var(--line);aspect-ratio:1200/630;object-fit:cover;display:block}.kimgs figcaption{font-size:12.5px;color:var(--muted);margin-top:6px}
.kqr{display:flex;gap:12px;align-items:center;margin-top:6px}.kqr img{background:#fff;border-radius:10px;padding:6px}.kqr span{font-size:13px;color:var(--muted)}
.myfoot{display:flex;gap:16px;align-items:center;flex-wrap:wrap;margin-top:34px}.myfoot form{margin:0}.linkbtn{background:none;border:0;color:var(--violet-hi);font:600 14px var(--body);cursor:pointer;text-decoration:underline;padding:0}
@media (prefers-reduced-motion:reduce){.card,.btn{transition:none}.card:hover{transform:none}}
`;
@@ -118,7 +136,10 @@ function head(o) {
+ (o.jsonld || []).map(j => '<script type="application/ld+json">' + JSON.stringify(j).replace(/</g, '\\u003c') + '</script>').join('')
+ '</head><body><div class="wrap">'
+ '<header class="bar"><a class="logo" href="/" aria-label="Stack POL home">' + LOGO + 'Stack POL</a>'
+ '<nav class="top" aria-label="Main">' + [['/', 'Home'], ['/programs', 'Programs'], ['/ledger', 'Ledger'], ['/blog', 'Blog']].map(([h, l]) => '<a href="' + h + '"' + (o.nav === h ? ' aria-current="page"' : '') + '>' + l + '</a>').join('') + '</nav></header>';
+ '<nav class="top" aria-label="Main">' + [['/', 'Home'], ['/programs', 'Programs'], ['/ledger', 'Ledger'], ['/blog', 'Blog']].map(([h, l]) => '<a href="' + h + '"' + (o.nav === h ? ' aria-current="page"' : '') + '>' + l + '</a>').join('')
// My Stack POL (2026-11-19): pages are cached for everyone, so the label comes from the sp.in cookie (no data in it, set by /my)
+ '<a class="mylink" id="spmy" href="/my"' + (o.nav === '/my' ? ' aria-current="page"' : '') + ' rel="nofollow">Sign in</a></nav>'
+ '<script>(function(){if(/(?:^|; )sp\\.in=1/.test(document.cookie)){var a=document.getElementById("spmy");if(a)a.textContent="My Stack POL";}})();</script></header>';
}
// a LinkSpin zone spot. wide = zone for screens 760px and up, narrow = zone below that; only the one that fits is loaded, so a
// hidden size never counts a view. Zones are on Marty's LinkSpin account, site stackpol.com (created 2026-11-09).
+208
View File
@@ -0,0 +1,208 @@
// 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>';
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 };
+452
View File
@@ -0,0 +1,452 @@
// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each
// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes.
//
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
// sets the loop guard (nsso.tried, 2 minutes) and sends the browser to P.
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
// P mints a token bound to R, the state and the email, and sends the browser
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
// 3. R GET /sso/in?t=<token> R checks signature, audience, expiry (60 s), the state against its cookie
// (so nobody can push their own token into someone else's browser), and spends
// the nonce (a second use is refused). The email must already be a member
// here; then R makes an ordinary session and redirects to the relative path.
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
// stops a second bounce for 2 minutes (30 until 2026-11-15, when it blocked Marty's silent sign-in on LinkSpin), signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
// bots and non-page fetches never bounce.
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
//
// Wallet sites (Downline Banners, 2026-11-13, Marty: "sign in once and be logged into all these sites"). Downline Banners has no email
// accounts; its members are wallets. IAP and LinkSpin list it under `wallets: { bannerline: base }` and vouch one way: /go/bannerline
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
//
// THE HUB AS THE PROVIDER (Marty approved 2026-11-15; off unless HUB_SSO=on, with HUB_URL, HUB_SECRET (32+) and HUB_SITE or C.hubSite).
// The network hub keeps one network sign-in per browser in its own cookie (7 days, renewed on use). With it on:
// /sso/start asks the hub (GET <hub>/sso/check?site=<HUB_SITE>&st&to&m) instead of one other site; the hub answers
// /sso/in?h=<token> ("h1." token, HMAC-SHA256 with this site's HUB_SECRET under 'hubsso.v1.', iss 'hub', aud = this site,
// 60 s, single use, bound to the state cookie) or /sso/in?none=1&hub=1, and then the old pairwise path is tried once as the
// fallback (until every site is switched).
// Push: a signed-in member's page load (a real top-level navigation only) with no matching nsso.hp cookie goes once through
// <hub>/sso/set?site&t=<this site's token for the member> and straight back, so signing in on any site signs in the hub.
// Only when the hub answered /health in the last 2 minutes: a hub that is down never takes a page with it.
// Activity (Marty 2026-11-15, DownlineHydra "Wake it", the CRM score): a signed-in member's page load pings POST <hub>/v1/activity
// {email|wallet, kind 'visit'} at most once per member per day, fire and forget (HUB_URL + HUB_SECRET; HUB_ACTIVITY=0 turns it off).
// signOutEverywhere(session): POST <hub>/v1/sso/signout; the hub ends every hub sign-in of that person and tells hooked sites.
//
// ONE SITES LIST + THE WAY BACK (Marty 2026-11-17: "I logged in to Instant Ad Pay from Viral Ad Source, and it never had a return
// path back"). Before, each provider (IAP, LinkSpin) kept its own hand-written `wallets` list; a site missing from it (5xYourTeam
// 11-15, ViralAdSource 11-17) was refused at /sso/check and the member was dropped on the provider's dashboard with no way back.
// Sites list: a provider also knows every site in the hub's public GET <hub>/v1/sso-sites (HUB_SSO_SITES there; the same list the
// hub signs in for). Read at start, every 5 minutes, and once more (2 s at most) when an unknown site asks. Hand-written entries win.
// Return links: any provider page with ?return=<site>&to=/path (a known site only, never an open redirect) remembers the way back
// in nsso.ret (1 day) and reloads without the two parameters. Signed in already: straight back. After the email-code sign-in (and
// after the username step for a new account) the provider's dashboard goes to /sso/resume, which finishes it: /go/<site>?to=/path.
// No wallet yet (a wallet site needs one): with C.walletPath the member goes to the provider's wallet step first (nsso.wait), and
// afterWallet(req) gives the wallet-link answer its next hop, /sso/resume. The same holds for a deliberate tap (nsso.back).
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim();
const enabled = () => SECRET().length >= 32;
const TTL = 60 * 1000; // token life
const SKEW = 30 * 1000; // clock skew allowed between the two servers
const STATE_AGE = 300; // seconds: the state cookie
const GO_STATE_AGE = 3600; // seconds: the state cookie on a deliberate tap (time to sign in, pick a username and link a wallet on the provider first; 20 minutes until 2026-11-17)
const BACK_AGE = 3600; // seconds: the provider remembers an unfinished deliberate check while the member signs in (20 minutes until 2026-11-17)
const RET_AGE = 86400; // seconds: a ?return=<site> link remembers the way back (2026-11-17)
const TRIED_AGE = 120; // seconds: one silent check per browser per 2 minutes (loop guard only; 30 minutes until 2026-11-15)
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', fivex: '5xYourTeam' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15); fivex = 5xYourTeam (2026-11-15)
const WALLET_RE = /^0x[0-9a-f]{40}$/;
const PUSH_AGE = 6 * 86400; // seconds: this browser's member is signed in on the hub (the hub's own sign-in lasts 7 days)
const HUB_BASE = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
const HUB_KEY = () => String(process.env.HUB_SECRET || '').trim();
const HUB_NAME = () => String(process.env.HUB_SITE || (C && (C.hubSite || C.self)) || '').trim().toLowerCase();
const hubCreds = () => /^https?:\/\/[a-z0-9.:-]+$/i.test(HUB_BASE()) && HUB_KEY().length >= 32 && /^[a-z0-9_-]{1,64}$/.test(HUB_NAME());
const hubOn = () => String(process.env.HUB_SSO || '').trim().toLowerCase() === 'on' && hubCreds();
let hubSeen = 0, hubChecked = 0, hubAsking = null; // last good /health answer, last time we asked
// true when the hub answered /health in the last 2 minutes. Asked at most once a minute; while the answer is unknown (first use, or
// the last good answer is old) the caller waits for that one question (2 s at most), so a hub that is down costs one page 2 s a minute.
async function hubUp() {
const now = Date.now();
if (now - hubChecked >= 60000 && !hubAsking && typeof fetch === 'function') {
hubChecked = now;
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, 2000);
hubAsking = fetch(HUB_BASE() + '/health', { signal: ac ? ac.signal : undefined }).then(r => { if (r.ok) hubSeen = Date.now(); }).catch(() => {}).finally(() => { clearTimeout(tm); hubAsking = null; });
}
if (hubAsking && Date.now() - hubSeen >= 120000) await hubAsking;
return Date.now() - hubSeen < 120000;
}
// the hub's sign-in sites {site: base} (2026-11-17): providers answer every site the hub knows, not only their hand-written list
let hubSites = {}, hubSitesAt = 0, hubSitesAsking = null;
const SITE_RE = /^[a-z0-9_-]{1,64}$/, BASE_RE = /^https?:\/\/[a-z0-9.:-]+$/i;
function loadHubSites() {
if (hubSitesAsking) return hubSitesAsking;
if (!BASE_RE.test(HUB_BASE()) || typeof fetch !== 'function' || String(process.env.NSSO_HUB_SITES || '') === '0') return Promise.resolve();
hubSitesAt = Date.now();
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, 2000);
hubSitesAsking = fetch(HUB_BASE() + '/v1/sso-sites', { signal: ac ? ac.signal : undefined }).then(r => (r.ok ? r.json() : null)).then(j => {
if (!j || !j.sites || typeof j.sites !== 'object') return;
const out = {}; for (const [k, v] of Object.entries(j.sites)) { const b = String(v || '').replace(/\/+$/, ''); if (SITE_RE.test(k) && BASE_RE.test(b)) out[k] = b; }
hubSites = out;
}).catch(() => {}).finally(() => { clearTimeout(tm); hubSitesAsking = null; });
return hubSitesAsking;
}
const freshSites = () => { if (C && C.wallet && Date.now() - hubSitesAt > 5 * 60 * 1000) loadHubSites(); };
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() }, walletPath?: the provider's wallet step }
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', SECRET()).update('nsso.v1.' + s).digest();
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || '');
// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters.
function safePath(to, dflt) {
const d = dflt == null ? '/' : dflt;
const s = String(to == null ? '' : to);
if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d;
try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; }
}
function mint(o) {
const now = o.now || Date.now();
const t = { iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
if (o.name) t.name = String(o.name).slice(0, 40);
const body = b64u(JSON.stringify(t));
return 'v1.' + body + '.' + b64u(mac(body));
}
// -> { ok, email, to, n, exp } or { error: reason }
function verify(tok, o) {
if (!enabled()) return { error: 'off' };
const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
if (!m) return { error: 'malformed' };
const want = mac(m[1]), got = unb64u(m[2]);
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
const now = (o && o.now) || Date.now();
if (!p || p.aud !== o.aud || ![].concat(o.iss).includes(p.iss)) return { error: 'audience' };
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
const st = String((o && o.st) || '');
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
}
// hub tokens ("h1.", the hub's format): mint for the hub (push), verify from the hub (sign-in)
const hmacHub = x => crypto.createHmac('sha256', HUB_KEY()).update('hubsso.v1.' + x).digest();
function mintHub(o) {
const now = o.now || Date.now();
const t = { iss: HUB_NAME(), aud: 'hub', to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
if (o.email) t.email = String(o.email).trim().toLowerCase(); else if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
const body = b64u(JSON.stringify(t));
return 'h1.' + body + '.' + b64u(hmacHub(body));
}
function verifyHub(tok, o) {
if (!hubCreds()) return { error: 'off' };
const m = /^h1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
if (!m) return { error: 'malformed' };
const want = hmacHub(m[1]), got = unb64u(m[2]);
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
const now = (o && o.now) || Date.now();
if (!p || p.iss !== 'hub' || p.aud !== HUB_NAME()) return { error: 'audience' };
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
const st = String((o && o.st) || '');
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
return { ok: true, iss: 'hub', email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
}
// a signed /v1 call to the hub (the scheme every site already uses): hex HMAC-SHA256(HUB_SECRET, ts + newline + body)
async function hubCall(route, body, ms) {
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, ms || 5000);
try {
const r = await fetch(HUB_BASE() + route, { method: 'POST', body: raw, signal: ac ? ac.signal : undefined, headers: { 'Content-Type': 'application/json', 'X-Hub-Site': HUB_NAME(), 'X-Hub-Ts': ts, 'X-Hub-Sig': crypto.createHmac('sha256', HUB_KEY()).update(ts + '\n' + raw).digest('hex') } });
let j = null; try { j = await r.json(); } catch (e) {}
return { status: r.status, json: j };
} finally { clearTimeout(tm); }
}
const who = s => (s && s.email ? { email: String(s.email).toLowerCase() } : s && s.address && WALLET_RE.test(String(s.address).toLowerCase()) ? { wallet: String(s.address).toLowerCase() } : null);
const pushTag = w => b64u(crypto.createHmac('sha256', HUB_KEY()).update('push.' + (w.email || w.wallet)).digest()).slice(0, 22);
// once per member per day (memory; a restart may ping once more, the hub counts a visit once per 10 minutes anyway)
const pinged = new Map(); let pingDay = '';
function activity(w) {
if (String(process.env.HUB_ACTIVITY || '') === '0' || !hubCreds() || typeof fetch !== 'function') return;
const day = new Date().toISOString().slice(0, 10); if (day !== pingDay) { pinged.clear(); pingDay = day; }
const k = w.email || w.wallet; if (pinged.has(k)) return; pinged.set(k, 1);
hubCall('/v1/activity', Object.assign({ kind: 'visit' }, w), 5000).then(r => { if (r.status >= 500) pinged.delete(k); }).catch(() => { pinged.delete(k); });
}
// a signed-in request the site already answers (2026-11-16, Marty: "LinkSpin never reports activity"): /api/me, the dashboard
// heartbeat (/api/my/ping) and the admin portal call this, so a Control Room tab kept open for days, a browser that sends no
// Sec-Fetch headers and a wallet-only session still count the day's visit. The page-load ping in page() only sees full navigations.
// s = {email} and/or {address}. Same once-a-day rule as page(). -> true when a ping was due or already sent today.
function seen(s) {
try {
if (!C || !hubCreds()) return false;
const w = who(s && s.email ? s : s && s.address ? { address: s.address } : null); if (!w) return false;
activity(w); return true;
} catch (e) { return false; }
}
// a real top-level page load of a page (never an API call, an asset, a fetch, a bot or one of our own hops)
function pageLoad(req, p) {
if (req.method !== 'GET' || isBot(req)) return false;
if (req.headers['sec-fetch-dest'] !== 'document' || (req.headers['sec-fetch-mode'] && req.headers['sec-fetch-mode'] !== 'navigate')) return false;
if (/^\/(sso|api|go|assets|art|img|fonts|uploads|admin)(\/|$)/.test(p)) return false;
return !/\.[a-z0-9]{1,5}$/i.test(p);
}
async function signOutEverywhere(s) {
const w = who(s); if (!w || !hubCreds()) return { ok: false, reason: !w ? 'signed out' : 'hub off' };
try { const r = await hubCall('/v1/sso/signout', w, 8000); return r.status === 200 ? Object.assign({ ok: true }, r.json || {}) : { ok: false, reason: 'hub ' + r.status }; }
catch (e) { return { ok: false, reason: 'hub unreachable' }; }
}
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
const used = new Map(); let fileLoaded = false, tableReady = null;
const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null;
function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); }
function loadFile() {
if (fileLoaded) return; fileLoaded = true;
try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {}
}
function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } }
async function spend(n, exp) {
const now = Date.now(); loadFile(); prune(now);
if (used.has(n)) return false;
used.set(n, Number(exp) + SKEW); saveFile();
const db = C && C.db;
if (db && db.enabled && db.enabled()) {
try {
if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; });
await tableReady;
await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]);
if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {});
} catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed
}
return true;
}
// crawlers, link previews and headless browsers never bounce
const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i;
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); };
// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser)
const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; };
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;
}
const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : '');
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); if (hubOn()) { hubSeen = 0; hubChecked = 0; hubUp().catch(() => {}); } hubSites = {}; hubSitesAt = 0; if (C.wallet) loadHubSites(); }
// a site this provider answers for: its own list first, then the hub's (never itself, never the peer, which has its own path)
function siteBase(x) {
if (!C || !C.wallet || !SITE_RE.test(String(x || '')) || x === C.self || x === C.peer) return null;
if (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x)) return C.wallets[x];
if (Object.prototype.hasOwnProperty.call(hubSites, x)) { const b = hubSites[x]; return () => b; }
return null;
}
// an unknown site asking: ask the hub once more (at most every 30 s, 2 s at most) before refusing
async function siteBaseFresh(x) { let b = siteBase(x); if (!b && C && C.wallet && SITE_RE.test(String(x || '')) && Date.now() - hubSitesAt > 30000) { await loadHubSites(); b = siteBase(x); } return b; }
const siteName = x => NAMES[x] || ({ viraladsource: 'ViralAdSource', webworthit: 'WebWorthIt', stackpol: 'Stack POL' })[x] || x;
const retOf = req => { const m = /^([a-z0-9_-]{1,64})\|(\/.*)$/.exec(cookies(req)['nsso.ret'] || ''); return m ? { site: m[1], to: safePath(m[2], '/') } : null; };
// signed in here, on the way back to a site: its wallet step first when the site needs a wallet this account does not have yet
async function backHop(s, site, to, set) {
let w = null; try { w = await C.wallet(s); } catch (e) {}
if ((!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) && C.walletPath) { set.push(ck('nsso.wait', '1', BACK_AGE, true)); log('back: wallet step first', s.email, 'for ' + siteName(site)); return C.walletPath; }
return '/go/' + site + '?to=' + encodeURIComponent(to);
}
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
// -> true when the request was one of ours and has been answered
async function handle(req, res, u) {
if (!C || req.method !== 'GET') return false;
const p = u.pathname;
if (C.wallet && u.searchParams.has('return') && !/^\/(sso|api|go)(\/|$)/.test(p)) { // a site's "sign in / join on <provider>" link: remember the way back (2026-11-17)
const site = String(u.searchParams.get('return') || '').toLowerCase(); const to = safePath(u.searchParams.get('to'), '/');
const clean = new URL(u.pathname + u.search, 'http://x.invalid'); clean.searchParams.delete('return'); clean.searchParams.delete('to');
const here = safePath(clean.pathname + clean.search, '/');
const base = isBot(req) ? null : await siteBaseFresh(site);
if (!base) return go(res, here); // unknown site (or a bot): the page itself, nothing remembered
let s = null; try { s = await C.member(req); } catch (e) {}
if (s && s.email) { // signed in here already: straight back (wallet step first when the site needs one)
const set = []; const hop = await backHop(s, site, to, set);
set.push(hop === C.walletPath ? ck('nsso.ret', site + '|' + to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
return go(res, hop, set);
}
log('return link remembered', null, 'for ' + siteName(site));
return go(res, here, [ck('nsso.ret', site + '|' + to, RET_AGE, true), ck('nsso.wait', '', 0, true)]);
}
const peerName = NAMES[C.peer] || C.peer;
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
const walletBase = siteBase; freshSites(); // the hand-written list, then the hub's sign-in sites (2026-11-17)
if (goTo && (goTo === C.peer || walletBase(goTo))) {
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
const to = safePath(u.searchParams.get('to'), '/');
const plain = base + to;
if (!enabled() || isBot(req)) return go(res, plain);
let s = null; try { s = await C.member(req); } catch (e) {}
if (!s || !s.email) return go(res, plain);
if (goTo !== C.peer) { let w = null; try { w = await C.wallet(s); } catch (e) {} if (!w || !w.address) return go(res, plain); } // no wallet to vouch for: a plain link
return go(res, base + '/sso/start?mode=go' + (goTo === C.peer ? '' : '&via=' + C.self) + '&to=' + encodeURIComponent(to));
}
if (p === '/sso/start') {
const to = safePath(u.searchParams.get('to'), C.defaultPath);
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
const via = String(u.searchParams.get('via') || '');
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
const viaHub = hubOn() && !u.searchParams.get('nohub') && (await hubUp());
if (!(enabled() || viaHub) || isBot(req) || notPage(req)) return go(res, to);
let s = null; try { s = await C.member(req); } catch (e) {}
if (s && (s.email || s.address)) return go(res, to); // already signed in here
const c = cookies(req);
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off']) && !u.searchParams.get('nohub')) return go(res, to);
const st = crypto.randomBytes(16).toString('hex');
if (viaHub) { // the hub answers for the whole network; the pairwise provider is the fallback when it has nobody (nsso.via)
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true), ck('nsso.via', via || '-', STATE_AGE, true)];
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
return go(res, HUB_BASE() + '/sso/check?site=' + encodeURIComponent(HUB_NAME()) + '&st=' + st + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
}
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
}
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
const clear = [ck('nsso.back', '', 0, true), ck('nsso.wait', '', 0, true)];
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) { // no deliberate tap waiting: a ?return=<site> link may be (2026-11-17)
const ret = retOf(req);
if (!ret || !siteBase(ret.site)) return go(res, C.defaultPath, clear.concat(ck('nsso.ret', '', 0, true)));
let s = null; try { s = await C.member(req); } catch (e) {}
if (!s || !s.email) return go(res, C.signinPath(C.defaultPath)); // not signed in yet: keep it for after the sign-in
const set = clear.slice(); const hop = await backHop(s, ret.site, ret.to, set);
set.push(hop === C.walletPath ? ck('nsso.ret', ret.site + '|' + ret.to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
log('back to ' + siteName(ret.site), s.email); return go(res, hop, set);
}
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')) + '&m=go', clear); // m=go: still a deliberate tap (the wallet step when one is missing)
}
if (p === '/sso/check') {
const st = String(u.searchParams.get('st') || '');
const to = safePath(u.searchParams.get('to'), '/');
const r = String(u.searchParams.get('r') || '');
const wb = r && r !== C.peer ? await siteBaseFresh(r) : null; // a wallet site asking: the token carries the wallet (the hub's sign-in sites too, 2026-11-17)
if (r && r !== C.peer && !wb) { log('check: unknown site asking, nothing sent', null, r.slice(0, 20)); return go(res, C.defaultPath); } // never answer an unknown site as if the peer asked (2026-11-15: 5xYourTeam was sent to LinkSpin)
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = siteName(aud);
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
let s = null; try { s = await C.member(req); } catch (e) {}
if (!s || !s.email) {
if (u.searchParams.get('m') === 'go' && !isBot(req)) { // a deliberate tap: sign in here first, then /sso/resume finishes the trip
log('check: not signed in here, asking to sign in', null, 'for ' + forName);
const back = new URLSearchParams({ st, to }); if (r) back.set('r', r);
return go(res, C.signinPath(C.defaultPath), [ck('nsso.back', back.toString(), BACK_AGE, true)]);
}
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
}
let w = null;
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) {
if (u.searchParams.get('m') === 'go' && C.walletPath && !isBot(req)) { // a deliberate tap: link a wallet here first, then /sso/resume finishes the trip (2026-11-17)
log('check: no wallet on the account, wallet step first', s.email, 'for ' + forName);
const back = new URLSearchParams({ st, to, m: 'go' }); if (r) back.set('r', r);
return go(res, C.walletPath, [ck('nsso.back', back.toString(), BACK_AGE, true), ck('nsso.wait', '1', BACK_AGE, true)]);
}
log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
log('token issued', s.email, 'for ' + forName);
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
}
if (p === '/sso/in') {
const c = cookies(req);
const set = [ck('nsso.st', '', 0, true)];
if (u.searchParams.get('none')) {
const nto = safePath(u.searchParams.get('to'), C.defaultPath);
if (u.searchParams.get('hub') && enabled()) { // nobody on the hub: ask the old pairwise provider once (until every site is switched)
const via = String(c['nsso.via'] || ''); set.push(ck('nsso.via', '', 0, true));
log('none on the hub, trying ' + (NAMES[via] || peerName));
return go(res, '/sso/start?nohub=1&mode=' + (u.searchParams.get('m') === 'go' ? 'go' : 'check') + (via && via !== '-' ? '&via=' + encodeURIComponent(via) : '') + '&to=' + encodeURIComponent(nto), set);
}
log('none: not signed in on ' + (u.searchParams.get('hub') ? 'the hub' : peerName)); return go(res, C.signinPath(nto), set);
}
const fromHub = !!u.searchParams.get('h');
const v = fromHub ? verifyHub(u.searchParams.get('h'), { st: c['nsso.st'] }) : verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in
log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email);
set.push(ck('nsso.hint', v.email, HINT_AGE, true));
return go(res, C.signinPath(v.to), set);
}
let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); }
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
if (fromHub) { const w2 = v.wallet && C.from ? { wallet: v.wallet } : { email: v.email }; set.push(ck('nsso.hp', pushTag(w2), PUSH_AGE, true)); } // the hub already has this sign-in
log('signed in from ' + (fromHub ? 'the network hub' : (NAMES[v.iss] || peerName)), v.email);
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
}
if (p === '/api/sso/status') {
const c = cookies(req); const set = [];
let s = null; try { s = await C.member(req); } catch (e) {}
const signedIn = !!(s && (s.email || s.address));
const out = { peer: hubOn() ? 'the network' : peerName, check: (enabled() || (hubOn() && (await hubUp()))) && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
return sendJson(res, out, set);
}
return false;
}
// every GET a site serves passes here first (2026-11-15): a signed-in member's real page load pings the hub's activity once a day and,
// with the hub on, tells the hub about this sign-in once (nsso.hp). -> true when it answered (the redirect through the hub).
async function page(req, res, u) {
if (!C || !hubCreds()) return false;
const p = u.pathname;
if (!pageLoad(req, p)) return false;
let s = null; try { s = await C.member(req); } catch (e) {}
const w = who(s); if (!w) return false;
activity(w);
if (hubOn() && cookies(req)['nsso.hp'] !== pushTag(w) && (await hubUp())) {
log('hub: telling the hub about this sign-in', w.email || null);
return go(res, HUB_BASE() + '/sso/set?site=' + encodeURIComponent(HUB_NAME()) + '&t=' + mintHub(Object.assign({ to: p + u.search }, w)), [ck('nsso.hp', pushTag(w), PUSH_AGE, true)]);
}
return false;
}
// true when this browser came here from a deliberate network tap (nsso.back) or a ?return=<site> link (nsso.ret) and still has to
// finish it after signing in. False while it waits on the wallet step (nsso.wait): the dashboard must not bounce it back and forth.
const pendingBack = req => { const c = cookies(req); return !!(c['nsso.back'] || retOf(req)) && !c['nsso.wait']; };
// the wallet was just linked: the next hop when a way back is waiting (2026-11-17), else null
const afterWallet = req => { const c = cookies(req); return c['nsso.back'] || retOf(req) ? '/sso/resume' : null; };
// the name of the site a member is on the way back to, for a line on the provider's dashboard; null when none
function backName(req) {
const c = cookies(req); const ret = retOf(req);
if (ret) return siteName(ret.site);
if (!c['nsso.back']) return null;
const r = new URLSearchParams(c['nsso.back']).get('r'); return siteName(r || (C && C.peer) || '') || null;
}
module.exports = { init, handle, page, seen, enabled, pendingBack, afterWallet, backName, siteBase, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES, hubOn, hubCreds, signOutEverywhere, mintHub, verifyHub, _hubSeen: t => { hubSeen = t == null ? Date.now() : t; hubChecked = Date.now(); }, _pinged: pinged, _hubSites: o => { if (o) { hubSites = o; hubSitesAt = Date.now(); } return hubSites; } };
+265
View File
@@ -0,0 +1,265 @@
// 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&amp;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(/<span class="pill on">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(/<span class="pill on">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('>3</b><span>payments'), '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(/<span class="pill off">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);
+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());
+25 -1
View File
@@ -447,8 +447,32 @@ def main():
links = [{'code': x['code'], 'name': str(x.get('name') or '')[:60]} for x in rt
if str(x.get('owner', '')).lower() in mine and not x.get('paused') and any(d.get('active', True) for d in x.get('destinations') or [])]
stacks[un]['pro'] = {'spins': spins[:40], 'links': links[:20]}
# My Stack POL (Marty 2026-11-19): the signed-in member area. Every paid member's own rows (newest first, up to 500), their totals
# (the same sums as their public stack), the wallets mapped to them, whether their page is on, plus IAP's explicit switches and Pro
# owners. Read only by /my for the member who is signed in; never rendered on a public page, so a switched-off member stays hidden.
wl = {}
for a, un in wu.items():
if a and un:
wl.setdefault(str(un).lower(), set()).add(str(a).lower())
members = {}
for r in rows:
un = r['u']
if not un:
continue
m = members.setdefault(un, {'total': 0.0, 'payments': 0, 'since': r['ts'], 'byProg': {}, 'rows': []})
m['total'] += r['pol']; m['payments'] += 1; m['since'] = min(m['since'], r['ts'])
b = m['byProg'].setdefault(r['k'], {'pol': 0.0, 'payments': 0}); b['pol'] += r['pol']; b['payments'] += 1
if len(m['rows']) < 500:
m['rows'].append({'k': r['k'], 'pol': round(r['pol'], 4), 'tx': r['tx'], 'ts': r['ts']})
for un, m in members.items():
m['total'] = round(m['total'], 4)
m['byProg'] = {k: {'pol': round(v['pol'], 4), 'payments': v['payments']} for k, v in m['byProg'].items()}
m['wallets'] = sorted(wl.get(un, set()))
m['page'] = un in stacks
switch = {str(un).lower(): bool(on) for un, on in (so.get('users', {}) if isinstance(so, dict) else {}).items()}
my = {'members': members, 'switch': switch, 'pro': sorted(pro)}
snap = {'v': 1, 'at': now, 'network': {'pol': round(sum(r['pol'] for r in rows), 4), 'payments': len(rows), 'wallets': len(wallets - {''})},
'last7': {'pol': round(sum(r['pol'] for r in l7), 4), 'payments': len(l7)}, 'programs': programs, 'recent': recent, 'progRecent': prog_recent, 'stacks': stacks}
'last7': {'pol': round(sum(r['pol'] for r in l7), 4), 'payments': len(l7)}, 'programs': programs, 'recent': recent, 'progRecent': prog_recent, 'stacks': stacks, 'my': my}
print('network %.2f POL, %d payments, %d wallets | last7 %.2f | stacks %s' % (snap['network']['pol'], snap['network']['payments'], snap['network']['wallets'], snap['last7']['pol'], ','.join(stacks) or '-'))
for k, v in sorted(programs.items(), key=lambda x: -x[1]['pol']):
print(' %-4s %10.2f POL %6d payments %5d wallets' % (k, v['pol'], v['payments'], v['wallets']))