// Network sign-in from a partner wallet site (5xYourTeam pattern) through InstantAdPay, with the login ad on its clock (2026-11-15). // Same file in InstantAdPay and LinkSpin. node qa/networksso-partner.e2e.mjs // Marty was stranded: 5xYourTeam's "get a position" sent him to sign in through InstantAdPay; IAP answered r=fivex as if LinkSpin // asked, and after a fresh sign-in the login ad's "Go to dashboard" left him on the IAP dashboard. This boots IAP and LinkSpin on // throwaway DATA_DIRs plus a stand-in partner (the same networksso.js as a wallet receiver, self 'fivex', on 127.0.0.2: its own // cookie host) and drives a real browser. Proves: // A. signed in on IAP (wallet linked): partner /sso/start -> straight back to the partner page with a session, no IAP page, no ad // B. signed out: partner -> IAP sign-in -> code -> the login ad -> its finish button says Continue -> back on the partner page, // signed in; the countdown restarted the member's clock (the next ask answers notDue) // C. the login-ad clock on a plain dashboard load: due -> the gate shows, after the countdown it does not show again on reload // D. signed in on LinkSpin (wallet linked): partner via=linkspin -> straight back with a session // No mail key, JSON stores, devCode. Skips when the other repo is not beside this one. 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 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) { console.log('SKIP partner sign-in e2e: the other repo was not found. Set NSSO_PEER_DIR.'); process.exit(0); } 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 SECRET = crypto.randomBytes(24).toString('hex'); const IP = Number(process.env.NSSO_IAP_PORT || 8831), LP = IP + 1, PP = IP + 2; const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP, P = 'http://127.0.0.2:' + PP; 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-partner-')); 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: '', DOCSTORE_URL: '', LS_SYNC_SECRET: '', HUB_ENABLED: '', FIVEX_URL: P }, 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 }); // the stand-in partner: a wallet receiver exactly like 5xYourTeam (self fivex, asks IAP or LinkSpin, sessions by wallet) process.env.NETWORK_SSO_SECRET = SECRET; 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]; N.init({ self: 'fivex', peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: path.join(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 (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('
' + u.pathname + '
'); }); await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); }); let ipN = 30; const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.8.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); // members have a username (the dashboard asks for one before anything else) const un = 'p' + 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) throw new Error('username on ' + base + ': ' + pr.status + ' ' + (await pr.text()).slice(0, 120)); return sid; } // link a throwaway wallet to the signed-in account (the dashboard's Link wallet: challenge, personal_sign, verify) 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 on ' + base + ': ' + j.error); return { address: w.address.toLowerCase(), sid: sidFrom(v) || sid }; } const host = base => new URL(base).hostname; let browser = null; async function newCtx(sessions) { const ctx = await browser.newContext({ userAgent: UA }); const add = Object.entries(sessions || {}).map(([base, sid]) => ({ name: 'iap.sid', value: sid, domain: host(base), path: '/' })); if (add.length) await ctx.addCookies(add); return ctx; } 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; }; 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: iap ' + a + ', linkspin ' + b); await sleep(500); } browser = await chromium.launch(); // a house login ad on IAP (the admin path), so the gate has something to show const hc = await fetch(IAP + '/api/admin/campaigns', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer localtest' }, body: JSON.stringify({ type: 'login', name: 'QA login sponsor', targetUrl: 'https://example.com/' }) }); const hj = await hc.json().catch(() => ({})); ok(hc.ok && !hj.error, 'setup: a house login ad on InstantAdPay', JSON.stringify(hj).slice(0, 160)); // signed out (bots, probes, link previews): no login ad drawn and no view counted, on either site const so = await (await fetch(IAP + '/api/ads/slot?type=login')).json(); const imps = async () => ((await (await fetch(IAP + '/api/admin/campaigns', { headers: { Authorization: 'Bearer localtest' } })).json()).campaigns || []).filter(c => c.type === 'login').reduce((t, c) => t + (Number(c.imps) || 0), 0); ok(so.signedOut === true && !so.ad && (await imps()) === 0, 'signed out: /api/ads/slot?type=login draws nothing and counts no view on IAP', JSON.stringify(so)); const sl = await (await fetch(LS + '/api/ads/slot?type=login')).json(); ok(sl.signedOut === true && !sl.ad, 'signed out: nothing on LinkSpin either', JSON.stringify(sl)); // A. signed in on IAP with a wallet: straight back to the partner page with a session, never an IAP page, no login ad const A = 'partner-a@example.com'; const wa = await linkWallet(IAP, await codeSignIn(IAP, A)); let ctx = await newCtx({ [IAP]: wa.sid }); let page = await ctx.newPage(); let navs = mainNavs(page); await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?pick=1#buy')); await page.waitForLoadState('domcontentloaded'); let who = await whoami(ctx); ok(page.url() === P + '/team?pick=1#buy' && who.address === wa.address && who.via === 'iap', 'A. signed in on IAP: back on the partner page signed in as the linked wallet', page.url() + ' ' + JSON.stringify(who)); ok(!navs.some(u => u.startsWith(IAP + '/my')), 'A. no IAP dashboard and no login ad on the way', navs.join(' , ')); ok(/token issued p\*\*\*@example\.com for 5xYourTeam/.test(logs.iap), 'A. IAP logged a token for 5xYourTeam (never "for LinkSpin")'); await ctx.close(); // B. signed out on IAP: sign in there, the login ad shows, its Continue goes back to the partner page const B = 'partner-b@example.com'; const wb = await linkWallet(IAP, await codeSignIn(IAP, B)); await fetch(IAP + '/api/auth/logout', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + wb.sid }), body: '{}' }); ctx = await newCtx(); page = await ctx.newPage(); navs = mainNavs(page); await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?pick=2')); await page.waitForSelector('#mcEmail', { timeout: 15000 }); ok(page.url().startsWith(IAP + '/my') && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), 'B. signed out: IAP asks for its sign-in and remembers the trip', page.url()); await page.fill('#mcEmail', B); 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'); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 }); ok(true, 'B. the login ad shows after the fresh sign-in'); await page.click('#lgOpen'); await page.waitForSelector('#lgContinue:not([hidden])', { timeout: 20000 }); ok((await page.textContent('#lgContinue')).trim() === 'Continue', 'B. its finish button continues the trip (not "Go to dashboard")', await page.textContent('#lgContinue')); await page.click('#lgContinue'); await page.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 }); who = await whoami(ctx); ok(page.url() === P + '/team?pick=2' && who.address === wb.address, 'B. back on the partner page it came from, signed in', page.url() + ' ' + JSON.stringify(who)); const again = await (await ctx.request.get(IAP + '/api/ads/slot?type=login')).json(); ok(again.notDue === true && !again.ad, 'B. the countdown restarted the clock: the next ask on IAP is not due', JSON.stringify(again).slice(0, 120)); await ctx.close(); // C. the clock on a plain dashboard load (no sign-in on this page): due -> the gate; after the countdown, a reload shows no gate const C = 'partner-c@example.com'; const cI = await codeSignIn(IAP, C); ctx = await newCtx({ [IAP]: cI }); page = await ctx.newPage(); await page.goto(IAP + '/my'); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 }); ok((await page.textContent('#lgContinue')).trim() === 'Go to dashboard', 'C. signed in earlier, first dashboard load: the login ad shows (due), finish says Go to dashboard'); const early = await (await ctx.request.post(IAP + '/api/ads/login/seen')).json(); ok(early.ok === false && early.reason === 'too soon', 'C. telling the server "seen" before the countdown is refused', JSON.stringify(early)); await page.click('#lgOpen', { timeout: 10000 }); await page.waitForSelector('#lgContinue:not([hidden])', { timeout: 20000 }); await page.waitForTimeout(800); await page.click('#lgContinue'); ok(await page.locator('#loginGate').isHidden(), 'C. Go to dashboard closes the gate'); await page.reload(); await page.waitForTimeout(3500); ok(await page.locator('#loginGate').isHidden(), 'C. a reload inside the setting (3 hours) shows no login ad'); const d2 = await ctx.newPage(); await d2.goto(IAP + '/my'); await d2.waitForTimeout(3000); ok(await d2.locator('#loginGate').isHidden(), 'C. nor does another tab'); await ctx.close(); // and a reload DURING the countdown does not skip it const D0 = 'partner-d0@example.com'; const d0 = await codeSignIn(IAP, D0); ctx = await newCtx({ [IAP]: d0 }); page = await ctx.newPage(); await page.goto(IAP + '/my'); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 }); await page.click('#lgOpen'); await page.waitForTimeout(2000); await page.reload(); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 }); ok(true, 'C. a reload during the countdown brings the login ad back'); await ctx.close(); // D. signed in on LinkSpin with a wallet: via=linkspin, straight back to the partner const D = 'partner-d@example.com'; const wd = await linkWallet(LS, await codeSignIn(LS, D)); ctx = await newCtx({ [LS]: wd.sid }); page = await ctx.newPage(); navs = mainNavs(page); await page.goto(P + '/sso/start?mode=go&via=linkspin&to=' + encodeURIComponent('/team')); await page.waitForLoadState('domcontentloaded'); who = await whoami(ctx); ok(page.url() === P + '/team' && who.address === wd.address && who.via === 'linkspin', 'D. signed in on LinkSpin: back on the partner page signed in', page.url() + ' ' + JSON.stringify(who)); ok(/token issued p\*\*\*@example\.com for 5xYourTeam/.test(logs.ls), 'D. LinkSpin logged a token for 5xYourTeam'); // E. LinkSpin's login-ad clock: a house login ad, then the member's clock (served, too soon refused, finished, not due) const lh = await fetch(LS + '/api/admin/campaigns', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer localtest' }, body: JSON.stringify({ type: 'login', name: 'QA LS login sponsor', targetUrl: 'https://example.com/' }) }); const lhj = await lh.json().catch(() => ({})); if (!lh.ok || lhj.error) ok(false, 'E. setup: a house login ad on LinkSpin', lh.status + ' ' + JSON.stringify(lhj).slice(0, 160)); else { const lsGet = async () => (await ctx.request.get(LS + '/api/ads/slot?type=login')).json(); const lsSeen = async () => (await ctx.request.post(LS + '/api/ads/login/seen')).json(); let x = await lsGet(); ok(!!(x.ad && x.ad.targetUrl), 'E. LinkSpin: due -> a login ad', JSON.stringify(x).slice(0, 100)); x = await lsSeen(); ok(x.ok === false && x.reason === 'too soon', 'E. LinkSpin: "seen" before the countdown is refused', JSON.stringify(x)); await sleep(9000); x = await lsSeen(); ok(x.ok === true, 'E. LinkSpin: after the countdown the clock restarts', JSON.stringify(x)); x = await lsGet(); ok(x.notDue === true && !x.ad, 'E. LinkSpin: inside the setting, no login ad', JSON.stringify(x)); } await ctx.close(); } catch (e) { console.log('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) {} try { srvI.kill(); } catch (e) {} try { srvL.kill(); } catch (e) {} try { partner.close(); } 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 (tail)\n' + logs[k].split('\n').filter(l => !/rpc eth_call/.test(l)).slice(-30).join('\n')); } console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);