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:
+452
@@ -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; } };
|
||||
Reference in New Issue
Block a user