Files
instantadpay/qa/networksso.test.cjs
martbost 1a13f53b9c Login ad on a clock + 5xYourTeam sign-in loop fix (Marty 2026-11-15)
Login ad: shown on the next member page load whenever the member's last finished view on this site is older than loginAdEveryHours (site setting, default 3), signed in just now or not. One row per member in MySQL (loginadclock.js, table login_ad_views; the same file in LinkSpin): /api/ads/slot?type=login answers notDue inside the window and marks the serve; POST /api/ads/login/seen at the end of the countdown restarts the clock only if the serve was at least dwell-2 s earlier (a reload during the countdown does not skip it). Framed gate, 10 s timer, click relay, frameable fallback, delivery and credit accounting unchanged. Welcome tour still outranks it. Member erase forgets the row. Admin site setting label added.

5xYourTeam loop: IAP answered /sso/check?r=fivex as if LinkSpin asked (fivex was missing from the wallets map), so tokens went to LinkSpin and Marty never got back. fivex added (FIVEX_URL, default https://5xyourteam.com); networksso.js now refuses an unknown r instead of answering as the peer. A pending network hop (nsso.back) is finished after sign-in: the login ad (if due) then /sso/resume; the gate's finish button says Continue and goes back to the site and page the member came from. /api/me carries nssoBack. The session pop-up (welcome.js) waits until the login gate is closed.

networksso.js: loop guard TRIED_AGE 30 min -> 120 s (it blocked Marty's silent sign-in on LinkSpin), NAMES gains fivex. The same file now ships byte-identical in IAP, LinkSpin, VBB, DLB, ViralAdBlitz, DownlineHydra, 5xYourTeam.

Tests: qa/networksso-partner.e2e.mjs (new, in run.sh member): a stand-in wallet partner on its own host; signed in on IAP -> straight back with a session, no dashboard, no ad; signed out -> sign in, login ad, Continue -> back on the partner page; the clock (due, too-soon refused, no re-show on reload or another tab, reload during the countdown brings it back); LinkSpin -> partner. networksso unit test: 2-minute guard, unknown site gets nothing. qa member: ALL PASSED (2 known admin warnings).

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

129 lines
12 KiB
JavaScript

// Network sign-in (InstantAdPay <-> LinkSpin, 2026-11-12): unit test of networksso.js. Same file in both repos. node qa/networksso.test.cjs
// Token sign/verify, expiry, clock skew, tamper, wrong audience, state binding, replay, the secret switch, open redirects,
// bots, and the route handler with fake requests (no server, no network, throwaway DATA_DIR).
'use strict';
const fs = require('fs'), os = require('os'), path = require('path'), crypto = require('crypto');
process.env.NETWORK_SSO_SECRET = 'u'.repeat(48);
const N = require('../networksso.js');
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-unit-'));
const st = crypto.randomBytes(16).toString('hex');
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
(async () => {
const sessions = { 'tok-a': { email: 'a@example.com' } };
const accounts = new Set(['a@example.com']);
const signedIn = [];
N.init({ self: 'iap', peer: 'linkspin', peerBase: () => 'https://ls.example', isProd: true, dataDir: DATA, db: null, defaultPath: '/my',
member: async req => sessions[(/sid=([^;]+)/.exec(req.headers.cookie || '') || [])[1]] || null,
accept: async e => accounts.has(e) ? { ok: true } : { fallback: 'no account here yet' },
signIn: async e => { signedIn.push(e); return 'iap.sid=new; Path=/; HttpOnly'; },
landing: to => to, signinPath: to => '/my' });
// ---- tokens ----
const t = N.mint({ iss: 'linkspin', aud: 'iap', email: 'A@Example.com', st, to: '/my#buy' });
let v = N.verify(t, { iss: 'linkspin', aud: 'iap', st });
ok(v.ok && v.email === 'a@example.com' && v.to === '/my#buy', 'round trip: email (lower-cased) and path come back', JSON.stringify(v));
ok(/^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(t), 'token format v1.<payload>.<hmac>');
ok(N.verify(t, { iss: 'linkspin', aud: 'linkspin', st }).error === 'audience', 'wrong audience refused');
ok(N.verify(t, { iss: 'iap', aud: 'iap', st }).error === 'audience', 'wrong issuer refused');
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st, now: Date.now() + 61000 }).error === 'expired', 'expired after 60 s');
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st, now: Date.now() + 55000 }).ok, 'still good at 55 s');
const fut = N.mint({ iss: 'linkspin', aud: 'iap', email: 'a@example.com', st, to: '/', now: Date.now() + 120000 });
ok(N.verify(fut, { iss: 'linkspin', aud: 'iap', st }).error === 'expired', 'issued too far in the future refused');
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st: crypto.randomBytes(16).toString('hex') }).error === 'state', 'state from another browser refused');
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st: '' }).error === 'state', 'missing state cookie refused');
const [, body, mac] = t.split('.');
const pl = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString()); pl.email = 'evil@example.com';
ok(N.verify('v1.' + b64u(JSON.stringify(pl)) + '.' + mac, { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'payload tampered (email swapped) refused');
ok(N.verify('v1.' + body + '.' + (mac[0] === 'A' ? 'B' : 'A') + mac.slice(1), { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'signature tampered refused');
const longer = JSON.parse(JSON.stringify(pl)); longer.email = 'a@example.com'; longer.exp = longer.iat + 3600000;
const forged = 'v1.' + b64u(JSON.stringify(longer)) + '.' + b64u(crypto.createHmac('sha256', process.env.NETWORK_SSO_SECRET).update('nsso.v1.' + b64u(JSON.stringify(longer))).digest());
ok(N.verify(forged, { iss: 'linkspin', aud: 'iap', st }).error === 'expired', 'a validly signed token with a life over 60 s is refused');
ok(N.verify('garbage', { iss: 'linkspin', aud: 'iap', st }).error === 'malformed' && N.verify('', { iss: 'linkspin', aud: 'iap', st }).error === 'malformed', 'garbage refused');
process.env.NETWORK_SSO_SECRET = 'w'.repeat(48);
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'another secret refused');
process.env.NETWORK_SSO_SECRET = 'short';
ok(!N.enabled() && N.verify(t, { iss: 'linkspin', aud: 'iap', st }).error === 'off', 'secret under 32 characters = switched off');
process.env.NETWORK_SSO_SECRET = 'u'.repeat(48);
// ---- replay ----
ok(await N.spend(v.n, v.exp) === true, 'first use of a nonce is spent');
ok(await N.spend(v.n, v.exp) === false, 'second use of the same nonce refused (replay)');
ok(JSON.parse(fs.readFileSync(path.join(DATA, 'network-sso-nonces.json'), 'utf8'))[v.n] > 0, 'spent nonce kept on disk (survives a restart inside the window)');
// ---- open redirects ----
const bad = ['https://evil.example/x', '//evil.example/x', '/\\evil.example', '\\\\evil.example', 'javascript:alert(1)', '/x\r\nSet-Cookie: a=b', ' /my', '/my\t', 'http:/evil.example', '/' + 'a'.repeat(700), '', null];
ok(bad.every(b => N.safePath(b, '/my') === '/my'), 'off-site, protocol-relative, backslash, script, header-injection and over-long paths fall back to the default', bad.map(b => N.safePath(b, '/my')).filter(x => x !== '/my').join(' | '));
ok(N.safePath('/credits?from=iap&task=refuel#refuel') === '/credits?from=iap&task=refuel#refuel' && N.safePath('/my#buy') === '/my#buy', 'same-site paths with query and hash pass');
ok(N.safePath('/%2F%2Fevil.example') === '/%2F%2Fevil.example', 'an encoded // stays a path on this site');
const t2 = N.mint({ iss: 'linkspin', aud: 'iap', email: 'a@example.com', st, to: 'https://evil.example/' });
ok(N.verify(t2, { iss: 'linkspin', aud: 'iap', st }).to === '/', 'a token carrying an off-site path lands on /');
// ---- bots ----
const R = (url, cookie, ua, extra) => ({ method: 'GET', url, headers: Object.assign({ cookie: cookie || '', 'user-agent': ua === undefined ? 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130 Safari/537.36' : ua }, extra || {}) });
ok(N.isBot(R('/', '', 'Googlebot/2.1')) && N.isBot(R('/', '', 'facebookexternalhit/1.1')) && N.isBot(R('/', '', '')) && N.isBot(R('/', '', 'Mozilla/5.0 HeadlessChrome/120')) && !N.isBot(R('/')), 'bots, previews, headless and empty agents are bots; a browser is not');
// ---- the handler ----
const call = async req => { let code = 0, h = {}, body = ''; const res = { writeHead: (c, hh) => { code = c; h = hh || {}; }, end: b => { body = b || ''; } };
const handled = await N.handle(req, res, new URL(req.url, 'http://x')); const set = [].concat(h['Set-Cookie'] || []); return { handled, code, loc: h.Location, set, body }; };
let r = await call(R('/go/linkspin?to=/ads'));
ok(r.code === 302 && r.loc === 'https://ls.example/ads', '/go signed out: a plain link to the other site');
r = await call(R('/go/linkspin?to=//evil.example', 'sid=tok-a'));
ok(r.loc === 'https://ls.example/sso/start?mode=go&to=%2F', '/go never forwards an off-site path', r.loc);
r = await call(R('/go/linkspin?to=/ads%3Fx%3D1', 'sid=tok-a'));
ok(r.loc === 'https://ls.example/sso/start?mode=go&to=%2Fads%3Fx%3D1', '/go signed in: through the other site\'s /sso/start', r.loc);
r = await call(R('/sso/start?to=/my', '', 'Googlebot/2.1'));
ok(r.loc === '/my' && !r.set.length, 'bot on /sso/start: no bounce, no cookies');
r = await call(R('/sso/start?to=/my', '', undefined, { 'sec-fetch-dest': 'empty' }));
ok(r.loc === '/my' && !r.set.length, 'a fetch (not a page load) never bounces');
r = await call(R('/sso/start?to=/my', 'nsso.tried=1'));
ok(r.loc === '/my', 'loop guard: a second silent check inside 2 minutes goes straight to the page');
r = await call(R('/sso/start?to=/my', 'nsso.off=1'));
ok(r.loc === '/my', 'after a sign-out here: no silent check');
r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1'));
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy&m=go$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
r = await call(R('/sso/start?to=https://evil.example'));
const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1];
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=120/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 2-minute guard, off-site path replaced', r.loc);
r = await call(R('/sso/start?to=/my', 'sid=tok-a'));
ok(r.loc === '/my' && !r.set.length, 'already signed in here: no bounce');
r = await call(R('/sso/check?st=' + st + '&to=/ads'));
ok(r.loc === 'https://ls.example/sso/in?none=1&to=%2Fads', 'provider, signed out: none');
r = await call(R('/sso/check?st=nothex&to=/ads', 'sid=tok-a'));
ok(r.loc.includes('none=1'), 'provider: a malformed state gets none, never a token');
r = await call(R('/sso/check?st=' + st + '&to=/ads', 'sid=tok-a'));
const issued = new URL(r.loc).searchParams.get('t');
ok(r.loc.startsWith('https://ls.example/sso/in?t=v1.') && N.verify(issued, { iss: 'iap', aud: 'linkspin', st }).email === 'a@example.com', 'provider, signed in: a token for the other site only, bound to the state');
r = await call(R('/sso/check?st=' + st + '&r=fivex&to=/team', 'sid=tok-a'));
ok(r.loc === '/my' && !/sso\/in/.test(r.loc), 'provider: a site it does not know (r=fivex with no wallets entry) gets nothing, never a token for the peer (2026-11-15)', r.loc);
// receiver: a LinkSpin-issued token arriving here
const mk = (email, to) => N.mint({ iss: 'linkspin', aud: 'iap', email, st, to });
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my#buy'), 'nsso.st=' + st));
ok(r.loc === '/my#buy' && r.set.includes('iap.sid=new; Path=/; HttpOnly') && signedIn.length === 1, 'receiver: valid token -> session cookie, redirect to the path');
const once = mk('a@example.com', '/my');
r = await call(R('/sso/in?t=' + once, 'nsso.st=' + st)); r = await call(R('/sso/in?t=' + once, 'nsso.st=' + st));
ok(signedIn.length === 2 && !r.set.some(c => c.startsWith('iap.sid=')), 'receiver: the same token twice signs in once (replay refused)');
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my'), 'nsso.st=' + crypto.randomBytes(16).toString('hex')));
ok(signedIn.length === 2 && r.loc === '/my', 'receiver: a token pushed into another browser (login CSRF) is refused');
r = await call(R('/sso/in?t=' + issued, 'nsso.st=' + st));
ok(signedIn.length === 2, 'receiver: a token minted FOR the other site is refused here');
r = await call(R('/sso/in?t=' + mk('new@example.com', '/my'), 'nsso.st=' + st));
ok(signedIn.length === 2 && r.loc === '/my' && r.set.some(c => /^nsso\.hint=new%40example\.com;.*HttpOnly/.test(c)), 'receiver: not a member here yet -> normal sign-in with the email kept for the form, nothing created');
r = await call(R('/sso/in?none=1&to=https://evil.example', 'nsso.st=' + st));
ok(r.loc === '/my' && r.set.some(c => /^nsso\.st=;/.test(c)), 'receiver: none -> the sign-in page, never an off-site path');
r = await call(R('/api/sso/status', 'nsso.hint=new%40example.com; nsso.tried=1'));
let j = JSON.parse(r.body); ok(j.hint === 'new@example.com' && j.check === false && r.set.some(c => /^nsso\.hint=;/.test(c)), '/api/sso/status hands the hint over once and clears it');
j = JSON.parse((await call(R('/api/sso/status'))).body); ok(j.check === true && j.peer === 'LinkSpin', '/api/sso/status: signed out, fresh browser -> check');
j = JSON.parse((await call(R('/api/sso/status', 'sid=tok-a'))).body); ok(j.check === false, '/api/sso/status: signed in -> no check');
j = JSON.parse((await call(R('/api/sso/status', '', 'Googlebot/2.1'))).body); ok(j.check === false, '/api/sso/status: bot -> no check');
process.env.NETWORK_SSO_SECRET = '';
r = await call(R('/go/linkspin?to=/ads', 'sid=tok-a')); ok(r.loc === 'https://ls.example/ads', 'secret not set: /go is a plain link');
j = JSON.parse((await call(R('/api/sso/status'))).body); ok(j.check === false, 'secret not set: no silent check');
ok(N.offCookie().startsWith('nsso.off=1;') && /Max-Age=43200/.test(N.offCookie()), 'sign-out cookie pauses the silent check 12 hours');
ok(!(await call({ method: 'POST', url: '/sso/in', headers: {} })).handled, 'non-GET requests are not handled');
})().catch(e => { console.log('FAIL exception', e && e.stack || e); fails++; }).finally(() => {
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exitCode = fails ? 1 : 0;
});