// End-to-end check of the sponsor follow through the REAL sync code (lssync.js -> LinkSpin /api/partner/registry and // iapsync.js -> InstantAdPay /api/partner/registry, the hash and registry loop guards, the Sponsor check endpoints). // Boots a local InstantAdPay AND a local LinkSpin, each on a throwaway data dir seeded with the same few accounts (JSON // stores, no DATABASE_URL, no mail key, no engine key), pointed ONLY at each other with a throwaway LS_SYNC_SECRET. // Nothing touches production. Needs the LinkSpin repo beside this one (LS_SITE to override). // node qa/sponsorfollow-e2e.mjs import { spawn, execSync } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; const require = createRequire(import.meta.url); const HERE = path.dirname(fileURLToPath(import.meta.url)); const IAP_SITE = path.join(HERE, '..'); const LS_SITE = process.env.LS_SITE || path.join(IAP_SITE, '..', '..', 'linkspin', 'site'); const SECRET = 'qa-sponsorfollow-' + 'x'.repeat(40); process.env.LS_SYNC_SECRET = SECRET; const SF = require(path.join(IAP_SITE, 'sponsorfollow.js')); const IAP_PORT = Number(process.env.SF_E2E_PORT || 8811), LS_PORT = IAP_PORT + 1, IAP = 'http://127.0.0.1:' + IAP_PORT, LS = 'http://127.0.0.1:' + LS_PORT; const sleep = ms => new Promise(r => setTimeout(r, ms)); let pass = 0, fail = 0; const lines = []; const ok = (cond, name, extra) => { if (cond) { pass++; lines.push('ok ' + name); } else { fail++; lines.push('FAIL ' + name + (extra ? '\n ' + extra : '')); } }; const now = Date.now(); const acct = (email, username, o) => Object.assign({ email, pass: null, sponsorRef: '', code: ('c' + username).slice(0, 7), username, address: null, created: now - 20 * 86400000, lastSeen: now - 3600000, memberId: 0 }, o || {}); function seed(dir, list) { fs.mkdirSync(path.join(dir, 'uploads'), { recursive: true }); const db = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: 0, positions: {} }; for (const a of list) { db.byEmail[a.email] = a; db.byCode[a.code] = a.email; } fs.writeFileSync(path.join(dir, 'accounts.json'), JSON.stringify(db)); } const base = () => [acct('boss@qa.test', 'qaboss', { memberId: 77 }), acct('lead5@qa.test', 'leadfive'), acct('adopter@qa.test', 'adopter', { memberId: 0 }), acct('old@qa.test', 'oldsponsor'), acct('lead1@qa.test', 'leadone'), acct('lead2@qa.test', 'leadtwo', { sponsorRef: 'oldsponsor' }), acct('lead4@qa.test', 'leadfour', { sponsorRef: 'oldsponsor' })]; const iapDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-e2e-iap-')), lsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-e2e-ls-')); // lead3 is bound on InstantAdPay (memberId), lead4 joined LinkSpin under someone else (ordinary, already different) seed(iapDir, base().concat([acct('lead3@qa.test', 'leadthree', { memberId: 42, sponsorRef: 'oldsponsor' })])); seed(lsDir, base().map(a => a.email === 'lead4@qa.test' ? Object.assign(a, { sponsorRef: 'adopter' }) : a).concat([acct('lead3@qa.test', 'leadthree', { sponsorRef: 'oldsponsor' })])); const env = (port, dir, extra) => Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_EMAIL: 'admin@qa.test', ADMIN_PASSWORD: 'localtest', LS_SYNC_SECRET: SECRET, DATABASE_URL: '', SENDGRID_API_KEY: '', ENGINE_KEY: '', ENGINE_KEY_FILE: '' }, extra); for (const k of ['DATABASE_URL', 'NETWORK_DB_URL']) delete process.env[k]; const procs = []; function boot(site, port, dir, extra, log) { const p = spawn(process.execPath, ['server.js'], { cwd: site, env: env(port, dir, extra), stdio: ['ignore', fs.openSync(log, 'w'), fs.openSync(log, 'a')] }); procs.push(p); return p; } async function up(url) { for (let i = 0; i < 40; i++) { try { const r = await fetch(url + '/api/config', { signal: AbortSignal.timeout(2000) }); if (r.status < 500) return true; } catch (e) {} await sleep(1000); } return false; } const admin = async (url, pth, body, method) => { const r = await fetch(url + pth, { method: method || (body ? 'POST' : 'GET'), headers: { Authorization: 'Bearer localtest', 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined }); return r.json(); }; const facts = async (url, email) => ((await SF.peerPost(url, '/api/partner/sponsor-facts', { emails: [email] })).rows || [])[0] || null; async function waitFor(fn, ms) { const t0 = Date.now(); while (Date.now() - t0 < (ms || 20000)) { try { if (await fn()) return true; } catch (e) {} await sleep(700); } return false; } const OUT = path.join(IAP_SITE, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true }); try { boot(IAP_SITE, IAP_PORT, iapDir, { LS_URL: LS }, path.join(OUT, 'sf-e2e-iap.log')); boot(LS_SITE, LS_PORT, lsDir, { IAP_URL: IAP, SITE_HOST: '127.0.0.1:' + LS_PORT, TANK_RESCUE: '' }, path.join(OUT, 'sf-e2e-ls.log')); ok(await up(IAP), 'local InstantAdPay up'); ok(await up(LS), 'local LinkSpin up'); // 1. a deliberate change on InstantAdPay (admin edit from the tank) follows to LinkSpin let r = await admin(IAP, '/api/admin/member', { email: 'lead1@qa.test', sponsorRef: 'adopter' }, 'PATCH'); ok(!r.error, 'IAP admin sets lead1 -> @adopter', JSON.stringify(r)); ok(await waitFor(async () => (await facts(LS, 'lead1@qa.test')).sponsorEmail === 'adopter@qa.test'), 'LinkSpin follows: lead1 under adopter'); const l1 = await facts(LS, 'lead1@qa.test'); ok(l1 && l1.prov && l1.prov.by === 'admin' && l1.prov.origin === 'instantadpay', 'LinkSpin keeps the same record (by admin, origin instantadpay)', JSON.stringify(l1 && l1.prov)); // 2. a deliberate change on LinkSpin (both had @oldsponsor) follows to InstantAdPay, a clear back to the tank r = await admin(LS, '/api/admin/member', { email: 'lead2@qa.test', sponsorRef: '' }, 'PATCH'); ok(!r.error, 'LinkSpin admin clears lead2 to the tank', JSON.stringify(r)); ok(await waitFor(async () => (await facts(IAP, 'lead2@qa.test')).sponsorEmail === null), 'InstantAdPay follows the clear: lead2 in the tank'); // 3. bound on InstantAdPay: a LinkSpin change does not move it there; reported; resolve refuses on the bound side r = await admin(LS, '/api/admin/member', { email: 'lead3@qa.test', sponsorRef: 'adopter' }, 'PATCH'); await sleep(6000); ok((await facts(IAP, 'lead3@qa.test')).sponsorEmail === 'old@qa.test', 'bound on InstantAdPay: sponsor there unchanged'); // 3b. Who invited you (2026-11-07): the member, signed in on InstantAdPay, names their sponsor; LinkSpin follows through the real sync { const st = await fetch(IAP + '/api/auth/email/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'lead5@qa.test', fts: Date.now() - 8000 }) }).then(x => x.json()); const v = await fetch(IAP + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'lead5@qa.test', code: st.devCode }) }); const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; '); const inv = await fetch(IAP + '/api/my/tank/invited', { method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: cookie }, body: JSON.stringify({ who: '@qaboss' }) }).then(x => x.json()); ok(inv.ok && inv.name === '@qaboss', 'lead5 names @qaboss on InstantAdPay', JSON.stringify({ inv, dev: !!st.devCode })); ok(await waitFor(async () => (await facts(LS, 'lead5@qa.test')).sponsorEmail === 'boss@qa.test'), 'LinkSpin follows: lead5 under boss'); const f5 = await facts(LS, 'lead5@qa.test'); ok(f5 && f5.prov && f5.prov.by === 'invited' && f5.prov.origin === 'instantadpay', 'LinkSpin keeps the record (by invited, origin instantadpay)', JSON.stringify(f5 && f5.prov)); const a5 = await admin(IAP, '/api/admin/tank'); ok((a5.adoptions || []).some(x => x.adoptee === 'lead5@qa.test' && x.status === 'invited'), 'InstantAdPay admin tank shows the record'); } // 4. ping-pong: let both ticks run; nothing keeps bouncing const s1 = await admin(IAP, '/api/admin/lssync'), t1 = await admin(LS, '/api/admin/iapsync'); await admin(IAP, '/api/admin/lssync/run', {}); await admin(LS, '/api/admin/iapsync/run', {}); await sleep(1500); await admin(IAP, '/api/admin/lssync/run', {}); await admin(LS, '/api/admin/iapsync/run', {}); await sleep(1500); const s2 = await admin(IAP, '/api/admin/lssync/run', {}), t2 = await admin(LS, '/api/admin/iapsync/run', {}); ok(s2.sent === 0 && t2.sent === 0, 'no ping-pong: a third reconcile on each side sends 0 rows', JSON.stringify({ s1: s1.pushed, s2, t1: t1.pushed, t2 })); // 5. the Sponsor check on both apps lists lead3 (bound on IAP) and lead4 (ordinary, different) and nothing else const rep = await admin(IAP, '/api/admin/sponsor-check'); const rep2 = await admin(LS, '/api/admin/sponsor-check'); const emails = x => (x.rows || []).map(y => y.email).sort().join(','); ok(!rep.peerError && emails(rep) === 'lead3@qa.test,lead4@qa.test', 'IAP Sponsor check rows = lead3, lead4', JSON.stringify({ e: emails(rep), err: rep.peerError })); ok(emails(rep2) === emails(rep), 'LinkSpin Sponsor check shows the same rows'); const r3 = (rep.rows || []).find(x => x.email === 'lead3@qa.test'); ok(r3 && r3.iap.bound && !r3.ls.bound, 'lead3: bound on InstantAdPay, not on LinkSpin'); ok(r3 && (r3.iap.log || []).some(l => l.action === 'bound'), 'lead3: the refused follow is in the InstantAdPay log'); r = await admin(IAP, '/api/admin/sponsor-check/resolve', { email: 'lead3@qa.test', use: 'linkspin' }); ok(r.error && /bound/.test(r.error), "resolve 'Use LinkSpin's sponsor' on the bound side is refused", JSON.stringify(r)); r = await admin(LS, '/api/admin/sponsor-check/resolve', { email: 'lead3@qa.test', use: 'instantadpay' }); ok(r.ok, "resolve from LinkSpin admin: 'Use InstantAdPay's sponsor' applies on LinkSpin", JSON.stringify(r)); ok((await facts(LS, 'lead3@qa.test')).sponsorEmail === 'old@qa.test', 'lead3 now @oldsponsor on both'); r = await admin(IAP, '/api/admin/sponsor-check/resolve', { email: 'lead4@qa.test', use: 'instantadpay' }); ok(r.ok, "resolve from InstantAdPay admin: lead4 'Use InstantAdPay's sponsor' applied on LinkSpin through the partner call", JSON.stringify(r)); await sleep(5000); const rep3 = await admin(IAP, '/api/admin/sponsor-check'); ok((rep3.rows || []).length === 0, 'after both picks the Sponsor check is empty', emails(rep3)); ok((await facts(IAP, 'lead4@qa.test')).sponsorEmail === 'old@qa.test', 'lead4 on InstantAdPay untouched by its own pick'); // 6. an old peer (no proto 2): rows carrying the new facts are sent again later (checked through the stored hashes) const st = JSON.parse(fs.readFileSync(path.join(iapDir, 'sponsorfollow.json'), 'utf8')); ok(st.peer && st.peer.proto === 2, 'IAP saw LinkSpin answer proto 2'); } catch (e) { fail++; lines.push('FAIL exception ' + (e && e.stack || e)); } finally { for (const p of procs) { try { p.kill(); } catch (e) {} } if (process.platform === 'win32') for (const port of [IAP_PORT, LS_PORT]) { try { const o = execSync('netstat -ano | findstr :' + port, { encoding: 'utf8' }); for (const pid of new Set(o.split(/\r?\n/).map(l => l.trim().split(/\s+/).pop()).filter(x => /^\d+$/.test(x) && x !== '0'))) { try { execSync('taskkill /F /PID ' + pid, { stdio: 'ignore' }); } catch (e) {} } } catch (e) {} } await sleep(500); for (const d of [iapDir, lsDir]) { try { fs.rmSync(d, { recursive: true, force: true }); } catch (e) {} } } console.log(lines.join('\n')); console.log('\nsponsorfollow e2e: ' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);