Files
linkspin/qa/networksso.e2e.mjs
T
martbost 73bee6c826 Login ad on a clock, hop back to the asking site, 5xYourTeam in the wallets map, signed-out login slot refused (Marty 2026-11-15)
Login ad: every Control Room page asks (cr-shell.js loginAd, the per-tab sessionStorage guard is gone); the server answers with an ad only when the member's last finished view on LinkSpin is older than loginAdEveryHours (site setting, default 3). loginadclock.js (the same file as InstantAdPay), MySQL table login_ad_views through DOCSTORE_URL. POST /api/ads/login/seen at the end of the countdown restarts the clock only if the serve was dwell-2 s earlier. Member erase forgets the row. Admin site setting label.
Signed out: /api/ads/slot?type=login draws nothing and counts no view (bots, probes, previews cannot run up an advertiser's numbers).
Hop: a member who signed in here because another network site asked ("Sign in with LinkSpin", nsso.back) goes back there after the login ad (/sso/resume), from every Control Room screen, not only the retired /my.
networksso.js: the network-wide copy (loop guard 120 s, fivex, unknown r refused); fivex added to the wallets map (FIVEX_URL, default https://5xyourteam.com).
Tests: qa/networksso-partner.e2e.mjs (same file as InstantAdPay, in run.sh): partner via LinkSpin, LinkSpin clock, signed-out slot; networksso e2e retries a keep-alive ECONNRESET. qa sso: ALL PASSED; qa member: ALL PASSED (2 known warnings; networksso e2e flaked on ECONNRESET once, passes with the retry).

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

223 lines
19 KiB
JavaScript

// Network sign-in (InstantAdPay <-> LinkSpin, 2026-11-12) end to end: boots BOTH servers locally on throwaway DATA_DIRs and drives
// a real browser across them. Same file in both repos. node qa/networksso.e2e.mjs
// The other repo is found at NSSO_PEER_DIR, else ../../linkspin/site or ../../onchain-ad-membership/site from this site dir.
// InstantAdPay runs on http://127.0.0.1:<port> and LinkSpin on http://localhost:<port>: two hosts, so the two sites' cookies
// stay apart like instantadpay.com and linkspin.app do. No mail key on either copy (no email can leave), JSON stores, devCode.
// Proves: IAP -> LinkSpin and LinkSpin -> IAP arrive signed in without a code; the silent check on a sign-in page (signed in on
// the other site -> in; not -> the normal sign-in, one bounce only); signed out on the other site -> normal sign-in; a replayed or
// expired token is refused; an email not on the receiving site yet gets the email-code form prefilled, nothing created; sign-out
// stays per site; bots never bounce; no email-code request is made 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 { 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 peerGuess = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean);
const PEER = peerGuess.find(d => fs.existsSync(path.join(d, 'server.js')));
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
if (!PEER || !fs.existsSync(path.join(IAP_DIR, 'networksso.js')) || !fs.existsSync(path.join(LS_DIR, 'networksso.js'))) {
console.log('SKIP network sign-in e2e: the other repo (with networksso.js) was not found. Set NSSO_PEER_DIR.'); process.exit(0);
}
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
const SECRET = crypto.randomBytes(24).toString('hex');
const IP = Number(process.env.NSSO_IAP_PORT || 8821), LP = Number(process.env.NSSO_LS_PORT || 8822);
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP;
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));
// an idle keep-alive socket the server closed (5 s default) while the browser launched: the request never reached it, send again
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-e2e-'));
// a request log on each server (method + path only), so "no email-code request was made" is checked on the server side
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: '' };
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: SECRET, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', LS_SYNC_SECRET: '', NODE_OPTIONS: '--require ' + JSON.stringify(SPY).slice(1, -1) }, 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 srvI = boot('iap', IAP_DIR, IP, { LS_URL: LS });
const srvL = boot('ls', LS_DIR, LP, { IAP_URL: IAP });
const reqs = name => logs[name].split('\n').filter(l => l.startsWith('REQ '));
const codeReqs = () => reqs('iap').concat(reqs('ls')).filter(l => /\/api\/auth\/email\/(start|verify)$/.test(l)).length;
// sign in through the email code over plain HTTP (a separate client: its own IP via x-forwarded-for, its own device)
let ipN = 10;
async function codeSignIn(base, email) {
const h = { 'Content-Type': 'application/json', 'x-forwarded-for': '10.9.0.' + (ipN++), 'User-Agent': UA };
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 = (v.headers.getSetCookie ? v.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid='));
if (!sid) throw new Error('code sign-in failed on ' + base + ' for ' + email + ': ' + JSON.stringify(sj) + ' / ' + v.status + ' ' + (await v.text()).slice(0, 200));
return sid.slice('iap.sid='.length);
}
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 {}; } };
async function newCtx(sessions) {
const ctx = await browser.newContext({ userAgent: UA });
const add = [];
if (sessions && sessions.iap) add.push({ name: 'iap.sid', value: sessions.iap, domain: '127.0.0.1', path: '/' });
if (sessions && sessions.ls) add.push({ name: 'iap.sid', value: sessions.ls, domain: 'localhost', path: '/' });
if (add.length) await ctx.addCookies(add);
return ctx;
}
let browser = null;
try {
for (let i = 0; i < 60; 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; await sleep(500); }
browser = await chromium.launch();
// members: A and B have accounts on both sites, C only on InstantAdPay, D only on LinkSpin
const A = 'nsso-a@example.com', B = 'nsso-b@example.com', C = 'nsso-c@example.com', D = 'nsso-d@example.com';
const aI = await codeSignIn(IAP, A); await codeSignIn(LS, A);
const bL = await codeSignIn(LS, B); await codeSignIn(IAP, B);
const cI = await codeSignIn(IAP, C);
const dL = await codeSignIn(LS, D);
const codes0 = codeReqs();
// 1. IAP -> LinkSpin through the /go hop
let ctx = await newCtx({ iap: aI }); let page = await ctx.newPage();
await page.goto(IAP + '/go/linkspin?to=' + encodeURIComponent('/ads'));
await page.waitForLoadState('domcontentloaded');
let me = await meOf(ctx, LS);
ok(page.url() === LS + '/ads' && me.signedIn && me.email === A, 'IAP -> LinkSpin: lands on /ads signed in as the same member, no code', page.url() + ' ' + JSON.stringify({ s: me.signedIn, e: me.email }));
ok((await meOf(ctx, IAP)).email === A, 'IAP session untouched');
// sign-out on LinkSpin stays on LinkSpin, and the silent check does not sign them straight back in
await ctx.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
await page.goto(LS + '/ads'); await page.waitForTimeout(2500);
me = await meOf(ctx, LS);
ok(!me.signedIn && page.url() === LS + '/ads', 'signed out on LinkSpin: stays signed out there (no automatic sign-in back)', page.url());
ok((await meOf(ctx, IAP)).email === A, 'signing out of LinkSpin leaves InstantAdPay signed in');
// a deliberate link from IAP still signs them in after the sign-out
await page.goto(IAP + '/go/linkspin?to=' + encodeURIComponent('/credits?from=iap&task=refuel#refuel')); await page.waitForLoadState('domcontentloaded');
me = await meOf(ctx, LS);
ok(me.email === A && page.url() === LS + '/credits?from=iap&task=refuel#refuel', 'after a sign-out, a link from InstantAdPay signs in again and keeps the query and hash', page.url());
await ctx.close();
// 2. LinkSpin -> IAP through the /go hop (dashboard gets ?welcome=1, the step a code sign-in takes for the login ad)
ctx = await newCtx({ ls: bL }); page = await ctx.newPage();
const navs = []; page.on('framenavigated', f => { if (f === page.mainFrame()) navs.push(f.url()); });
await page.goto(LS + '/go/iap?to=' + encodeURIComponent('/my#engine')); await page.waitForLoadState('domcontentloaded');
me = await meOf(ctx, IAP);
ok(me.signedIn && me.email === B && navs.some(u => u.startsWith(IAP + '/my?welcome=1#engine')), 'LinkSpin -> IAP: lands on /my#engine signed in as the same member, no code', navs.slice(-2).join(' , '));
await ctx.close();
// 3. silent check: signed in on IAP, open a LinkSpin screen directly
ctx = await newCtx({ iap: aI }); page = await ctx.newPage();
await page.goto(LS + '/links'); await page.waitForURL(u => String(u).startsWith(LS + '/links'), { timeout: 15000 }); await page.waitForTimeout(2500);
me = await meOf(ctx, LS);
ok(me.email === A && page.url() === LS + '/links', 'silent check: a LinkSpin screen opened directly signs in through IAP', page.url());
await ctx.close();
// and the other way: signed in on LinkSpin, open the IAP dashboard
ctx = await newCtx({ ls: bL }); page = await ctx.newPage();
await page.goto(IAP + '/my'); await page.waitForTimeout(4000);
me = await meOf(ctx, IAP);
ok(me.email === B && page.url().startsWith(IAP + '/my'), 'silent check: the IAP sign-in page signs in through LinkSpin', page.url());
await ctx.close();
// 4. silent check, signed in nowhere: one bounce, then the normal sign-in; no second bounce on reload
ctx = await newCtx(); page = await ctx.newPage();
const starts = []; page.on('request', r => { if (r.url().includes('/sso/start')) starts.push(r.url()); });
await page.goto(LS + '/ads'); await page.waitForTimeout(3000);
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads' && starts.length === 1, 'signed in nowhere: one bounce, back on the page signed out', starts.length + ' bounce(s), ' + page.url());
ok(await page.locator('#siEmail').isVisible(), 'the normal email-code sign-in shows');
await page.reload(); await page.waitForTimeout(2500);
ok(starts.length === 1, 'reload inside 2 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)');
await page.goto(IAP + '/my'); await page.waitForTimeout(3000);
ok(!(await meOf(ctx, IAP)).signedIn && starts.length === 2 && (await page.locator('#mcEmail').count()) === 1, 'IAP /my signed in nowhere: one bounce, then the normal sign-in', starts.length + ' bounce(s), ' + page.url());
await ctx.close();
// 5. expired / absent session on the provider: signed out on IAP, the /go link is a plain link and LinkSpin asks for the code
const aI2 = await codeSignIn(IAP, A);
ctx = await newCtx({ iap: aI2 }); page = await ctx.newPage();
await ctx.request.post(IAP + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
await page.goto(IAP + '/go/linkspin?to=%2Fads'); await page.waitForTimeout(2500);
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads', 'signed out on IAP: /go/linkspin is a plain link, LinkSpin shows its sign-in', page.url());
await ctx.close();
// a session that expired on the provider: the check answers none
ctx = await newCtx({ iap: 'f'.repeat(64) }); page = await ctx.newPage();
await page.goto(LS + '/sso/start?mode=go&to=%2Fads'); await page.waitForTimeout(1500);
ok(!(await meOf(ctx, LS)).signedIn && page.url().startsWith(IAP + '/my'), 'an expired IAP session on a deliberate tap: IAP asks for its own sign-in first (2026-11-14)', page.url());
ok((await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), 'IAP remembers the unfinished trip while the member signs in');
await ctx.close();
// 6. not on the receiving site yet: C (IAP only) going to LinkSpin, D (LinkSpin only) going to IAP
ctx = await newCtx({ iap: cI }); page = await ctx.newPage();
await page.goto(IAP + '/go/linkspin?to=%2Fads'); await page.waitForSelector('#siEmail', { timeout: 10000 }); await page.waitForTimeout(1500);
ok(!(await meOf(ctx, LS)).signedIn && (await page.inputValue('#siEmail')) === C && (await page.locator('#nssoNote').count()) === 1, 'IAP member not on LinkSpin yet: LinkSpin sign-in with the email filled in, nothing signed', await page.inputValue('#siEmail'));
ok(!fs.readFileSync(path.join(TMP, 'ls', 'accounts.json'), 'utf8').includes(C), 'no LinkSpin account was created by the network sign-in');
await ctx.close();
ctx = await newCtx({ ls: dL }); page = await ctx.newPage();
await page.goto(LS + '/go/iap?to=%2Fmy'); await page.waitForTimeout(4000);
ok(!(await meOf(ctx, IAP)).signedIn && page.url().startsWith(IAP + '/my') && (await page.inputValue('#mcEmail').catch(() => '')) === D, 'LinkSpin member not on IAP yet: IAP sign-in with the email filled in, nothing signed', page.url() + ' ' + (await page.inputValue('#mcEmail').catch(() => '?')));
await ctx.close();
// 7. replay: walk the hops by hand, spend the token once, then try it again with the state cookie put back
const aI3 = await codeSignIn(IAP, A);
ctx = await newCtx({ iap: aI3 });
const hop = async url => { const r = await ctx.request.get(url, { maxRedirects: 0, headers: { 'User-Agent': UA, 'sec-fetch-dest': 'document' } }); return r.headers()['location'] || ''; };
let loc = await hop(LS + '/sso/start?mode=go&to=%2Fads');
const st = (await ctx.cookies(LS)).find(c => c.name === 'nsso.st');
loc = await hop(loc.startsWith('http') ? loc : LS + loc);
ok(/^http:\/\/localhost:\d+\/sso\/in\?t=v1\./.test(loc), 'provider minted a token for LinkSpin', loc.slice(0, 60));
const tokUrl = loc;
let land = await hop(tokUrl);
ok(land === '/ads' && (await meOf(ctx, LS)).email === A, 'first use signs in');
await ctx.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
await ctx.addCookies([{ name: 'nsso.st', value: st.value, domain: 'localhost', path: '/' }]);
land = await hop(tokUrl);
ok(!(await meOf(ctx, LS)).signedIn && /token already used/.test(logs.ls), 'the same token again is refused (replay), even with the state cookie put back', land);
// a token from a different browser (state cookie missing) is refused: login CSRF
const ctx2 = await newCtx({ iap: aI3 });
const r2 = await ctx2.request.get(LS + '/sso/start?mode=go&to=%2Fads', { maxRedirects: 0, headers: { 'sec-fetch-dest': 'document' } });
const l2 = await ctx2.request.get(r2.headers()['location'], { maxRedirects: 0 });
const other = await newCtx(); const r3 = await other.request.get(l2.headers()['location'], { maxRedirects: 0 });
ok(!(await meOf(other, LS)).signedIn && /refused: state/.test(logs.ls), 'a token opened in another browser (no matching state) is refused', r3.headers()['location']);
await ctx2.close(); await other.close();
// an expired token (minted by hand with a past clock) is refused
const require = createRequire(import.meta.url); process.env.NETWORK_SSO_SECRET = SECRET;
const N = require(path.join(IAP_DIR, 'networksso.js'));
const st2 = crypto.randomBytes(16).toString('hex');
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]);
const old = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads', now: Date.now() - 120000 });
await hop(LS + '/sso/in?t=' + old);
ok(!(await meOf(ctx, LS)).signedIn && /refused: expired/.test(logs.ls), 'an expired token is refused');
const forged = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads' }).replace(/.$/, c => c === 'A' ? 'B' : 'A');
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]); await hop(LS + '/sso/in?t=' + forged);
ok(!(await meOf(ctx, LS)).signedIn && /refused: signature/.test(logs.ls), 'a tampered token is refused');
// open redirect: an off-site path never leaves the site
const ev = await hop(IAP + '/go/linkspin?to=' + encodeURIComponent('https://evil.example/x'));
ok(ev === LS + '/sso/start?mode=go&to=%2F', '/go with an off-site path stays on the network', ev);
const ev2 = await ctx.request.get(LS + '/sso/in?none=1&to=' + encodeURIComponent('//evil.example'), { maxRedirects: 0 });
ok(ev2.headers()['location'] === '/ads', '/sso/in never redirects off the site', ev2.headers()['location']);
await ctx.close();
// 8. bots and API calls never bounce
const bot = await fetch(LS + '/sso/start?to=%2Fads', { redirect: 'manual', headers: { 'User-Agent': 'Googlebot/2.1 (+http://www.google.com/bot.html)' } });
ok(bot.headers.get('location') === '/ads' && !(bot.headers.getSetCookie ? bot.headers.getSetCookie() : []).length, 'a crawler on /sso/start goes straight to the page');
const bs = await (await fetch(IAP + '/api/sso/status', { headers: { 'User-Agent': 'Googlebot/2.1' } })).json();
ok(bs.check === false, 'a crawler is never told to check');
// 9. no email-code request was made by any network sign-in (only the setup code sign-ins above)
const total = codeReqs();
ok(total === codes0 + 4, 'no email-code request made by any network sign-in (server request log: only the 2 later setup sign-ins, start + verify each)', 'before ' + codes0 + ', after ' + total);
ok(!/sendCode|sendgrid/i.test(logs.iap + logs.ls), 'no mail send attempted on either server');
ok(/network-sso signed in from InstantAdPay n\*\*\*@example\.com/.test(logs.ls) && /network-sso signed in from LinkSpin n\*\*\*@example\.com/.test(logs.iap), 'successes logged with the email masked');
ok(!logs.iap.includes(SECRET) && !logs.ls.includes(SECRET) && !/nsso-a@example\.com/.test((logs.iap + logs.ls).split('\n').filter(l => l.includes('network-sso')).join('\n')), 'no secret and no full email in the network sign-in log lines');
} catch (e) { console.log('FAIL exception', e && e.stack || e); fails++; }
finally {
try { if (browser) await browser.close(); } catch (e) {}
try { srvI.kill(); } catch (e) {} try { srvL.kill(); } catch (e) {}
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
}
if (fails) { for (const k of ['iap', 'ls']) console.log('--- ' + k + ' log (network-sso / errors)\n' + logs[k].split('\n').filter(l => /network-sso|error|Error/.test(l)).slice(-25).join('\n')); }
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);