Files
instantadpay/qa/networksso-return.e2e.mjs
T
martbost 72160c6a10 Network sign-in: the way back to every network site (Marty 2026-11-17: "I just logged in to Instant Ad Pay from Viral Ad Source, and it never had a return path back")
Root cause: IAP's networksso `wallets` list was hand-written and had no ViralAdSource line, so
/sso/check?r=viraladsource was refused ("unknown site asking") and the browser was sent to the
IAP dashboard: a signed-out visitor to viraladsource.com/my was even dropped there by the silent
check, and a signed-in IAP member could never be signed in on ViralAdSource through IAP.
- networksso.js: providers also answer every site in the hub's GET /v1/sso-sites; ?return=<site>
  &to=/path links remember the way back (nsso.ret, known sites only); /sso/resume finishes it
  after the code sign-in; a wallet site with no wallet on the account goes to the Wallet tab
  first (nsso.wait, no bounce loop) and the wallet link answers next: /sso/resume; the tap state
  lives 1 hour.
- server.js: every /go/<site> and ?return= request goes to networksso (no per-site list; fivex
  was missing from it too); walletPath /my#wallet; /api/me nssoBackTo; wallet link next/backTo.
- my.js: "Taking you back to <site>" after the wallet link; one line on the Wallet tab while a
  site waits for the wallet. my.js?v=20261117back.
- qa/networksso-return.e2e.mjs: hub-only site, silent check, tap, wallet step, return links,
  no open redirect. All network sign-in suites and iap-qa member pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 07:21:19 -06:00

195 lines
18 KiB
JavaScript

// 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);