Files
instantadpay/qa/tank-hold.mjs
martbost 59607d0c94 One-tap switch on payouts after a holding-tank assignment + reminders (Marty approved 2026-10-27)
- Assignment chat + member email (manual adoption and the 24h auto-assign) carry "Switch on payouts" -> https://instantadpay.com/my?activate=1#wallet
- /my?activate=1: signed in, wallet linked, real sponsor, no hold -> Wallet tab, explainer line, the Activate button's own flow (injected wallet or the WalletConnect picker on a phone). Survives sign-in and the wallet link (sessionStorage); never starts on tankHold, a blocked/routed sponsor or the #1 fallback (/api/me sponsorFallback)
- payTick (in the 15-min readyTick): not activated 24h after the assignment -> ONE member email + ONE in-app notice to the sponsor; 72h -> last member email; stops on memberId / MemberActivated / sponsor change. State tank-ready.json `pay`, each send gated by marks.claim (deploy overlap), record saved before the send; Admin tank view gets payReminders
- Chatbot: tank-activate-link canned answer + system prompt; my.js ?v=20261027pa
- qa/tank-hold.mjs: link texts, reminder schedule on a mocked clock, overlap copy, ?activate=1 browser flows (stubbed wallet)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 07:29:43 -05:00

369 lines
33 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; the one-tap /my?activate=1#wallet link (stubbed wallet) starts the Activate
// flow only with a wallet, a real sponsor and no hold, and carries on after an on-page sign-in. 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(o) {
o = o || {};
const tankPath = path.join(SITE, 'tank.js'); delete require.cache[require.resolve(tankPath)];
const tank = require(tankPath);
const dir = o.dir || fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-'));
const accounts = o.accounts || fakeAccounts(); const events = []; const chats = []; const mails = []; const alerts = []; const assigned = []; const net = {};
const notices = []; const claims = o.claims || new Set(); const onChain = o.onChain || new Set();
const blocked = new Set();
const env = o.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, body) => { mails.push({ to, subject, body }); } }, 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); },
claim: k => { if (claims.has(k)) return false; claims.add(k); return true; }, activated: a => onChain.has(a.address), notify: async (to, subject, text) => { notices.push({ to, subject, text }); } } });
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, notices, claims, onChain };
}
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');
const LINK = 'https://iap.test/my?activate=1#wallet';
ok(B.chats.some(c => c.to === 'free@x.co' && c.text.includes('Switch on payouts in one tap') && c.text.includes(LINK)), 'auto-assign chat carries the one-tap link');
ok(B.mails.some(m => m.to === 'free@x.co' && m.body.includes('Switch on payouts: ' + LINK) && m.body.includes('locks @a in as your sponsor')), 'auto-assign member email carries the one-tap link');
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")');
}
{ // one-tap link + switch-on-payouts reminders (24 h member + sponsor, 72 h member only), mocked clock
const B = bench(); const { tank, accounts, env } = B; const LINK = 'https://iap.test/my?activate=1#wallet';
B.buyer('sp@x.co', 41);
accounts.add('m1@x.co', { address: '0x' + '7'.repeat(40) }); accounts.add('m2@x.co'); accounts.add('m3@x.co', { address: '0x' + '8'.repeat(40) }); accounts.add('m4@x.co', { address: '0x' + '9'.repeat(40) });
const r = await tank.adopt('sp@x.co', 'm1', 'Hey, I am your new sponsor.');
ok(r && r.ok && !r.auto, 'manual adoption (setup)', JSON.stringify(r && r.error));
const chat = B.chats.find(c => c.to === 'm1@x.co');
ok(chat && chat.text === 'Hey, I am your new sponsor.\n\nSwitch on payouts in one tap (one free transaction, it locks me in as your sponsor): ' + LINK, 'manual adoption chat: own note + the one-tap line', chat && chat.text);
const mail = B.mails.find(m => m.to === 'm1@x.co');
ok(mail && mail.body.includes('Switch on payouts: ' + LINK) && !mail.body.includes('No wallet linked yet'), 'manual adoption email: link, no wallet sentence when linked');
await tank.adopt('sp@x.co', 'm2'); // no wallet yet
ok(B.mails.some(m => m.to === 'm2@x.co' && m.body.includes('No wallet linked yet? The same link shows you how')), 'no wallet: the email says the link walks them through linking');
const t0 = env.now;
env.now = t0 + 23 * H; let p = await tank.payTick();
ok(p.sent.length === 0, 'no reminder before 24 h');
accounts._by.get('m2@x.co').memberId = 51; // m2 switched on payouts: no reminder ever
env.now = t0 + 24 * H + 60000; const mailsBefore = B.mails.length;
p = await tank.payTick();
const r1 = B.mails.slice(mailsBefore);
ok(p.sent.length === 1 && p.sent[0].email === 'm1@x.co' && p.sent[0].stage === 1, '24 h: one reminder, only for the member still off', JSON.stringify(p.sent));
ok(r1.length === 1 && r1[0].to === 'm1@x.co' && r1[0].subject === 'Reminder: switch on payouts with @sp on InstantAdPay' && r1[0].body.includes(LINK), '24 h member email: subject + one-tap link', r1[0] && r1[0].subject);
ok(B.notices.length === 1 && B.notices[0].to === 'sp@x.co' && B.notices[0].subject === "@m1 hasn't switched on payouts yet" && B.notices[0].text.startsWith("@m1 hasn't switched on payouts yet; a nudge from you helps.") && B.notices[0].text.includes(LINK), '24 h sponsor notice', B.notices[0] && B.notices[0].text.slice(0, 80));
ok(!r1.some(m => m.to === 'sp@x.co'), 'the sponsor gets a notice, not an email');
await tank.payTick(); env.now += 15 * 60000; p = await tank.payTick();
ok(p.sent.length === 0 && B.notices.length === 1, 'idempotent: later ticks send nothing more before 72 h');
ok(tank.payView().find(x => x.email === 'm2@x.co').done === 'activated', 'activated member: record closed (activated)');
env.now = t0 + 72 * H + 60000; const m72 = B.mails.length;
p = await tank.payTick();
ok(p.sent.length === 1 && p.sent[0].stage === 2 && B.mails.length === m72 + 1 && B.mails[m72].subject === 'Last reminder: switch on payouts with @sp on InstantAdPay' && B.mails[m72].body.includes(LINK), '72 h: the last reminder, member only', JSON.stringify(p.sent));
ok(B.notices.length === 1, '72 h: no second sponsor notice');
env.now += 24 * H; p = await tank.payTick();
ok(p.sent.length === 0 && tank.payView().find(x => x.email === 'm1@x.co').done === 'reminded', 'after 72 h: done, nothing more');
ok(!/—/.test(B.chats.map(c => c.text).join(' ') + B.mails.map(m => m.subject + m.body).join(' ') + B.notices.map(n => n.subject + n.text).join(' ')), 'no em dashes in member texts');
// m3 activated on chain (MemberActivated) before the account has a memberId; m4 moved away before 24 h: both stop
B.buyer('sp2@x.co', 42);
const r3 = await tank.adopt('sp2@x.co', 'm3'); ok(r3 && r3.ok, 'second sponsor adopts m3 (setup)', JSON.stringify(r3 && r3.error));
const r4 = await tank.adopt('sp2@x.co', 'm4'); ok(r4 && r4.ok, 'second sponsor adopts m4 (setup)', JSON.stringify(r4 && r4.error));
const t3 = env.now; B.onChain.add(accounts._by.get('m3@x.co').address);
accounts._by.get('m4@x.co').sponsorRef = '';
env.now = t3 + 25 * H; p = await tank.payTick();
ok(p.sent.length === 0, 'activated on chain / sponsor changed: no reminder', JSON.stringify(p.sent));
const pv = tank.payView();
ok(pv.find(x => x.email === 'm3@x.co').done === 'activated' && pv.find(x => x.email === 'm4@x.co').done === 'moved', 'records closed as activated / moved');
ok((await tank.adminView()).payReminders.length >= 4, 'adminView lists the reminder records');
}
{ // deploy overlap: a second app copy with a stale tank-ready.json and the shared claim table sends nothing twice
const accounts = fakeAccounts(); const claims = new Set(); const env = { now: Date.now() };
const A = bench({ accounts, claims, env });
A.buyer('ov@x.co', 61); accounts.add('ovm@x.co', { address: '0x' + '6'.repeat(40) });
await A.tank.adopt('ov@x.co', 'ovm');
const stale = fs.readFileSync(path.join(A.dir, 'tank-ready.json'), 'utf8');
env.now += 25 * H;
const pa = await A.tank.payTick();
const dir2 = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-ov-')); fs.writeFileSync(path.join(dir2, 'tank-ready.json'), stale);
const Bc = bench({ accounts, claims, env, dir: dir2 }); // copy B: same accounts + claims, stale state
const pb = await Bc.tank.payTick();
ok(pa.sent.length === 1 && pb.sent.length === 0 && Bc.mails.length === 0 && Bc.notices.length === 0, 'overlap: copy A sends the 24 h reminder, stale copy B sends nothing', JSON.stringify({ a: pa.sent.length, b: pb.sent.length }));
}
{ // 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, ip) { // ip: X-Forwarded-For of its own (the code guard allows 5 sends per IP per 10 min)
const xf = ip ? { 'X-Forwarded-For': ip } : {};
const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000 }, Object.assign({}, xf, extraCookie ? { Cookie: extraCookie } : {}));
const v = await fetch(BASE + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, xf, 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));
// 5. one-tap link /my?activate=1#wallet (2026-10-27): IAPWallet.activate is stubbed in the page (records the sponsor id,
// never reaches a wallet); it must start only for a signed-in member with a wallet, a real sponsor and no hold
const STUB = () => { window.__act = []; let real; Object.defineProperty(window, 'IAPWallet', { configurable: true, get() { return real; },
set(v) { if (v && v.activate) v.activate = async id => { window.__act.push(id); throw new Error('qa: activation stub'); }; real = v; } });
try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} };
async function actCtx(cookie, ip) { // ip: its own address for the on-page sign-in (the code guard allows 5 sends per IP per 10 min)
const c = await browser.newContext(Object.assign({ viewport: { width: 390, height: 844 } }, ip ? { extraHTTPHeaders: { 'X-Forwarded-For': ip } } : {})); await c.addInitScript(STUB);
if (cookie) await c.addCookies(cookie.split('; ').filter(Boolean).map(x => { const i = x.indexOf('='); return { name: x.slice(0, i), value: x.slice(i + 1), url: BASE }; }));
const pg = await c.newPage(); pg.on('pageerror', e => errs.push(e.message)); return { c, pg };
}
const actState = pg => pg.evaluate(() => { const n = document.getElementById('actIntentNote'); return { act: window.__act, note: n && !n.hidden ? n.textContent : null, url: location.pathname + location.search + location.hash, hold: (document.getElementById('tankHoldNote') || {}).hidden === false }; });
{ // held tank member: never triggers, the param is dropped, the hold text shows
const { c, pg } = await actCtx(tc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
const s1 = await actState(pg);
ok(s1.act.length === 0 && !s1.note && s1.hold && !/activate=1/.test(s1.url), '?activate=1 on a held tank member: no activation, hold text, param dropped', JSON.stringify(s1));
await c.close();
}
{ // sponsor link to a member who never switched on payouts (walk-up / routed): no real sponsor, never triggers
ok(me2 && me2.sponsorRouted, 'setup: the link-joined member routes past an unactivated sponsor', JSON.stringify(me2 && me2.sponsorRouted));
const { c, pg } = await actCtx(jc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
const s2 = await actState(pg);
ok(s2.act.length === 0 && !s2.note, '?activate=1 when no real sponsor resolves: no activation', JSON.stringify(s2));
await c.close();
}
// a member with a real sponsor (#21) and a wallet: the Activate flow starts at once with #21
const pc = await signIn('qa-pay@example.com', 'qapayone', 'iap.sponsor=21', '10.78.0.1'); await linkWallet(pc);
const mp = (await api('/api/me', null, { Cookie: pc })).j;
ok(mp && mp.sponsorId === 21 && !mp.sponsorFallback && !mp.tankHold && !mp.memberId, 'setup: sponsored member, sponsor #21 resolves', JSON.stringify({ id: mp && mp.sponsorId, f: mp && mp.sponsorFallback }));
{ const { c, pg } = await actCtx(pc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4500);
const s3 = await actState(pg);
ok(s3.act.length === 1 && s3.act[0] === 21, '?activate=1: the Activate flow starts once with the sponsor prefilled (#21)', JSON.stringify(s3));
ok(s3.note === 'One free transaction switches on your payouts and locks member #21 in as your sponsor. Confirm it in your wallet.', 'explainer line above the Activate button', s3.note);
ok(/#wallet$/.test(s3.url) && !/activate=1/.test(s3.url), 'Wallet tab open, param consumed', s3.url);
await pg.reload({ waitUntil: 'load' }); await pg.waitForTimeout(3500);
ok((await actState(pg)).act.length === 0, 'a reload does not start it again');
await pg.screenshot({ path: path.join(SITE, 'qa/out/tank-activate-link.png') }).catch(() => {});
await c.close(); }
{ // signed out: sign in on the page, then the same flow carries on
const c2 = await signIn('qa-pay2@example.com', 'qapaytwo', 'iap.sponsor=21', '10.78.0.2'); await linkWallet(c2);
const { c, pg } = await actCtx(null, '10.77.' + (1 + Math.floor(Math.random() * 250)) + '.9'); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
ok((await actState(pg)).act.length === 0, 'signed out: nothing starts before sign-in');
await pg.fill('#mcEmail', 'qa-pay2@example.com'); await pg.click('#mcSendBtn');
await pg.waitForFunction(() => (document.getElementById('mcCode') || {}).value, null, { timeout: 15000 }).catch(() => {});
await pg.click('#mcVerifyBtn'); await pg.waitForTimeout(5000);
const s4 = await actState(pg);
ok(s4.act.length === 1 && s4.act[0] === 21, 'signed out -> sign in -> the Activate flow continues with #21', JSON.stringify(s4));
await c.close(); }
{ // sponsored, no wallet yet: link first (note), nothing starts; the intent waits for the link
const c3 = await signIn('qa-pay3@example.com', 'qapaythree', 'iap.sponsor=21', '10.78.0.3');
const { c, pg } = await actCtx(c3); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
const s5 = await actState(pg);
ok(s5.act.length === 0 && s5.note === 'Step 1: link your wallet (one free signature). Then switching on payouts with member #21 starts by itself.', 'no wallet yet: asks to link first, nothing starts', JSON.stringify(s5));
await c.close(); }
ok(!errs.length, 'no page errors (one-tap link pages)', 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);