Files
instantadpay/qa/tank-hold.mjs
T

249 lines
20 KiB
JavaScript

// Holding-tank activation hold + 24-hour safety net + network alignment (2026-10-27).
// node qa/tank-hold.mjs (or: bash qa/run.sh tankhold; also part of `bash qa/run.sh member`)
// Part A, no server: tank.js with in-memory accounts, a fake chain and a MOCKED CLOCK (tank.setClock):
// ready clock starts at first sight of a linked wallet, the hold, alignment to a LinkSpin sponsor (and the refusals:
// released-from sponsor, unclaimed shell, loop), the safety net at 24 h (rotation order, cap, 7-day sign-in, company
// excluded, no-payout chain skipped, own-downline skipped), nobody eligible = keep holding + one admin alert.
// Part B, LOCAL copy (throwaway DATA_DIR, JSON store, devCode sign-in, LS_URL pointed at a dead local port so nothing
// reaches LinkSpin): a tank account links a wallet -> /api/me + /api/sponsor answer tankHold with no fallback sponsor,
// the Wallet tab hides Activate payouts and shows the hold text, the Getting started card has no activate button,
// Admin tank shows the ready badge; a member who joined through a link is never held; a LinkSpin row naming a sponsor
// aligns a tank member instead of holding them. Never production. Exit code 1 on any failure.
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 { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const require = createRequire(path.join(SITE, 'package.json'));
delete process.env.DATABASE_URL; // JSON stores only
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const H = 3600000;
// ---------------- Part A ----------------
function fakeAccounts() {
const by = new Map(); let nextId = 100;
const pub = a => a ? Object.assign({}, a) : null;
const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
return {
_by: by,
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - H, joinedVia: null }, o || {}); by.set(email, a); return pub(a); },
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true }; },
async listAll() { return [...by.values()].filter(a => !(a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId)).map(pub); },
isUnclaimedShell: a => !!a && a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId,
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); }
};
}
function bench() {
const tankPath = path.join(SITE, 'tank.js'); delete require.cache[require.resolve(tankPath)];
const tank = require(tankPath);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-'));
const accounts = fakeAccounts(); const events = []; const chats = []; const mails = []; const alerts = []; const assigned = []; const net = {};
const blocked = new Set();
const env = { now: Date.now() };
tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) },
messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 },
mailer: { hasKey: () => true, send: async (to, subject) => { mails.push({ to, subject }); } }, site: 'https://iap.test',
hooks: { network: e => net[e] || null, isSuspended: () => false, excluded: () => false, payoutBlocked: async id => blocked.has(id), companyId: () => 1,
assigned: r => { assigned.push(r); }, adminAlert: t => { alerts.push(t); } } });
tank.setClock(() => env.now);
let block = 1000;
const buyer = (email, memberId, o) => { const a = accounts.add(email, Object.assign({ memberId, address: '0x' + crypto.randomBytes(20).toString('hex'), lastSeen: env.now - H }, o || {})); events.push({ type: 'Purchase', buyerId: memberId, priceCents: 2000, block: block++ }); return a; };
return { tank, accounts, events, chats, mails, alerts, assigned, net, blocked, env, buyer, dir };
}
async function partA() {
console.log('-- Part A: tank.js with a mocked clock');
{ // hold + ready clock + safety net rotation
const B = bench(); const { tank, accounts, env } = B;
const t0 = env.now;
accounts.add('free@x.co'); // in the tank, no wallet
const h0 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h0 && h0.hold && h0.hold.since === null, 'tank member without a wallet: held, no clock yet');
accounts._by.get('free@x.co').address = '0x' + 'a'.repeat(40);
const h1 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h1 && h1.hold && h1.hold.since === t0 && h1.hold.until === t0 + 24 * H, 'wallet linked: clock starts now, until = +24 h');
env.now = t0 + 5 * H;
const h2 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h2.hold.since === t0, 'the clock does not restart on later visits');
const sponsored = accounts.add('kid@x.co', { sponsorRef: 'someone', address: '0x' + 'b'.repeat(40) });
ok((await tank.holdFor(sponsored)) === null, 'a member with a sponsor is never held');
const w = await tank.waiting();
ok(w[0] && w[0].email === 'free@x.co' && w[0].ready && w[0].holdUntil === t0 + 24 * H, 'waiting(): ready member first with holdUntil');
// adopters: A qualified first, B second, C third; D stale (8 days), E company #1, F blocked chain, G full (2 open)
B.buyer('a@x.co', 11); B.buyer('b@x.co', 12); B.buyer('c@x.co', 13);
B.buyer('d@x.co', 14, { lastSeen: env.now - 8 * 86400000 }); B.buyer('e@x.co', 1); B.buyer('f@x.co', 16); B.blocked.add(16);
const tk = await tank.readyTick(); // 5 h in: nothing due
ok(tk.fresh.length === 1 && tk.fresh[0].email === 'free@x.co', 'readyTick announces the ready member once', JSON.stringify(tk.fresh.map(x => x.email)));
ok((await tank.readyTick()).fresh.length === 0, '...and not twice');
ok(tk.assigned.length === 0, 'not assigned before 24 h');
env.now = t0 + 24 * H - 10 * 60000; // 23 h 50 min: inside the last tick, so the hold never runs past 24 h
const r1 = await tank.readyTick();
ok(r1.assigned.length === 1 && r1.assigned[0].adopter === 'a@x.co', 'safety net: first in rotation = earliest qualified (A)', JSON.stringify(r1.assigned));
const fa = await accounts.byEmail('free@x.co');
ok(fa.sponsorRef === 'a', 'adoptee now sponsored by A', fa.sponsorRef);
ok((await tank.holdFor(fa)) === null, 'hold lifted once sponsored');
const recs = (await tank.adminView()).adoptions;
ok(recs[0] && recs[0].note === 'auto-assigned after 24 hours in the tank' && recs[0].status === 'open', 'adoption record note', recs[0] && recs[0].note);
ok(B.chats.some(c => c.from === 'a@x.co' && c.to === 'free@x.co'), 'sponsor chat opened');
ok(B.mails.some(m => m.to === 'free@x.co') && B.mails.some(m => m.to === 'a@x.co' && /holding tank is now in your line/.test(m.subject)), 'both sides emailed');
ok(B.assigned.length === 1, 'assigned hook fired (Telegram pickup line with "(auto-assigned)")');
// second ready member: rotation moves to B (A was just auto-assigned)
accounts.add('free2@x.co', { address: '0x' + 'c'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
const r2 = await tank.readyTick();
ok(r2.assigned.length === 1 && r2.assigned[0].adopter === 'b@x.co', 'rotation: least recently auto-assigned next (B)', JSON.stringify(r2.assigned));
// third: C; D stale, E company, F blocked chain never picked
accounts.add('free3@x.co', { address: '0x' + 'd'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
const r3 = await tank.readyTick();
ok(r3.assigned.length === 1 && r3.assigned[0].adopter === 'c@x.co', 'rotation: C (stale, company and no-payout chain skipped)', JSON.stringify(r3.assigned));
// fourth: everyone in rotation has been used once: back to A (oldest auto-assign)
accounts.add('free4@x.co', { address: '0x' + 'e'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
for (const em of ['a@x.co', 'b@x.co', 'c@x.co']) accounts._by.get(em).lastSeen = env.now - H;
const r4 = await tank.readyTick();
ok(r4.assigned.length === 1 && r4.assigned[0].adopter === 'a@x.co', 'rotation wraps to the least recently assigned (A)', JSON.stringify(r4.assigned));
// A now has 2 open adoptions (free + free4): full. Make B and C stale: nobody eligible
accounts._by.get('b@x.co').lastSeen = env.now - 8 * 86400000; accounts._by.get('c@x.co').lastSeen = env.now - 8 * 86400000;
accounts.add('free5@x.co', { address: '0x' + 'f'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
const r5 = await tank.readyTick();
const f5 = await accounts.byEmail('free5@x.co');
ok(r5.assigned.length === 0 && r5.held === 1 && !f5.sponsorRef, 'nobody eligible: keeps holding, never the company');
ok(B.alerts.length === 1 && /free5@x.co/.test(B.alerts[0]), 'admin alerted once');
await tank.readyTick(); await tank.sweep();
ok(B.alerts.length === 1, 'no second alert on later ticks / the hourly sweep');
const h5 = await tank.holdFor(f5);
ok(h5 && h5.hold && h5.hold.until <= env.now, 'still held past the clock (client shows "Any minute now")');
}
{ // own-downline adopter skipped
const B = bench(); const { tank, accounts, env } = B;
accounts.add('top@x.co', { address: '0x' + '1'.repeat(40) });
B.buyer('under@x.co', 21, { sponsorRef: 'top' }); B.buyer('other@x.co', 22);
await tank.readyTick(); env.now += 24 * H;
const r = await tank.readyTick();
ok(r.assigned.length === 1 && r.assigned[0].adopter === 'other@x.co', 'an adopter in the member\'s own downline is skipped', JSON.stringify(r.assigned));
}
{ // network alignment
const B = bench(); const { tank, accounts, net } = B;
accounts.add('lsboss@x.co', { memberId: 31 });
accounts.add('t1@x.co', { address: '0x' + '2'.repeat(40) }); net['t1@x.co'] = { sponsorEmail: 'lsboss@x.co', via: 'same email' };
const h = await tank.holdFor(await accounts.byEmail('t1@x.co'));
ok(h && h.aligned && (await accounts.byEmail('t1@x.co')).sponsorRef === 'lsboss', 'LinkSpin sponsor with an account here: aligned, not held', JSON.stringify(h));
ok((await tank.adminView()).aligned[0].why.includes('aligned to network sponsor @lsboss from LinkSpin'), 'alignment recorded with the reason');
accounts.add('shell@x.co', { joinedVia: 'linkspin', lastSeen: 0 });
accounts.add('t2@x.co'); net['t2@x.co'] = { sponsorEmail: 'shell@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t2@x.co'))).hold, 'sponsor only an unclaimed LinkSpin shell here: held, not aligned');
accounts.add('t3@x.co'); net['t3@x.co'] = { sponsorEmail: 'nobody@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t3@x.co'))).hold, 'sponsor with no account here: held');
// released from lsboss on purpose: never back to them
accounts.add('t4@x.co', { sponsorRef: 'lsboss' });
const rel = await tank.release('lsboss@x.co', 't4@x.co');
ok(rel && rel.ok, 'release to the tank (setup)', JSON.stringify(rel));
net['t4@x.co'] = { sponsorEmail: 'lsboss@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t4@x.co'))).hold, 'never aligned back to a sponsor who released them');
// loop: the LinkSpin sponsor sits under the tank member
accounts.add('t5@x.co'); accounts.add('child@x.co', { sponsorRef: 't5', memberId: 33 }); net['t5@x.co'] = { sponsorEmail: 'child@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t5@x.co'))).hold, 'never aligned under their own downline');
}
}
// ---------------- Part B ----------------
async function partB() {
console.log('-- Part B: local copy');
const PORT = Number(process.env.TANKHOLD_PORT || 8799);
const BASE = 'http://127.0.0.1:' + PORT; const ADMIN = 'localtest';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-srv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const LSSECRET = crypto.randomBytes(24).toString('hex'); // throwaway
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, LS_SYNC_SECRET: LSSECRET, LS_URL: 'http://127.0.0.1:1' }) });
let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
let browser = null;
try {
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(BASE + '/api/config')).ok; } catch (e) { await sleep(500); } }
if (!up) throw new Error('local server did not come up:\n' + log.slice(-1500));
const api = async (p, body, hdr) => { const r = await fetch(BASE + p, body ? { method: body.method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: JSON.stringify(body.data || body) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
const adminH = { Authorization: 'Bearer ' + ADMIN };
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 20 } }, adminH);
async function signIn(email, username, extraCookie) {
const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000 }, extraCookie ? { Cookie: extraCookie } : null);
const v = await fetch(BASE + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extraCookie ? { Cookie: extraCookie } : {}), body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).filter(c => /^iap\./.test(c) || c.includes('=')).join('; ');
if (username) await api('/api/my/profile', { username }, { Cookie: cookie });
return cookie;
}
const { ethers } = require('ethers');
async function linkWallet(cookie) {
const w = ethers.Wallet.createRandom();
const c = await api('/api/auth/challenge', { address: w.address }, { Cookie: cookie });
const signature = await w.signMessage(c.j.message);
const v = await api('/api/auth/verify', { address: w.address, signature }, { Cookie: cookie });
return { w, v };
}
// 1. tank member with a wallet
const tc = await signIn('qa-tank@example.com', 'qatankone');
const lw = await linkWallet(tc);
ok(lw.v.j && lw.v.j.linked, 'tank member links a wallet', JSON.stringify(lw.v.j));
const me = (await api('/api/me', null, { Cookie: tc })).j;
ok(me && me.tankHold && me.tankHold.until - me.tankHold.since === 24 * H, '/api/me answers tankHold with a 24-hour clock', JSON.stringify(me && me.tankHold));
ok(me && !me.sponsorId && me.sponsorBlocked === 'tankHold', '/api/me: no fallback sponsor (sponsorId ' + (me && me.sponsorId) + ')');
const sp = (await api('/api/sponsor?intent=buy', null, { Cookie: tc })).j;
ok(sp && sp.sponsorId === 1 && !sp.sponsorBlocked && !sp.tankHold, '/api/sponsor (buy) is NEVER held: falls back to the catch position #1 (Marty 2026-10-27)', JSON.stringify({ id: sp && sp.sponsorId, b: sp && sp.sponsorBlocked }));
const spa = (await api('/api/sponsor', null, { Cookie: tc })).j;
ok(spa && !spa.sponsorId && spa.sponsorBlocked === 'tankHold', '/api/sponsor without buy intent still holds (activation only)', JSON.stringify({ id: spa && spa.sponsorId, b: spa && spa.sponsorBlocked }));
const adm = (await api('/api/admin/tank', null, adminH)).j;
const row = adm && adm.waiting && adm.waiting.find(w => w.email === 'qa-tank@example.com');
ok(row && row.ready && row.holdUntil === me.tankHold.until, 'admin tank: ready with holdUntil');
// 2. joined through a link: never held, today's behaviour
const jc = await signIn('qa-kid@example.com', 'qakidone', 'iap.sponsor=qatankone');
await linkWallet(jc);
const me2 = (await api('/api/me', null, { Cookie: jc })).j;
ok(me2 && !me2.tankHold && me2.sponsorBlocked !== 'tankHold' && me2.sponsorId > 0, 'member with a sponsor link: no hold, sponsor resolves as before', JSON.stringify({ id: me2 && me2.sponsorId, b: me2 && me2.sponsorBlocked, routed: me2 && me2.sponsorRouted }));
// 3. LinkSpin knows a sponsor for this email: aligned instead of held
await signIn('qa-lsboss@example.com', 'qalsboss');
const tc3 = await signIn('qa-tank3@example.com', 'qatankthree');
const raw = JSON.stringify({ rows: [{ email: 'qa-tank3@example.com', username: 'qatankthree', sponsorEmail: 'qa-lsboss@example.com', joinedAt: Date.now() - 86400000 }] });
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', LSSECRET).update(ts + '\n' + raw).digest('hex');
const pr = await fetch(BASE + '/api/partner/registry', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw });
ok(pr.ok, 'LinkSpin row accepted (first-platform rule leaves the sponsor empty)');
const me3 = (await api('/api/me', null, { Cookie: tc3 })).j;
ok(me3 && !me3.tankHold && me3.sponsorBlocked !== 'tankHold', 'tank member LinkSpin knows: aligned, not held', JSON.stringify({ b: me3 && me3.sponsorBlocked, h: me3 && me3.tankHold }));
const adm3 = (await api('/api/admin/tank', null, adminH)).j;
ok(adm3 && adm3.aligned && adm3.aligned.some(x => x.email === 'qa-tank3@example.com' && x.to === 'qa-lsboss@example.com'), 'admin tank lists the alignment');
// 4. the page: Wallet tab + Getting started card
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
browser = await chromium.launch();
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); localStorage.removeItem('iap.gs.collapsed'); } catch (e) {} });
await ctx.addCookies(tc.split('; ').filter(Boolean).map(c => { const i = c.indexOf('='); return { name: c.slice(0, i), value: c.slice(i + 1), url: BASE }; }));
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
await page.goto(BASE + '/my#wallet', { waitUntil: 'load' }); await page.waitForTimeout(4000);
const st = await page.evaluate(() => { const b = document.getElementById('activateBtn'); const n = document.getElementById('tankHoldNote'); const g = document.getElementById('gsNow');
return { card: !document.getElementById('activateCard').hidden, btnHidden: !!(b && b.hidden), note: n && !n.hidden ? n.textContent : null, gs: g ? g.textContent : '', gsBtn: !!document.getElementById('gsGo') }; });
ok(st.card && st.btnHidden, 'Wallet tab: Activate payouts button hidden', JSON.stringify(st));
ok(st.note && st.note.startsWith("You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).") && /Time left: \d+ h \d+ min\./.test(st.note), 'hold text with time left', st.note);
ok(/Matching you with a sponsor/.test(st.gs) && !st.gsBtn, 'Getting started: hold text, no activate button', st.gs.slice(0, 120));
await page.screenshot({ path: path.join(SITE, 'qa/out/tank-hold-wallet.png') }).catch(() => {});
ok(!errs.length, 'no page errors', errs.join(' | ').slice(0, 200));
} finally {
if (browser) await browser.close().catch(() => {});
try { srv.kill(); } catch (e) {}
await sleep(500);
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
}
}
await partA();
if (process.argv[2] !== 'unit') await partB();
console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed');
process.exit(fails ? 1 : 0);