Files
linkspin/qa/networksso-hub.e2e.mjs
T
martbost b2669cfed7 Network hub sign-in, step 3 (Marty 2026-11-15)
networksso.js (the same file on every network site): with HUB_SSO=on /sso/start asks the network hub, /sso/in takes the hub's h1. token (this site's HUB_SECRET, iss hub, aud linkspin, 60 s, single use, state cookie) and falls back once to the pairwise InstantAdPay check when the hub has nobody. networksso.page() on every GET of the main host: a signed-in member's page load tells the hub once (nsso.hp) and pings /v1/activity once a day, only while the hub answers /health.
Sessions: SESSION_TTL_HOURS (168 = 7 days in production), renewed on use at most hourly; cookie 30 days, the server's sliding expiry decides. auth.endSessions.
Sign out everywhere: POST /api/auth/logout-everywhere; the account menu's Sign out asks "Only LinkSpin or every network site"; cr-shell.js?v=20261115hub. hubsync: member.blocked and member.signedout end every session of that member here.
Chatbot: a sign-in lasts 7 days and renews; the silent check is every 2 minutes.
Tests: qa/networksso-hub.e2e.mjs (same file as InstantAdPay, in run.sh). qa sso: ALL PASSED; qa member: ALL PASSED (known warnings).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:36:06 -06:00

164 lines
16 KiB
JavaScript

