Network sign-in: the way back to every network site (Marty 2026-11-17)
networksso.js now also answers every site in the hub's GET /v1/sso-sites (the hand-written list missed sites, the ViralAdSource bug), ?return=<site>&to=/path links remember the way back and /sso/resume finishes it after the sign-in, and the deliberate-tap state lives 1 hour. Every /go/<site> and ?return= request goes to networksso (no per-site line in server.js any more). qa/networksso-return.e2e.mjs: a hub-only site, silent check, tap, wallet step, return links, no open redirect. All network sign-in suites pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+100
-14
@@ -37,6 +37,17 @@
|
||||
// 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');
|
||||
@@ -47,8 +58,9 @@ 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 = 1200; // seconds: the state cookie on a deliberate tap (time to sign in on the provider first, 2026-11-14)
|
||||
const BACK_AGE = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in
|
||||
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
|
||||
@@ -74,8 +86,25 @@ async function hubUp() {
|
||||
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() } }
|
||||
// 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');
|
||||
@@ -232,7 +261,25 @@ const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/;
|
||||
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(() => {}); } }
|
||||
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);
|
||||
@@ -241,9 +288,24 @@ const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
||||
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 = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
|
||||
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'), '/');
|
||||
@@ -277,17 +339,25 @@ async function handle(req, res, u) {
|
||||
}
|
||||
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)];
|
||||
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
|
||||
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')), clear);
|
||||
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 ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
|
||||
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 = NAMES[aud] || aud;
|
||||
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) {}
|
||||
@@ -300,7 +370,13 @@ async function handle(req, res, u) {
|
||||
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())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
|
||||
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 }));
|
||||
}
|
||||
@@ -360,7 +436,17 @@ async function page(req, res, u) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
|
||||
const pendingBack = req => !!cookies(req)['nsso.back'];
|
||||
// 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, 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 };
|
||||
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; } };
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
// The way back to a network site after signing in on InstantAdPay (Marty 2026-11-17: "I just logged in to Instant Ad Pay from
|
||||
// Viral Ad Source, and it never had a return path back"). Same file in InstantAdPay and LinkSpin.
|
||||
// node qa/networksso-return.e2e.mjs (needs ../../network-hub and the other site beside this one; skips otherwise)
|
||||
// The partner here is a site InstantAdPay has NO hand-written line for (the ViralAdSource case): only the hub's HUB_SSO_SITES lists
|
||||
// it, and IAP learns it from the hub's public GET /v1/sso-sites. Real hub (JSON store), IAP, LinkSpin, a stand-in wallet partner
|
||||
// (the ViralAdSource shape: email-less, signs in by wallet), each on its own cookie host, driven by a real browser:
|
||||
// 1. signed in nowhere, the partner's silent check: back on the partner's own sign-in page, never dropped on the IAP dashboard
|
||||
// 2. a deliberate tap, signed out on IAP: IAP's sign-in, the code, then back on the exact partner page, signed in by wallet
|
||||
// 3. a deliberate tap, signed in on IAP with no wallet yet: the IAP Wallet tab (no bounce loop), the wallet link, then back
|
||||
// 4. a ?return=<site>&to=/path link on IAP: remembered, the URL cleaned, the code sign-in, then back on that partner page
|
||||
// 5. the same link while signed in: straight back; /go/<site> works for a hub-only site
|
||||
// 6. never an open redirect: an unknown ?return= is ignored, an off-site to= becomes /
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import http from 'node:http';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
|
||||
const PEER = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||
const HUB_DIR = [process.env.HUB_DIR, path.resolve(HERE, '../../network-hub')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'lib', 'sso.js')));
|
||||
if (!PEER || !HUB_DIR) { console.log('SKIP return e2e: needs the other site and network-hub beside this repo.'); process.exit(0); }
|
||||
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
|
||||
const require = createRequire(import.meta.url);
|
||||
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||
const { ethers } = require(path.join(IAP_DIR, 'node_modules', 'ethers'));
|
||||
const SITE = 'newsite'; // in no provider's hand-written list
|
||||
const SSO = crypto.randomBytes(24).toString('hex');
|
||||
const K = { iap: crypto.randomBytes(24).toString('hex'), linkspin: crypto.randomBytes(24).toString('hex'), [SITE]: crypto.randomBytes(24).toString('hex') };
|
||||
const IP = Number(process.env.NSSO_IAP_PORT || 8861), LP = IP + 1, PP = IP + 2, HP = IP + 3;
|
||||
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP, P = 'http://127.0.0.2:' + PP, HUB = 'http://127.0.0.3:' + HP;
|
||||
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-ret-'));
|
||||
const logs = { iap: '', ls: '', hub: '' };
|
||||
function boot(name, dir, port, extra) {
|
||||
const data = path.join(TMP, name); fs.mkdirSync(path.join(data, 'uploads'), { recursive: true });
|
||||
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: data, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DEV_POL_USD: '0.10',
|
||||
NETWORK_SSO_SECRET: SSO, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', DOCSTORE_URL: '', LS_SYNC_SECRET: '', HUB_ENABLED: '', HUB_URL: HUB, HUB_SSO: 'on', HUB_ACTIVITY: '0' }, extra);
|
||||
const p = spawn(process.execPath, ['server.js'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env });
|
||||
p.stdout.on('data', d => logs[name] += d); p.stderr.on('data', d => logs[name] += d); return p;
|
||||
}
|
||||
const srvH = boot('hub', HUB_DIR, HP, { HUB_URL: '', HUB_SSO: '', HUB_ADMIN_SECRET: crypto.randomBytes(24).toString('hex'),
|
||||
HUB_SITES: JSON.stringify({ iap: { secret: K.iap }, linkspin: { secret: K.linkspin }, [SITE]: { secret: K[SITE] } }),
|
||||
HUB_SSO_SITES: JSON.stringify({ iap: IAP, linkspin: LS, [SITE]: P }) });
|
||||
// the hub has to answer /v1/sso-sites before IAP and LinkSpin start (they read it at start, and again when an unknown site asks)
|
||||
for (let i = 0; i < 120; i++) { try { if ((await fetch(HUB + '/health')).ok) break; } catch (e) {} await sleep(250); }
|
||||
const srvI = boot('iap', IAP_DIR, IP, { LS_URL: LS, HUB_SECRET: K.iap, HUB_SITE: 'iap' });
|
||||
const srvL = boot('ls', LS_DIR, LP, { IAP_URL: IAP, HUB_SECRET: K.linkspin, HUB_SITE: 'linkspin' });
|
||||
|
||||
// the stand-in partner (the ViralAdSource shape), hub mode on, in this process
|
||||
Object.assign(process.env, { NETWORK_SSO_SECRET: SSO, HUB_URL: HUB, HUB_SECRET: K[SITE], HUB_SITE: SITE, HUB_SSO: 'on', HUB_ACTIVITY: '0' });
|
||||
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||
const PS = new Map(); const sidOf = req => (/(?:^|;\s*)ns\.sid=([a-f0-9]{32})/.exec(req.headers.cookie || '') || [])[1];
|
||||
const origLog = console.log; const partnerLog = []; console.log = (...a) => { if (a[0] === 'network-sso') partnerLog.push(a.join(' ')); else origLog(...a); };
|
||||
N.init({ self: SITE, peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: TMP, defaultPath: '/my',
|
||||
member: async req => { const s = PS.get(sidOf(req)); return s ? { address: s.address } : null; },
|
||||
accept: async (e, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
||||
signIn: async (e, req, v) => { const id = crypto.randomBytes(16).toString('hex'); PS.set(id, { address: v.wallet, via: v.iss }); return 'ns.sid=' + id + '; Path=/; HttpOnly; SameSite=Lax'; },
|
||||
landing: to => to, signinPath: to => '/signin?to=' + encodeURIComponent(to) });
|
||||
const partner = http.createServer(async (req, res) => {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
if (await N.handle(req, res, u)) return;
|
||||
if (u.pathname === '/api/whoami') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(PS.get(sidOf(req)) || {})); }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>partner</title><p id="pg">' + u.pathname + '</p>');
|
||||
});
|
||||
await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); });
|
||||
|
||||
let ipN = 70;
|
||||
const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.9.0.' + (ipN++), 'User-Agent': UA });
|
||||
const sidFrom = r => ((r.headers.getSetCookie ? r.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid=')) || '').slice('iap.sid='.length);
|
||||
async function codeSignIn(base, email) {
|
||||
const h = H();
|
||||
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
|
||||
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
|
||||
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
|
||||
const sid = sidFrom(v); if (!sid) throw new Error('code sign-in failed on ' + base + ': ' + JSON.stringify(sj) + ' ' + v.status);
|
||||
const un = 'r' + email.split('@')[0].replace(/[^a-z0-9]/g, '').slice(0, 14) + crypto.randomBytes(2).toString('hex');
|
||||
const pr = await fetch(base + '/api/my/profile', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: JSON.stringify({ username: un }) });
|
||||
if (!pr.ok && !(await (await fetch(base + '/api/me', { headers: { Cookie: 'iap.sid=' + sid } })).json()).username) throw new Error('username on ' + base + ': ' + pr.status); // a second sign-in: the name is set already
|
||||
return sid;
|
||||
}
|
||||
async function linkWallet(base, sid) {
|
||||
const w = ethers.Wallet.createRandom(); const h = Object.assign(H(), { Cookie: 'iap.sid=' + sid });
|
||||
const ch = await (await fetch(base + '/api/auth/challenge', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address }) })).json();
|
||||
const v = await fetch(base + '/api/auth/verify', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address, signature: await w.signMessage(ch.message) }) });
|
||||
const j = await v.json(); if (j.error) throw new Error('wallet link: ' + j.error);
|
||||
return { address: w.address.toLowerCase(), sid: sidFrom(v) || sid };
|
||||
}
|
||||
const logout = sid => fetch(IAP + '/api/auth/logout', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: '{}' });
|
||||
// the IAP dashboard's email-code sign-in, in the browser (the form's 4-second human timer included)
|
||||
async function uiSignIn(page, email) {
|
||||
await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||
await page.fill('#mcEmail', email); await page.waitForTimeout(4600); await page.click('#mcSendBtn');
|
||||
await page.waitForFunction(() => document.getElementById('mcCode') && document.getElementById('mcCode').value.length === 6, null, { timeout: 15000 });
|
||||
await page.click('#mcVerifyBtn');
|
||||
}
|
||||
const whoami = async ctx => (await (await ctx.request.get(P + '/api/whoami')).json());
|
||||
const mainNavs = page => { const n = []; page.on('framenavigated', f => { if (f === page.mainFrame()) n.push(f.url()); }); return n; };
|
||||
let browser = null;
|
||||
const newCtx = async sid => { const c = await browser.newContext({ userAgent: UA }); if (sid) await c.addCookies([{ name: 'iap.sid', value: sid, domain: '127.0.0.1', path: '/' }]); return c; };
|
||||
|
||||
try {
|
||||
for (let i = 0; i < 240; i++) { let a = false, b = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} if (a && b) break; if (i === 239) throw new Error('servers not up'); await sleep(500); }
|
||||
await sleep(1500); N._hubSeen();
|
||||
browser = await chromium.launch();
|
||||
const sites = await (await fetch(HUB + '/v1/sso-sites')).json();
|
||||
ok(sites.sites && sites.sites[SITE] === P, 'setup: the hub lists the partner at GET /v1/sso-sites', JSON.stringify(sites));
|
||||
|
||||
// 1. the 2026-11-17 bug: signed in nowhere, the partner's silent check dropped the visitor on the IAP dashboard
|
||||
let ctx = await newCtx(); let page = await ctx.newPage(); let navs = mainNavs(page);
|
||||
await page.goto(P + '/sso/start?mode=check&to=' + encodeURIComponent('/my')); await page.waitForLoadState('domcontentloaded'); await page.waitForTimeout(800);
|
||||
ok(page.url() === P + '/signin?to=%2Fmy', '1. signed in nowhere: back on the partner\'s own sign-in page', page.url());
|
||||
ok(!navs.some(u => u.startsWith(IAP + '/my')), '1. never dropped on the InstantAdPay dashboard', navs.map(u => u.slice(0, 60)).join(' , '));
|
||||
ok(!/unknown site asking/.test(logs.iap), '1. IAP knows the hub-only site (no "unknown site asking")');
|
||||
await ctx.close();
|
||||
|
||||
// 2. a deliberate tap while signed out on IAP: sign in there, then back on the exact partner page
|
||||
const B = 'ret-b@example.com'; const wb = await linkWallet(IAP, await codeSignIn(IAP, B)); await logout(wb.sid);
|
||||
ctx = await newCtx(); page = await ctx.newPage();
|
||||
await page.goto(P + '/sso/start?mode=go&to=' + encodeURIComponent('/my?tab=post#new')); await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||
ok(page.url().startsWith(IAP + '/my') && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), '2. signed out on IAP: IAP asks for its sign-in and remembers the trip', page.url());
|
||||
await uiSignIn(page, B);
|
||||
await page.waitForURL(u => String(u).startsWith(P + '/my'), { timeout: 20000 });
|
||||
let who = await whoami(ctx);
|
||||
ok(page.url() === P + '/my?tab=post#new' && who.address === wb.address, '2. after the code: back on the exact partner page, signed in by wallet', page.url() + ' ' + JSON.stringify(who));
|
||||
await ctx.close();
|
||||
|
||||
// 3. signed in on IAP with no wallet yet: the Wallet tab first, no bounce, then the wallet link sends it back
|
||||
const C = 'ret-c@example.com'; const sc = await codeSignIn(IAP, C);
|
||||
ctx = await newCtx(sc); page = await ctx.newPage(); navs = mainNavs(page);
|
||||
await page.goto(P + '/sso/start?mode=go&to=' + encodeURIComponent('/my?c=3')); await page.waitForURL(u => String(u).startsWith(IAP + '/my'), { timeout: 15000 }); await page.waitForTimeout(3500);
|
||||
ok(page.url() === IAP + '/my#wallet' && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.wait'), '3. no wallet yet: the IAP Wallet tab, waiting', page.url());
|
||||
const resumes = navs.filter(u => u.includes('/sso/resume')).length;
|
||||
ok(resumes === 0, '3. the dashboard does not bounce back and forth while it waits', resumes + ' resume hops');
|
||||
await page.waitForFunction(() => /signs you in with your wallet/.test((document.getElementById('status') || {}).textContent || ''), null, { timeout: 8000 }).catch(() => {});
|
||||
const st3 = await page.evaluate(() => (document.getElementById('status') || {}).textContent || '');
|
||||
ok(/newsite signs you in with your wallet/.test(st3) && !/\u2014/.test(st3), '3. one plain line says why and what to do', st3);
|
||||
const w3 = ethers.Wallet.createRandom();
|
||||
const ch = await (await ctx.request.post(IAP + '/api/auth/challenge', { headers: H(), data: { address: w3.address } })).json();
|
||||
const lk = await (await ctx.request.post(IAP + '/api/auth/verify', { headers: H(), data: { address: w3.address, signature: await w3.signMessage(ch.message) } })).json();
|
||||
ok(lk.linked && lk.next === '/sso/resume' && lk.backTo === SITE, '3. the wallet link answers with the way back', JSON.stringify({ next: lk.next, backTo: lk.backTo }));
|
||||
await page.goto(IAP + lk.next); await page.waitForURL(u => String(u).startsWith(P + '/my'), { timeout: 15000 });
|
||||
who = await whoami(ctx);
|
||||
ok(page.url() === P + '/my?c=3' && who.address === w3.address.toLowerCase(), '3. back on the partner page, signed in with the new wallet', page.url() + ' ' + JSON.stringify(who));
|
||||
await ctx.close();
|
||||
|
||||
// 4. a ?return= link on IAP (a site's "Join free" / "Sign in on InstantAdPay" link), signed out
|
||||
const D = 'ret-d@example.com'; const wd = await linkWallet(IAP, await codeSignIn(IAP, D)); await logout(wd.sid);
|
||||
ctx = await newCtx(); page = await ctx.newPage();
|
||||
await page.goto(IAP + '/my?x=1&return=' + SITE + '&to=' + encodeURIComponent('/post?y=2')); await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||
const ret = (await ctx.cookies(IAP)).find(c => c.name === 'nsso.ret');
|
||||
ok(!/return=|to=/.test(page.url()) && ret && decodeURIComponent(ret.value) === SITE + '|/post?y=2' && ret.httpOnly, '4. remembered (HttpOnly), the URL cleaned', page.url());
|
||||
await uiSignIn(page, D);
|
||||
await page.waitForURL(u => String(u).startsWith(P + '/post'), { timeout: 20000 });
|
||||
who = await whoami(ctx);
|
||||
ok(page.url() === P + '/post?y=2' && who.address === wd.address, '4. after the code: back on that partner page, signed in', page.url() + ' ' + JSON.stringify(who));
|
||||
ok(!(await ctx.cookies(IAP)).some(c => c.name === 'nsso.ret'), '4. the way back is used once');
|
||||
|
||||
// 5. the same link while signed in on IAP: straight back; /go/<site> for a hub-only site
|
||||
const sd = await codeSignIn(IAP, D); const ctx5 = await newCtx(sd); const p5 = await ctx5.newPage();
|
||||
await p5.goto(IAP + '/?return=' + SITE + '&to=' + encodeURIComponent('/team')); await p5.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 });
|
||||
ok(p5.url() === P + '/team' && (await whoami(ctx5)).address === wd.address, '5. signed in already: straight back, signed in', p5.url());
|
||||
const ctx5b = await newCtx(sd); const p5b = await ctx5b.newPage();
|
||||
await p5b.goto(IAP + '/go/' + SITE + '?to=' + encodeURIComponent('/stats')); await p5b.waitForURL(u => String(u).startsWith(P + '/stats'), { timeout: 15000 });
|
||||
ok(p5b.url() === P + '/stats' && (await whoami(ctx5b)).address === wd.address, '5. /go/<site> signs in on a site only the hub lists', p5b.url());
|
||||
await ctx5.close(); await ctx5b.close(); await ctx.close();
|
||||
|
||||
// 6. never an open redirect
|
||||
ctx = await newCtx(); page = await ctx.newPage();
|
||||
await page.goto(IAP + '/my?return=evil&to=' + encodeURIComponent('/x')); await page.waitForLoadState('domcontentloaded');
|
||||
ok(new URL(page.url()).search === '' && !(await ctx.cookies(IAP)).some(c => c.name === 'nsso.ret'), '6. an unknown ?return= is ignored and the URL cleaned', page.url());
|
||||
await page.goto(IAP + '/my?return=' + SITE + '&to=' + encodeURIComponent('//evil.example/x')); await page.waitForLoadState('domcontentloaded');
|
||||
const r6 = (await ctx.cookies(IAP)).find(c => c.name === 'nsso.ret');
|
||||
ok(r6 && decodeURIComponent(r6.value) === SITE + '|/', '6. an off-site to= becomes /', r6 && decodeURIComponent(r6.value));
|
||||
const r6b = await ctx.request.get(IAP + '/my?return=' + SITE + '&to=%2Fa', { maxRedirects: 0, headers: { 'User-Agent': 'curl/8' } });
|
||||
ok(r6b.status() === 302 && !(r6b.headers()['set-cookie'] || '').includes('nsso.ret'), '6. a bot remembers nothing');
|
||||
await ctx.close();
|
||||
ok(!logs.iap.includes(K.iap) && !logs.hub.includes(K[SITE]), 'no secret in any log');
|
||||
} catch (e) { origLog('FAIL exception', e && e.stack || e); fails++; }
|
||||
finally {
|
||||
try { if (browser) await browser.close(); } catch (e) {}
|
||||
for (const s of [srvI, srvL, srvH]) { try { s.kill(); } catch (e) {} } try { partner.close(); } catch (e) {}
|
||||
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
|
||||
}
|
||||
console.log = origLog;
|
||||
if (fails) { for (const k of ['hub', 'iap']) console.log('--- ' + k + ' log (tail)\n' + logs[k].split('\n').filter(l => /sso/.test(l)).slice(-25).join('\n')); console.log('--- partner\n' + partnerLog.slice(-15).join('\n')); }
|
||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||
@@ -1461,7 +1461,8 @@ const server = http.createServer(async (req, res) => {
|
||||
if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
|
||||
// network sign-in with InstantAdPay (2026-11-12): /go/iap, /sso/start, /sso/check, /sso/in, /api/sso/status (app host only)
|
||||
if (req.method === 'GET' && !isPagesHost(req) && !isLinkHost(req) && await networksso.page(req, res, u)) return; // network hub: daily activity ping + the hub sign-in push (2026-11-15)
|
||||
if (req.method === 'GET' && (p === '/go/iap' || p === '/go/viraladblitz' || p === '/go/downlinehydra' || p.startsWith('/sso/') || p === '/api/sso/status') && !isPagesHost(req) && !isLinkHost(req) && await networksso.handle(req, res, u)) return;
|
||||
// every /go/<site> and every ?return=<site> link goes to networksso (2026-11-17): it knows the hub's sign-in sites, so a new site no longer needs a line here
|
||||
if (req.method === 'GET' && (p.startsWith('/go/') || p.startsWith('/sso/') || p === '/api/sso/status' || u.searchParams.has('return')) && !isPagesHost(req) && !isLinkHost(req) && await networksso.handle(req, res, u)) return;
|
||||
|
||||
// -- the rotator redirect: one hop, recorded, on any host (LinkSpin)
|
||||
let rm = /^\/r\/([a-z0-9]{4,12})$/i.exec(p);
|
||||
|
||||
Reference in New Issue
Block a user