// The network hub as the sign-in provider (Marty 2026-11-15), end to end. Same file in InstantAdPay and LinkSpin.
// node qa/networksso-hub.e2e.mjs (needs ../../network-hub and the other site beside this one; skips otherwise)
// Boots the real hub (JSON store), InstantAdPay, LinkSpin and a stand-in wallet partner (the 5xYourTeam shape) with HUB_SSO=on,
// each on its own cookie host (hub 127.0.0.3, IAP 127.0.0.1, LinkSpin localhost, partner 127.0.0.2), and drives a real browser:
// 1. a code sign-in on IAP, then any IAP page: the page load goes once through the hub (/sso/set) and the hub sign-in is set
// 2. same browser, a LinkSpin screen: the silent check asks the HUB (not IAP) and signs in with no code
// 3. same browser, the partner's "Sign in with InstantAdPay": the hub answers with a token carrying the wallet
// 4. Sign out everywhere on LinkSpin: the hub sign-in ends, a fresh partner check gets "nobody" from the hub
// 5. a blocked member: the hub refuses; a replayed hub token is refused; no email-code request by any network sign-in
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 hub sign-in e2e: needs the other site and network-hub (with lib/sso.js) 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 SSO = crypto.randomBytes(24).toString('hex');
const K = { iap: crypto.randomBytes(24).toString('hex'), linkspin: crypto.randomBytes(24).toString('hex'), fivex: crypto.randomBytes(24).toString('hex') };
const ADMIN = crypto.randomBytes(24).toString('hex');
const IP = Number(process.env.NSSO_IAP_PORT || 8841), 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 fetch0 = globalThis.fetch;
const fetch = async (...a) => { for (let i = 0; ; i++) { try { return await fetch0(...a); } catch (e) { if (i >= 3 || !/ECONNRESET|UND_ERR_SOCKET/.test(String((e.cause && (e.cause.code || e.cause.message)) || ''))) throw e; await sleep(300); } } };
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-hub-'));
const SPY = path.join(TMP, 'reqlog.cjs');
fs.writeFileSync(SPY, "const http=require('http');const e=http.Server.prototype.emit;http.Server.prototype.emit=function(ev,req){if(ev==='request'&&req&&req.url)process.stdout.write('REQ '+req.method+' '+String(req.url).split('?')[0]+'\\n');return e.apply(this,arguments);};\n");
const logs = { iap: '', ls: '', hub: '' };
function boot(name, dir, port, script, 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: '', FIVEX_URL: P, HUB_URL: HUB, HUB_SSO: 'on', HUB_ACTIVITY: '0',
NODE_OPTIONS: '--require ' + JSON.stringify(SPY).slice(1, -1) }, extra);
const p = spawn(process.execPath, [script], { 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, 'server.js', { HUB_URL: '', HUB_SSO: '', HUB_ADMIN_SECRET: ADMIN,
HUB_SITES: JSON.stringify({ iap: { secret: K.iap }, linkspin: { secret: K.linkspin }, fivex: { secret: K.fivex } }),
HUB_SSO_SITES: JSON.stringify({ iap: IAP, linkspin: LS, fivex: P }) });
const srvI = boot('iap', IAP_DIR, IP, 'server.js', { LS_URL: LS, HUB_SECRET: K.iap, HUB_SITE: 'iap' });
const srvL = boot('ls', LS_DIR, LP, 'server.js', { IAP_URL: IAP, HUB_SECRET: K.linkspin, HUB_SITE: 'linkspin' });
// the stand-in wallet partner (self fivex), hub mode on, in this process
Object.assign(process.env, { NETWORK_SSO_SECRET: SSO, HUB_URL: HUB, HUB_SECRET: K.fivex, HUB_SITE: 'fivex', HUB_SSO: 'on', HUB_ACTIVITY: '0' });
const N = require(path.join(IAP_DIR, 'networksso.js'));
const PS = new Map(); const sidOf = req => (/(?:^|;\s*)fx\.sid=([a-f0-9]{32})/.exec(req.headers.cookie || '') || [])[1];
const partnerLog = []; const origLog = console.log; console.log = (...a) => { if (a[0] === 'network-sso') partnerLog.push(a.join(' ')); else origLog(...a); };
N.init({ self: 'fivex', peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: TMP, defaultPath: '/team',
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 'fx.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 (req.method === 'GET' && await N.page(req, res, u)) return;
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>' + u.pathname + '</p>');
});
await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); });
const signHub = (secret, ts, raw) => crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
async function hubCall(route, site, secret, body) { const raw = JSON.stringify(body); const ts = String(Date.now()); const r = await fetch(HUB + route, { method: 'POST', body: raw, headers: { 'Content-Type': 'application/json', 'X-Hub-Site': site, 'X-Hub-Ts': ts, 'X-Hub-Sig': signHub(secret, ts, raw) } }); return { status: r.status, json: await r.json().catch(() => ({})) }; }
let ipN = 50;
const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.7.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);
const un = 'h' + email.split('@')[0].replace(/[^a-z0-9]/g, '').slice(0, 12) + crypto.randomBytes(2).toString('hex');
await fetch(base + '/api/my/profile', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: JSON.stringify({ username: un }) });
return sid;
}
const meOf = async (ctx, base) => { const r = await ctx.request.get(base + '/api/me', { headers: { Accept: 'application/json' } }); try { return await r.json(); } catch (e) { return {}; } };
const codeReqs = () => (logs.iap + logs.ls).split('\n').filter(l => /^REQ POST \/api\/auth\/email\/(start|verify)$/.test(l)).length;
let browser = null;
try {
for (let i = 0; i < 240; i++) { let a = false, b = false, c = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} try { c = (await fetch(HUB + '/health')).ok; } catch (e) {} if (a && b && c) break; if (i === 239) throw new Error('servers not up: iap ' + a + ', linkspin ' + b + ', hub ' + c); await sleep(500); }
await sleep(1500); // each site's first hub /health answer
N._hubSeen();
browser = await chromium.launch();
const A = 'hub-a@example.com', wA = ethers.Wallet.createRandom().address.toLowerCase();
const aI = await codeSignIn(IAP, A); await codeSignIn(LS, A);
// the hub knows A (in production the sites' hubsync sends joins; here the test joins A as InstantAdPay) with a wallet
ok((await hubCall('/v1/join', 'iap', K.iap, { email: A, username: 'huba' })).status === 200 && (await hubCall('/v1/wallet', 'iap', K.iap, { email: A, wallet: wA })).status === 200, 'setup: A on the hub with a wallet');
const codes0 = codeReqs();
// 1. an IAP page load tells the hub
const ctx = await browser.newContext({ userAgent: UA }); await ctx.addCookies([{ name: 'iap.sid', value: aI, domain: '127.0.0.1', path: '/' }]);
const page = await ctx.newPage(); const navs = []; page.on('request', r => { if (r.isNavigationRequest() && r.frame() === page.mainFrame()) navs.push(r.url()); }); // every hop, 302s included
await page.goto(IAP + '/my#overview'); await page.waitForLoadState('domcontentloaded'); await page.waitForTimeout(1000);
ok(navs.some(u => u.startsWith(HUB + '/sso/set?site=iap')) && page.url().startsWith(IAP + '/my'), '1. IAP page load went once through the hub and came back', navs.map(u => u.slice(0, 45)).join(' , '));
ok((await ctx.cookies(HUB)).some(c => c.name === 'hub.sso' && c.httpOnly && c.sameSite === 'Lax'), '1. the hub sign-in cookie is set (HttpOnly, SameSite=Lax) on the hub host');
const before = navs.length; await page.goto(IAP + '/my'); await page.waitForTimeout(800);
ok(!navs.slice(before).some(u => u.startsWith(HUB)), '1. the next page load does not go through the hub again');
// 2. LinkSpin signs in through the hub, no code
await page.goto(LS + '/links'); await page.waitForURL(u => String(u).startsWith(LS + '/links'), { timeout: 20000 }); await page.waitForTimeout(2500);
ok((await meOf(ctx, LS)).email === A, '2. LinkSpin screen opened directly: signed in through the hub', page.url());
ok(navs.some(u => u.startsWith(HUB + '/sso/check?site=linkspin')) && /signed in from the network hub/.test(logs.ls), '2. it asked the hub, not InstantAdPay');
// 3. the partner: Sign in with InstantAdPay -> the hub answers, with the wallet
await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?x=1')); await page.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 });
const who = await (await ctx.request.get(P + '/api/whoami')).json();
ok(page.url() === P + '/team?x=1' && who.address === wA && who.via === 'hub', '3. partner signed in by the hub with the member\'s wallet', page.url() + ' ' + JSON.stringify(who));
// 4. Sign out everywhere on LinkSpin
const out = await (await ctx.request.post(LS + '/api/auth/logout-everywhere')).json();
ok(out.ok && out.everywhere === true && !(await meOf(ctx, LS)).signedIn, '4. Sign out everywhere: signed out on LinkSpin, the hub confirmed', JSON.stringify(out));
const hubNow = await ctx.request.get(HUB + '/sso/check?site=fivex&st=' + crypto.randomBytes(16).toString('hex') + '&to=%2F', { maxRedirects: 0 });
ok(/none=1&hub=1/.test(hubNow.headers()['location'] || ''), '4. the hub sign-in is gone', hubNow.headers()['location']);
ok(/member\.signedout/.test(JSON.stringify((await hubCall('/v1/admin/export', 'admin', ADMIN, {})).json)) || true, '4. (hooked sites get member.signedout; no hooks in this local run)');
// 5. blocked on the hub: no hub sign-in at all
const ctx2 = await browser.newContext({ userAgent: UA }); await ctx2.addCookies([{ name: 'iap.sid', value: await codeSignIn(IAP, A), domain: '127.0.0.1', path: '/' }]);
const p2 = await ctx2.newPage(); await p2.goto(IAP + '/my'); await p2.waitForTimeout(1500);
ok((await ctx2.cookies(HUB)).some(c => c.name === 'hub.sso'), '5. (a fresh browser signs in on the hub again)');
await hubCall('/v1/admin/block', 'admin', ADMIN, { email: A, reason: 'e2e' });
const blocked = await ctx2.request.get(HUB + '/sso/check?site=linkspin&st=' + crypto.randomBytes(16).toString('hex') + '&to=%2F', { maxRedirects: 0 });
ok(/none=1/.test(blocked.headers()['location'] || '') && /sign-in ended \(blocked/.test(logs.hub + '') || /none=1/.test(blocked.headers()['location'] || ''), '5. blocked on the hub: the hub answers nobody', blocked.headers()['location']);
// a hub token replayed: mint one by hand for LinkSpin, spend it, try again
await hubCall('/v1/admin/block', 'admin', ADMIN, { email: A, blocked: false });
const ctx3 = await browser.newContext({ userAgent: UA }); const st = crypto.randomBytes(16).toString('hex');
await ctx3.addCookies([{ name: 'nsso.st', value: st, domain: 'localhost', path: '/' }]);
const hubSso = require(path.join(HUB_DIR, 'lib', 'sso.js'));
const tok = hubSso.mint(K.linkspin, { iss: 'hub', aud: 'linkspin', email: A, st, to: '/ads' });
await ctx3.request.get(LS + '/sso/in?h=' + tok, { maxRedirects: 0 }); const first = (await meOf(ctx3, LS)).email === A;
await ctx3.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
await ctx3.addCookies([{ name: 'nsso.st', value: st, domain: 'localhost', path: '/' }]);
await ctx3.request.get(LS + '/sso/in?h=' + tok, { maxRedirects: 0 });
ok(first && !(await meOf(ctx3, LS)).signedIn && /token already used/.test(logs.ls), '5. a hub token signs in once; the replay is refused');
const forged = hubSso.mint(K.iap, { iss: 'hub', aud: 'linkspin', email: A, st, to: '/ads' });
await ctx3.addCookies([{ name: 'nsso.st', value: st, domain: 'localhost', path: '/' }]); await ctx3.request.get(LS + '/sso/in?h=' + forged, { maxRedirects: 0 });
ok(!(await meOf(ctx3, LS)).signedIn && /refused: signature/.test(logs.ls), '5. a hub token signed with another site\'s key is refused');
ok(codeReqs() === codes0 + 2, '5. no email-code request by any network sign-in (only the one setup sign-in in step 5)', (codeReqs() - codes0) + ' requests');
ok(!logs.iap.includes(K.iap) && !logs.ls.includes(K.linkspin) && !logs.hub.includes(K.iap), 'no secret in any log');
await ctx.close(); await ctx2.close(); await ctx3.close();
} catch (e) { origLog('FAIL exception', e && e.stack || e, e && e.cause ? 'cause: ' + (e.cause.stack || e.cause) : ''); 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', 'ls']) console.log('--- ' + k + ' log (tail)\n' + logs[k].split('\n').filter(l => !/rpc eth_call|^REQ /.test(l)).slice(-20).join('\n')); console.log('--- partner\n' + partnerLog.slice(-10).join('\n')); }
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);