3920e53db2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
507 lines
57 KiB
JavaScript
507 lines
57 KiB
JavaScript
// ViralAdBlitz local smoke test. Boots the app in prototype mode (no DOCSTORE_URL: files in a throwaway data dir under qa/out)
|
|
// against local stand-ins, then checks: copy rules, pages, the promo kit, sign-in (wallet + network), the one free text ad, member
|
|
// pages built from the hub line (first 5 with an ad, by place), verified visits / views / clicks, the weekly board, Boost orders
|
|
// (line voucher signed by the keeper, already-bound line, hub down), Boost recording from the chain (ledger split, passed over,
|
|
// Telegram card once, hub report), Boost delivery (views counted, starred while active, finished), Network Ad Space finishing,
|
|
// old-link redirects, admin, a restart, and Playwright renders on desktop + phone.
|
|
// Nothing leaves this machine: hub, InstantAdPay lookup, chain RPC, Telegram and NAS are local stand-ins. No real wallet, no money.
|
|
// node qa/smoke.mjs (Playwright renders too, if installed at PLAYWRIGHT)
|
|
// SKIP_UI=1 node qa/smoke.mjs (HTTP checks only)
|
|
import { spawn } from 'node:child_process';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import crypto from 'node:crypto';
|
|
import http from 'node:http';
|
|
import { createRequire } from 'node:module';
|
|
import { fileURLToPath } from 'node:url';
|
|
const require = createRequire(import.meta.url);
|
|
const { ethers } = require('ethers');
|
|
|
|
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
|
|
const DATA = path.join(OUT, 'data-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
|
|
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
|
const PORT = Number(process.env.SMOKE_APP_PORT || 3317), BASE = 'http://127.0.0.1:' + PORT;
|
|
const ADMIN = 'smoke-admin-token', SSO_SECRET = crypto.randomBytes(32).toString('hex'), HUB_SECRET = 'h'.repeat(40);
|
|
const KEEPER_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d'; // anvil's public test key #1
|
|
const KEEPER = new ethers.Wallet(KEEPER_PK).address;
|
|
const SHOP = '0x00000000000000000000000000000000000Ab0B5';
|
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
let pass = 0, fail = 0; let srv = null;
|
|
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra, (k, v) => typeof v === 'bigint' ? v.toString() : v).slice(0, 500) : '')); } };
|
|
const listen = (port, fn) => http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; try { await fn(q, r, b); } catch (e) { r.statusCode = 500; r.end(String(e.message)); } }).listen(port, '127.0.0.1').unref();
|
|
|
|
// ---- stand-in network hub: people = wallet|id -> { id, username, wallet|null, sponsorId, blocked }. Signed as viraladblitz. ----
|
|
const HUB = { people: new Map(), down: false, badSig: 0, resolves: 0, got: [] };
|
|
function person(username, wallet, sponsorId) { const id = 'h_' + crypto.createHash('sha1').update(username).digest('hex').slice(0, 16); HUB.people.set(id, { id, username, wallet: wallet ? wallet.toLowerCase() : null, sponsorId: sponsorId || null }); return id; }
|
|
const hubView = p => { if (!p) return null; const sp = p.sponsorId && HUB.people.get(p.sponsorId); return { id: p.id, username: p.username, wallet: p.wallet, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null }; };
|
|
const HUB_PORT = PORT + 1;
|
|
listen(HUB_PORT, async (q, r, b) => {
|
|
r.setHeader('Content-Type', 'application/json');
|
|
if (HUB.down) { r.statusCode = 503; return r.end('{"error":"down"}'); }
|
|
const want = crypto.createHmac('sha256', HUB_SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
|
|
if (q.headers['x-hub-sig'] !== want || q.headers['x-hub-site'] !== 'viraladblitz') { HUB.badSig++; r.statusCode = 401; return r.end('{}'); }
|
|
const j = JSON.parse(b || '{}');
|
|
if (q.url === '/v1/resolve') {
|
|
HUB.resolves++; const all = [...HUB.people.values()]; let p = null;
|
|
if (j.id) p = HUB.people.get(j.id); else if (j.wallet) p = all.find(x => x.wallet === String(j.wallet).toLowerCase());
|
|
else if (j.ref) { const ref = String(j.ref).toLowerCase(); p = all.find(x => x.wallet === ref || x.username.toLowerCase() === ref); }
|
|
else if (j.email) p = all.find(x => x.email === j.email);
|
|
return r.end(JSON.stringify({ person: hubView(p) }));
|
|
}
|
|
HUB.got.push({ route: q.url, body: j }); r.end('{"ok":true}');
|
|
});
|
|
// ---- stand-in InstantAdPay member lookup (only used while the hub is down) ----
|
|
const IAP_KNOWS = new Set(); const LOOKUP_PORT = PORT + 2;
|
|
listen(LOOKUP_PORT, async (q, r) => { const a = (new URL(q.url, 'http://x').searchParams.get('a') || '').toLowerCase(); r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify(IAP_KNOWS.has(a) ? { address: a, username: 'iap' + a.slice(2, 8) } : {})); });
|
|
// ---- stand-in Polygon JSON-RPC: quoteWei at POL $0.25 (1 cent = 0.04 POL), sponsorOf from BOUND, contract facts, logs + receipts ----
|
|
const IFACE = new ethers.Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 views, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, uint256 companyPaid)',
|
|
'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)', 'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)',
|
|
'event SponsorBound(address indexed member, address indexed sponsor)',
|
|
'function quoteWei(uint256 sku, uint256 qty) view returns (uint256)', 'function sponsorOf(address) view returns (address)',
|
|
'function buy(uint256 sku, uint256 qty, uint256 ref, address[] line, uint256 deadline, bytes sig) payable returns (uint256)',
|
|
'function owner() view returns (address)', 'function company() view returns (address)', 'function keeper() view returns (address)', 'function paused() view returns (bool)', 'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)']);
|
|
const CHAIN = { head: 1, logs: [], receipts: {}, bound: new Map(), replayAll: false, down: false, times: {} };
|
|
const TANGEM = '0x7627Fc78876948AC9d95C1C9eB061E7D6d647b70';
|
|
const CHAIN_PORT = PORT + 3;
|
|
listen(CHAIN_PORT, async (q, r, b) => {
|
|
const j = JSON.parse(b || '{}'); let result = null; r.setHeader('Content-Type', 'application/json');
|
|
if (CHAIN.down) return r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, error: { code: -1, message: 'down' } }));
|
|
if (j.method === 'eth_blockNumber') result = '0x' + CHAIN.head.toString(16);
|
|
if (j.method === 'eth_call') {
|
|
const d = j.params[0].data; const tx = IFACE.parseTransaction({ data: d });
|
|
const enc = (fn, v) => IFACE.encodeFunctionResult(fn, v);
|
|
if (tx.name === 'quoteWei') result = enc('quoteWei', [500n * tx.args[1] * 4n * 10n ** 16n]);
|
|
if (tx.name === 'sponsorOf') result = enc('sponsorOf', [CHAIN.bound.get(tx.args[0].toLowerCase()) || ethers.ZeroAddress]);
|
|
if (tx.name === 'owner' || tx.name === 'company') result = enc(tx.name, [TANGEM]);
|
|
if (tx.name === 'keeper') result = enc('keeper', [KEEPER]);
|
|
if (tx.name === 'paused') result = enc('paused', [false]);
|
|
if (tx.name === 'totalOwed') result = enc('totalOwed', [0n]);
|
|
if (tx.name === 'orderCount') result = enc('orderCount', [BigInt(CHAIN.logs.length)]);
|
|
}
|
|
if (j.method === 'eth_getBalance') result = '0x0';
|
|
if (j.method === 'eth_getTransactionReceipt') result = CHAIN.receipts[j.params[0]] || null;
|
|
if (j.method === 'eth_maxPriorityFeePerGas') result = '0x' + (40n * 10n ** 9n).toString(16);
|
|
if (j.method === 'eth_getBlockByNumber') { const n = j.params[0] === 'latest' ? CHAIN.head : parseInt(j.params[0], 16); result = { number: '0x' + n.toString(16), timestamp: '0x' + (CHAIN.times[n] || Math.floor(Date.now() / 1000)).toString(16), baseFeePerGas: '0x' + (30n * 10n ** 9n).toString(16) }; }
|
|
if (j.method === 'eth_getLogs') { const f = j.params[0], lo = parseInt(f.fromBlock, 16), hi = parseInt(f.toBlock, 16); result = CHAIN.logs.filter(l => CHAIN.replayAll || (parseInt(l.blockNumber, 16) >= lo && parseInt(l.blockNumber, 16) <= hi)); }
|
|
r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, result }));
|
|
});
|
|
// a Boost on the stand-in chain: Purchase log + a receipt with SponsorBound / PassedOver / Paid logs, like VABShop emits
|
|
let orderId = 0;
|
|
function chainBoost(o) {
|
|
const id = ++orderId; const block = ++CHAIN.head; const tx = '0x' + crypto.randomBytes(32).toString('hex');
|
|
if (o.blockAt) CHAIN.times[block] = o.blockAt;
|
|
const weiPaid = 500n * BigInt(o.qty || 1) * 4n * 10n ** 16n; const share = weiPaid / 10n;
|
|
const mk = (name, args, li) => { const e = IFACE.encodeEventLog(name, args); return { address: SHOP.toLowerCase(), topics: e.topics, data: e.data, blockNumber: '0x' + block.toString(16), transactionHash: tx, logIndex: '0x' + li.toString(16), removed: false }; };
|
|
const logs = []; let li = 0;
|
|
for (const [m, s] of o.bound || []) { logs.push(mk('SponsorBound', [m, s], li++)); CHAIN.bound.set(m.toLowerCase(), s.toLowerCase()); }
|
|
for (const [w, d] of o.over || []) logs.push(mk('PassedOver', [id, w, d], li++));
|
|
(o.pays || []).forEach(([w, d], i) => logs.push(mk('Paid', [id, w, share, i + 1, d], li++)));
|
|
const company = weiPaid - share * BigInt((o.pays || []).length);
|
|
logs.push(mk('Paid', [id, TANGEM, company, 0, 0], li++));
|
|
const purchase = mk('Purchase', [id, o.buyer, 1, o.qty || 1, o.ref || 0, o.views || 500, 500 * (o.qty || 1), weiPaid, (o.pays || []).length, company], li++);
|
|
logs.push(purchase); CHAIN.logs.push(purchase);
|
|
CHAIN.receipts[tx] = { status: '0x1', blockNumber: '0x' + block.toString(16), to: SHOP.toLowerCase(), from: o.buyer.toLowerCase(), logs };
|
|
return { tx, id, weiPaid, share, company };
|
|
}
|
|
// ---- stand-in Telegram Bot API ----
|
|
const TG = []; const TG_PORT = PORT + 4;
|
|
listen(TG_PORT, async (q, r, b) => { TG.push({ method: q.url.split('/').pop(), token: q.url.split('/')[1], body: JSON.parse(b || '{}') }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); });
|
|
|
|
// ---- stand-in LinkSpin partner endpoint /api/partner/vab/links (net.v1 signature). Starts DOWN (404, as before LinkSpin ships it). ----
|
|
const LS = { up: false, calls: [], badSig: 0, links: new Map(), known: new Set(['one', 'owner', 'four', 'five', 'six', 'seven', 'topdog', 'downline']), stats: {} }; const LS_PORT = PORT + 5;
|
|
listen(LS_PORT, async (q, r, b) => {
|
|
r.setHeader('Content-Type', 'application/json');
|
|
if (!LS.up || q.url !== '/api/partner/vab/links') { r.statusCode = 404; return r.end('{"error":"Not found"}'); }
|
|
const want = crypto.createHmac('sha256', SSO_SECRET).update('net.v1.' + q.headers['x-net-ts'] + '\n' + b).digest('hex');
|
|
if (q.headers['x-net-sig'] !== want) { LS.badSig++; r.statusCode = 401; return r.end('{"error":"unauthorized"}'); }
|
|
const j = JSON.parse(b || '{}'); LS.calls.push(j);
|
|
if (!LS.known.has(String(j.username || '').toLowerCase())) return r.end('{"account":false}');
|
|
if (j.op === 'stats') return r.end(JSON.stringify({ account: true, stats: LS.stats[j.username] || {} }));
|
|
const links = {};
|
|
for (const x of j.links || []) { const k = j.username + ':' + x.id; let l = LS.links.get(k); if (!l) { l = { code: crypto.randomBytes(3).toString('hex'), url: x.url }; LS.links.set(k, l); } l.url = x.url; links[x.id] = { code: l.code, link: 'https://spin.test/r/' + l.code + '?s1=' + x.id + '&placement=' + x.id, created: false }; }
|
|
r.end(JSON.stringify({ account: true, username: j.username, host: 'spin.test', links, errors: {} }));
|
|
});
|
|
|
|
const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '',
|
|
VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '2', LINK_PROBE: '0', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + LOOKUP_PORT + '/api/network/member',
|
|
NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid', NETWORK_SITES_HUB: '0',
|
|
CONTRACT_ADDRESS: SHOP, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200', EXPLORER: 'https://explorer.invalid',
|
|
HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'viraladblitz', HUB_TICK_MS: '300', HUB_DOWN_MS: '300', HUB_CACHE_MS: '200',
|
|
LS_TRACK_URL: 'http://127.0.0.1:' + LS_PORT, LS_SWEEP_FIRST_MS: '300', LS_SWEEP_MS: '300', LS_RETRY_MS: '300', LS_CACHE_MS: '100',
|
|
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT });
|
|
process.on('exit', () => { try { srv && srv.kill(); } catch (e) {} });
|
|
|
|
let nextIp = 10;
|
|
function client(opts = {}) {
|
|
const jar = {}; const ip = opts.ip || ('203.0.113.' + (nextIp++)); const ua = opts.ua || ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) SmokeBrowser/' + ip);
|
|
return { jar, ip, ua,
|
|
async req(p, o = {}) {
|
|
const headers = Object.assign({ 'User-Agent': ua, 'X-Forwarded-For': ip, Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, o.headers || {});
|
|
const r = await fetch(BASE + p, { method: o.method || 'GET', headers, body: o.body, redirect: 'manual' });
|
|
for (const c of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv] = c.split(';'); const i = kv.indexOf('='); jar[kv.slice(0, i)] = kv.slice(i + 1); }
|
|
return r;
|
|
},
|
|
async json(p, body, extra) { const r = await this.req(p, body === undefined ? { headers: extra } : { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extra), body: JSON.stringify(body) }); return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); } };
|
|
}
|
|
async function boot() {
|
|
const log = fs.openSync(path.join(OUT, 'server.log'), 'a');
|
|
srv = spawn(process.execPath, ['server.js'], { cwd: APP, env: ENV, stdio: ['ignore', log, log] });
|
|
for (let i = 0; i < 80; i++) { try { const r = await fetch(BASE + '/health'); if (r.ok) return; } catch (e) {} await sleep(150); }
|
|
throw new Error('server did not start; see qa/out/server.log');
|
|
}
|
|
async function stop() { const p = srv; srv = null; if (!p) return; const done = new Promise(r => p.once('exit', r)); p.kill('SIGINT'); await Promise.race([done, sleep(3000)]); }
|
|
// a member signed in by wallet signature. hub: { username, sponsorId } puts them in the hub; iap: InstantAdPay knows the wallet
|
|
async function walletMember(o = {}) {
|
|
const w = o.wallet || ethers.Wallet.createRandom(); const c = client(); const a = w.address.toLowerCase();
|
|
if (o.hub) c.hubId = person(o.hub.username, a, o.hub.sponsorId);
|
|
if (o.iap) IAP_KNOWS.add(a);
|
|
const ch = await c.json('/api/auth/challenge', { address: w.address });
|
|
const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) });
|
|
c.address = a; c.wallet = w; c.ok = v.ok === true && !!c.jar['vab.sid'];
|
|
return c;
|
|
}
|
|
const adBody = (n, extra) => Object.assign({ headline: 'Headline number ' + n, line1: 'First line for ad ' + n + ', plain text', line2: 'Second line ' + n, link: 'https://member-' + n + '.example-shop.com/offer?id=' + n }, extra || {});
|
|
// one page load + its verified visit
|
|
async function view(c, page, u, wait) {
|
|
const d = await c.json('/api/wire?page=' + page + (u ? '&u=' + encodeURIComponent(u) : ''));
|
|
if (!d.ticket) return { d, r: { verified: false, why: 'no-ticket' } };
|
|
await sleep(wait != null ? wait : 2100);
|
|
return { d, r: await c.json('/api/visit/seen', { ticket: d.ticket, visibleMs: wait != null ? wait : 2100 }) };
|
|
}
|
|
|
|
async function main() {
|
|
if (await fetch(BASE).then(() => true, () => false)) throw new Error('port ' + PORT + ' is already in use; set SMOKE_APP_PORT');
|
|
console.log('data dir', DATA);
|
|
|
|
console.log('1. copy rules');
|
|
const pub = path.join(APP, 'public');
|
|
const files = fs.readdirSync(pub).filter(f => f.endsWith('.html')).map(f => path.join(pub, f)).concat(fs.readdirSync(path.join(pub, 'assets')).filter(f => /\.(js|css)$/.test(f) && f !== 'wallet.js').map(f => path.join(pub, 'assets', f)));
|
|
const texts = files.map(f => [path.basename(f), fs.readFileSync(f, 'utf8')]).concat(['promokit.js', 'proof.js', 'server.js', 'tools/pages.mjs', 'tools/art.mjs'].map(f => [f, fs.readFileSync(path.join(APP, f), 'utf8')]));
|
|
ok(texts.every(([, t]) => !/[\u2014\u2013]/.test(t)), 'no em or en dashes in any page, script or copy source', texts.filter(([, t]) => /[\u2014\u2013]/.test(t)).map(x => x[0]));
|
|
const html = texts.filter(([n]) => n.endsWith('.html')).map(x => x[1]).join('\n');
|
|
ok(!/metamask/i.test(html), 'pages never name MetaMask');
|
|
ok(/SafePal or any other crypto wallet/.test(html), 'wallet copy says "SafePal or any other crypto wallet"');
|
|
ok(!/passive income|guaranteed (income|returns|profit)|earn (cash|money)|make money|get rich|up to \$?\d+ (a|per)|maximum (you|earn)/i.test(html), 'no income promises and no earnings caps in page copy');
|
|
ok(/never a subscription/i.test(html) && /A Boost buys advertising, not income\. Nothing is promised\./.test(html), 'Boost copy: one-time, never a subscription; "advertising, not income. Nothing is promised."');
|
|
ok(/TrustClickz/.test(html) && /615 Green Valley Drive, Moody, AL 35004/.test(html), 'legal pages name TrustClickz, 615 Green Valley Drive, Moody, AL 35004');
|
|
|
|
console.log('2. boot (prototype mode, temp data dir)');
|
|
await boot();
|
|
const cfg = await (await fetch(BASE + '/api/config')).json();
|
|
ok(cfg.boost.usd === 5 && cfg.boost.views === 500 && cfg.boost.sku === 1 && cfg.split.levels === 5 && cfg.split.levelPct === 10 && cfg.split.companyPct === 50, 'config: Boost $5 = 500 views, 5 levels x 10% + 50% company', cfg.boost);
|
|
ok(cfg.shop.live === true && cfg.shop.contract.toLowerCase() === SHOP.toLowerCase(), 'shop live against the stand-in contract');
|
|
ok(fs.readFileSync(path.join(OUT, 'server.log'), 'utf8').includes('files (prototype mode)'), 'server says prototype mode (no DOCSTORE_URL)');
|
|
|
|
console.log('3. pages');
|
|
const anon = client();
|
|
for (const p of ['/', '/how', '/my', '/boost', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy', '/admin', '/robots.txt', '/sitemap.xml', '/art/mark.svg', '/art/og-share.png', '/assets/vab.css', '/assets/common.js']) { const r = await anon.req(p); ok(r.status === 200, 'GET ' + p + ' 200', r.status); }
|
|
let r = await anon.req('/'); const home = await r.text();
|
|
ok(/<h1 class="slant"><span class="l1">Spread your ad<\/span> <span class="l2">5 levels deep<\/span><\/h1>/.test(home) && /id="boardCards"/.test(home) && /og:image" content="https:\/\/viraladblitz\.com\/art\/og-share\.png/.test(home), 'front page: "Spread your ad 5 levels deep" headline, board, Open Graph');
|
|
r = await anon.req('/how'); const how = await r.text();
|
|
ok((how.match(/<svg viewBox="[^"]+" role="img" aria-labelledby="[^"]+"/g) || []).length === 3 && /Your ad spreads down your team/.test(how) && /What counts as a view/.test(how) && /Boost: where your \$5 goes/.test(how) && /Start in 3 steps/.test(how)
|
|
&& (how.match(/<details>/g) || []).length >= 5 && /PASSED OVER/.test(how) && /A Boost buys advertising, not income\. Nothing is promised\./.test(how) && /SafePal or any other crypto wallet/.test(how) && !/[—–]/.test(how) && /"@type":"FAQPage"/.test(how), 'How it works page: 3 accessible diagrams, 4 sections, FAQ, pass-up shown, copy rules', how.length);
|
|
ok(/href="\/how#boost">How a Boost works</.test(home) && /href="\/how"/.test(home) && /'\/how', 'How it works'/.test(fs.readFileSync(path.join(APP, 'public/assets/common.js'), 'utf8')) && /<a href="\/how">How it works<\/a>/.test(fs.readFileSync(path.join(APP, 'public/assets/common.js'), 'utf8')), 'How it works linked from the nav, the footer and the front page ("How a Boost works")');
|
|
ok((await (await anon.req('/sitemap.xml')).text()).includes('/how</loc>'), 'sitemap lists /how');
|
|
ok(!r.headers.get('x-frame-options'), 'front page stays frameable (traffic exchanges)');
|
|
r = await anon.req('/my'); ok(r.headers.get('x-frame-options') === 'DENY', '/my is never framed');
|
|
ok(/script-src[^;]*https:\/\/linkspin\.app/.test(r.headers.get('content-security-policy') || ''), 'CSP admits linkspin.app (network zones)');
|
|
r = await anon.req('/nobody-at-all'); ok(r.status === 404 && /Back to the wire/.test(await r.text()), 'a username the hub does not know: 404');
|
|
r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in');
|
|
|
|
console.log('4. promo kit');
|
|
{ const kr = await anon.req('/api/promo-kit?u=smokeleader'); const k = await kr.json();
|
|
ok(kr.status === 200 && kr.headers.get('access-control-allow-origin') === '*', 'GET /api/promo-kit 200 with CORS open');
|
|
ok(k.links[0].url === 'https://viraladblitz.com/smokeleader' && k.links.slice(1).every(l => l.url.endsWith('?ref=smokeleader')), 'kit links: the member page + ?ref=', k.links.map(l => l.url));
|
|
ok(k.links.every(l => /^https:\/\/linkspin\.app\/r\/nwvab\?src=viraladblitz&s1=smokeleader/.test(l.tracked)), 'every link has a LinkSpin-tracked twin (nwvab, source viraladblitz)', k.links.map(l => l.tracked));
|
|
const words = JSON.stringify([k.lines, k.headlines, k.email, k.posts, k.note, k.tagline]);
|
|
ok(!/[\u2014\u2013]/.test(words) && !/passive income|guaranteed (income|returns|profit)|make money|metamask/i.test(words) && /\$5 one-time Boost buys 500 guaranteed network views/.test(words) && /SafePal or any other crypto wallet/.test(words), 'kit copy: no dashes, no income promises, Boost facts from config, SafePal wording');
|
|
ok(k.creatives.length === 21 && new Set(k.creatives.map(c => c.angle)).size === 3, 'kit: 21 creatives in 3 angles', k.creatives.length);
|
|
const bad = k.creatives.filter(c => /\d{2,4}x\d{2,4}|banner|[-_/]ads?[-_./]/i.test(c.url.replace('https://viraladblitz.com', ''))); ok(!bad.length, 'kit: creative paths are ad-blocker neutral', bad.map(c => c.url));
|
|
let dimOk = true; const dimBad = [];
|
|
for (const c of k.creatives) { const rr = await anon.req(new URL(c.url).pathname); const buf = Buffer.from(await rr.arrayBuffer()); const w = buf.readUInt32BE(16), h = buf.readUInt32BE(20);
|
|
if (rr.status !== 200 || w !== c.w || h !== c.h || !c.html.includes('href="https://viraladblitz.com/smokeleader"')) { dimOk = false; dimBad.push(c.key + ' ' + w + 'x' + h); } }
|
|
ok(dimOk, 'kit: every creative is a PNG at its exact size and its HTML links to the member page', dimBad);
|
|
const pr = await anon.req('/art/proof/vab-proof-royal.png'); ok(pr.status === 200 && pr.headers.get('content-type') === 'image/png', 'Telegram proof card image served'); }
|
|
|
|
console.log('5. sign-in and network membership');
|
|
// the hub line used through the test (nearest first above OWNER): L1 (ad) <- L2 (NO ad) <- L3 (ad, NO wallet in hub) <- L4 (ad) <- L5 (ad) <- L6 (ad) <- L7 (ad) <- TOP
|
|
const W = n => ethers.Wallet.createRandom();
|
|
const wTop = W(), w7 = W(), w6 = W(), w5 = W(), w4 = W(), w2 = W(), w1 = W(), wOwner = W(), wDown = W();
|
|
const idTop = person('topdog', wTop.address), id7 = person('seven', w7.address, idTop), id6 = person('six', w6.address, id7), id5 = person('five', w5.address, id6), id4 = person('four', w4.address, id5);
|
|
const id3 = person('three', null, id4); const id2 = person('two', w2.address, id3), id1 = person('one', w1.address, id2);
|
|
const idOwner = person('owner', wOwner.address, id1);
|
|
const STR = await walletMember({ iap: false }); let my = await STR.json('/api/my');
|
|
ok(STR.ok && my.netVerified === false, 'a wallet the network does not know: signed in, not a network member', my);
|
|
let pa = await STR.json('/api/my/ad', adBody(0)); ok(pa._status === 403 && /network members/.test(pa.error), 'a non-member cannot post a text ad', pa);
|
|
const M1 = await walletMember({ wallet: w1 }); my = await M1.json('/api/my');
|
|
ok(my.netVerified === true && my.username === 'one', 'a wallet the hub knows: network member, username from the hub', my);
|
|
const bad = client(); const x0 = ethers.Wallet.createRandom(), x1 = ethers.Wallet.createRandom();
|
|
const ch0 = await bad.json('/api/auth/challenge', { address: x0.address }); const v0 = await bad.json('/api/auth/verify', { address: x0.address, signature: await x1.signMessage(ch0.message) });
|
|
ok(v0._status === 400 && !bad.jar['vab.sid'], 'a signature from another wallet is refused');
|
|
// network sign-in from InstantAdPay: /sso/start -> IAP mints a token -> /sso/in
|
|
const L = client(); r = await L.req('/sso/start?mode=go&via=iap&to=%2Fmy'); const loc = r.headers.get('location') || '';
|
|
ok(r.status === 302 && loc.startsWith('https://iap.invalid/sso/check?st=') && loc.includes('&r=viraladblitz'), 'network sign-in hops to InstantAdPay with r=viraladblitz', loc);
|
|
const nsso = require(path.join(APP, 'networksso.js')); process.env.NETWORK_SSO_SECRET = SSO_SECRET;
|
|
const tok = nsso.mint({ iss: 'iap', aud: 'viraladblitz', email: 'owner@example.org', wallet: wOwner.address.toLowerCase(), name: 'owner', st: new URL(loc).searchParams.get('st'), to: '/my' });
|
|
r = await L.req('/sso/in?t=' + encodeURIComponent(tok));
|
|
ok(r.status === 302 && r.headers.get('location') === '/my' && !!L.jar['vab.sid'], 'the network token signs the member in', { s: r.status, l: r.headers.get('location') });
|
|
r = await L.req('/sso/in?t=' + encodeURIComponent(tok)); ok(!/vab\.sid=[0-9a-f]{64}/.test(String(r.headers.get('set-cookie') || '')), 'a network token works only once');
|
|
const OWN = L; OWN.address = wOwner.address.toLowerCase();
|
|
my = await OWN.json('/api/my'); ok(my.username === 'owner' && my.netVerified && my.page === 'https://viraladblitz.com/owner', 'network member keeps the network username; page = viraladblitz.com/<username>', my);
|
|
ok(HUB.resolves > 0 && HUB.badSig === 0, 'hub lookups are signed as viraladblitz with HUB_SECRET', HUB.badSig);
|
|
HUB.down = true; const FB = await walletMember({ iap: true }); my = await FB.json('/api/my');
|
|
ok(my.netVerified === true, 'hub unreachable: InstantAdPay verifies the wallet (fallback)', my); HUB.down = false; await sleep(400);
|
|
|
|
console.log('6. the free text ad');
|
|
pa = await M1.json('/api/my/ad', adBody(1, { headline: 'ab' })); ok(pa._status === 400 && /headline/.test(pa.error), 'a 2-character headline is refused', pa);
|
|
pa = await M1.json('/api/my/ad', adBody(1, { headline: 'x'.repeat(61) })); ok(pa._status === 400, 'a 61-character headline is refused');
|
|
pa = await M1.json('/api/my/ad', adBody(1, { line1: '' })); ok(pa._status === 400 && /first line/.test(pa.error), 'the first line is required', pa);
|
|
pa = await M1.json('/api/my/ad', adBody(1, { link: 'http://plain.com/' })); ok(pa._status === 400 && /https/.test(pa.error), 'an http link is refused', pa);
|
|
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://bit.ly/x' })); ok(pa._status === 400 && /shortener/.test(pa.error), 'a link shortener is refused', pa);
|
|
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://10.0.0.1/' })); ok(pa._status === 400, 'an IP-address link is refused');
|
|
pa = await M1.json('/api/my/ad', adBody(1, { headline: 'Line <b>one</b> \u2014 deal', link: 'https://member-1.example-shop.com/o?c={clickid}&p={placement}' }));
|
|
ok(pa.ok && pa.created === true, 'a member posts their free text ad', pa);
|
|
const ad1 = pa.ad.id;
|
|
my = await M1.json('/api/my'); ok(my.ad.headline === 'Line b one /b - deal', 'markup and long dashes are stripped from ad text', my.ad.headline);
|
|
pa = await M1.json('/api/my/ad', adBody(1)); ok(pa.ok && pa.created === false && pa.ad.id === ad1, 'posting again edits the same ad (one ad per member)', pa);
|
|
// the rest of the line posts ads (L2 never does; L3 has no wallet in the hub but signs in with one the hub does not tie to them)
|
|
const M = { 1: M1 };
|
|
for (const [k, w] of [[4, w4], [5, w5], [6, w6], [7, w7], ['top', wTop]]) { M[k] = await walletMember({ wallet: w }); const q = await M[k].json('/api/my/ad', adBody(k, k === 5 ? { link: 'https://member-5.example-shop.com/o?c={clickid}&p={placement}' } : {})); ok(q.ok, 'line member ' + k + ' posts an ad'); }
|
|
const OWNAD = (await OWN.json('/api/my/ad', adBody('own'))).ad.id;
|
|
const DOWN = await walletMember({ wallet: wDown, hub: { username: 'downline', sponsorId: idOwner } }); await DOWN.json('/api/my/ad', adBody('down'));
|
|
|
|
console.log('7. member page from the hub line');
|
|
r = await anon.req('/owner'); ok(r.status === 200 && /member\.js/.test(await r.text()) && /vab\.ref=owner/.test(String(r.headers.get('set-cookie'))), 'GET /owner serves the member page and remembers the referrer');
|
|
let mp = await anon.json('/api/wire?page=member&u=owner');
|
|
ok(mp.page && mp.page.ad && mp.page.ad.id === OWNAD && mp.page.username === 'owner', 'member page: the owner\'s own ad', mp.page && mp.page.ad);
|
|
const lv = (mp.page.line || []).map(x => [x.level, x.depth, x.owner]);
|
|
ok(JSON.stringify(lv) === JSON.stringify([[1, 1, '@one'], [2, 4, '@four'], [3, 5, '@five'], [4, 6, '@six'], [5, 7, '@seven']]), 'five upline ads labelled LEVEL 1 to 5 in display order (real places 1,4,5,6,7): place 2 (no ad) and place 3 (no wallet) skipped, the 6th with an ad (topdog) not shown', lv);
|
|
ok(mp.page.joinUrl === 'https://instantadpay.com/join/owner', 'join link: the InstantAdPay join page under the page owner', mp.page.joinUrl);
|
|
mp = await anon.json('/api/wire?page=member&u=nobody-here'); ok(mp._status === 404, 'unknown member: 404 from the page API');
|
|
|
|
console.log('8. verified visits, views and clicks');
|
|
const botC = client({ ua: 'Mozilla/5.0 (compatible; Googlebot/2.1)' }); let wd = await botC.json('/api/wire?page=front'); ok(!wd.ticket, 'bots get no visit ticket');
|
|
const early = client(); let vv = await view(early, 'front', null, 300); ok(!vv.r.verified && vv.r.why === 'early', 'a visit sent before the timer is not verified', vv.r);
|
|
const V1 = client(); vv = await view(V1, 'member', 'owner');
|
|
ok(vv.r.verified && vv.r.views === 8 && /^[0-9a-f]{24}$/.test(vv.r.vt), 'a verified visit on a member page: every ad shown gets a view (own + 5 line + the rest on the ticker: 8 ads), verified token issued', vv.r);
|
|
const v2 = await view(V1, 'member', 'owner'); ok(v2.r.verified && v2.r.views === 0, 'the same visitor again: no second view of the same ads in 24 h', v2.r);
|
|
my = await OWN.json('/api/my'); ok(my.ad.views === 1, 'the owner\'s ad has 1 verified view', my.ad.views);
|
|
const ownView = await view(OWN, 'member', 'owner'); my = await OWN.json('/api/my'); ok(ownView.r.verified && my.ad.views === 1, 'the owner viewing their own page never counts for their own ad', my.ad.views);
|
|
const shared = '198.51.100.7'; const sv = [0, 1, 2].map(i => client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/' + i }));
|
|
const svr = []; for (const c of sv) svr.push((await view(c, 'front')).r);
|
|
ok(svr.filter(x => x.verified).length === 2 && svr[2].why === 'ip', 'only 2 browsers per connection are verified per day', svr);
|
|
// clicks
|
|
r = await anon.req('/go/' + ad1 + '?p=ticker'); const gl = new URL(r.headers.get('location'));
|
|
ok(r.status === 302 && gl.hostname === 'member-1.example-shop.com', '/go/<ad> sends to the ad link', r.headers.get('location'));
|
|
{ const a5 = (await M[5].json('/api/my')).ad.id; const r5 = await anon.req('/go/' + a5 + '?p=ticker'); const g5 = new URL(r5.headers.get('location'));
|
|
ok(/^[0-9a-f]{16}$/.test(g5.searchParams.get('c')) && g5.searchParams.get('p') === 'ticker', 'tracking macros: {clickid} and {placement} filled on every click', r5.headers.get('location')); }
|
|
r = await V1.req('/go/' + ad1 + '?p=level1&v=' + vv.r.vt); ok(r.status === 302, 'a verified visitor clicks');
|
|
r = await V1.req('/go/' + ad1 + '?p=level1&v=' + vv.r.vt); r = await V1.req('/go/' + ad1 + '?p=level1&v=' + 'f'.repeat(24));
|
|
const bc = client({ ua: 'curl/8' }); await bc.req('/go/' + ad1);
|
|
my = await M1.json('/api/my'); ok(my.ad.vclicks === 1 && my.ad.clicks >= 4, 'clicks: 1 verified (repeat, bad token and unverified ones are raw only, bots not counted)', { v: my.ad.vclicks, c: my.ad.clicks });
|
|
const Vb = client(); const vb = await view(Vb, 'front'); await Vb.req('/go/' + ad1 + '?v=' + vb.r.vt); const Vc = client(); const vcv = await view(Vc, 'front'); const ad4 = (await M[4].json('/api/my')).ad.id; await Vc.req('/go/' + ad4 + '?v=' + vcv.r.vt);
|
|
await OWN.req('/go/' + OWNAD + '?v=' + ownView.r.vt);
|
|
let fr = await anon.json('/api/wire?page=front');
|
|
ok(fr.board.items[0].id === ad1 && fr.board.items[0].clicks === 2 && fr.board.items[0].rank === 1 && fr.board.items.length === 2, 'Top ads this week: ranked by verified clicks (the owner\'s own click never counts)', fr.board.items.map(x => [x.id, x.clicks]));
|
|
ok(fr.today.vclicks === 3 && fr.today.ads >= 8, 'today on the wire: verified clicks + ads live', fr.today);
|
|
|
|
console.log('9. Boost orders (line voucher)');
|
|
let q = await OWN.json('/api/quote?qty=1'); ok(q.usd === 5 && q.views === 500 && BigInt(q.wei) === 20n * 10n ** 18n, 'quote: $5 at $0.25 = 20 POL (from the contract)', q);
|
|
q = await OWN.json('/api/quote?qty=11'); ok(q._status === 400, '11 Boosts refused (1 to 10)');
|
|
const NOAD = await walletMember({ wallet: w2 }); let od = await NOAD.json('/api/my/order', { qty: 1 }); ok(od._status === 400 && /text ad first/.test(od.error), 'no ad: no Boost', od);
|
|
od = await OWN.json('/api/my/order', { qty: 2 });
|
|
const call = IFACE.parseTransaction({ data: od.data, value: od.value });
|
|
const line = call.args[3].map(a => a.toLowerCase());
|
|
ok(od._status === 200 && call.name === 'buy' && Number(call.args[0]) === 1 && Number(call.args[1]) === 2 && Number(call.args[2]) === OWNAD, 'order = buy(sku 1, qty 2, ref = the owner\'s ad id)', od);
|
|
ok(JSON.stringify(line) === JSON.stringify([w1, w2, w4, w5, w6, w7, wTop].map(w => w.address.toLowerCase())), 'the voucher line = the hub line\'s wallets nearest first (L3 without a wallet left out)', line);
|
|
const rec = ethers.verifyTypedData({ name: 'VABShop', version: '1', chainId: 137, verifyingContract: ethers.getAddress(SHOP.toLowerCase()) }, { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'line', type: 'address[]' }, { name: 'deadline', type: 'uint256' }] },
|
|
{ buyer: ethers.getAddress(OWN.address), line: call.args[3], deadline: call.args[4] }, call.args[5]);
|
|
ok(rec === KEEPER, 'the voucher is signed by the keeper (EIP-712 VABShop v1)', rec);
|
|
ok(BigInt(od.value) === 40n * 10n ** 18n * 101n / 100n && Number(call.args[4]) > Date.now() / 1000 + 1700, 'value = quote + 1% (refunded by the contract), deadline 30 minutes', od.value);
|
|
CHAIN.bound.set(M1.address, w2.address.toLowerCase());
|
|
od = await M1.json('/api/my/order', { qty: 1 }); const c2 = IFACE.parseTransaction({ data: od.data, value: od.value });
|
|
ok(od.why === 'bound' && c2.args[3].length === 0 && c2.args[5] === '0x', 'a member whose line is already bound on chain: no voucher (the chain\'s binding wins)', od.why);
|
|
CHAIN.bound.delete(M1.address); HUB.down = true; await sleep(350);
|
|
od = await M[4].json('/api/my/order', { qty: 1 }); ok(od._status === 503 && /sponsor line/.test(od.error), 'hub unreachable: the Boost waits (the line is never signed partial)', od);
|
|
HUB.down = false; await sleep(350);
|
|
CHAIN.down = true; od = await OWN.json('/api/my/order', { qty: 1 }); ok(od._status === 503, 'chain unreachable: no order'); CHAIN.down = false;
|
|
|
|
console.log('10. a Boost recorded from the chain');
|
|
// the owner's 2 Boosts: line bound; one, four, five, six, seven paid; two passed over (place 2)
|
|
const b1 = chainBoost({ buyer: wOwner.address, qty: 2, ref: OWNAD, views: 6, bound: [[wOwner.address, w1.address], [w1.address, w2.address], [w2.address, w4.address]],
|
|
over: [[w2.address, 2]], pays: [[w1.address, 1], [w4.address, 3], [w5.address, 4], [w6.address, 5], [w7.address, 6]] });
|
|
let led; for (let i = 0; i < 40; i++) { led = await anon.json('/api/ledger'); if (led.items && led.items.length && led.items[0].pays.length > 1 && led.items[0].pays[0].to) break; await sleep(150); }
|
|
const it = led.items[0];
|
|
ok(led.items.length === 1 && it.tx === b1.tx && it.qty === 2 && it.buyerName === 'owner' && it.ad && it.ad.id === OWNAD, 'the ledger shows the Boost (buyer, ad)', it);
|
|
ok(it.pays.filter(p => p.level > 0).map(p => [p.level, p.depth, p.name, p.wei]).every((x, i) => x[0] === i + 1 && x[3] === b1.share.toString()) && it.pays.find(p => p.level === 0).wei === b1.company.toString(), 'the ledger split from the receipt: 5 levels x 10% with their places, company 50%', it.pays);
|
|
ok(it.passedOver.length === 1 && it.passedOver[0].depth === 2 && it.passedOver[0].name === 'two', 'passed over: @two at place 2 (never boosted)', it.passedOver);
|
|
for (let i = 0; i < 20 && !TG.length; i++) await sleep(150);
|
|
ok(TG.length === 1 && TG[0].method === 'sendPhoto' && TG[0].token === 'botstandin-token' && TG[0].body.message_thread_id === 632242 && /\/art\/proof\/vab-proof-[a-z]+\.png$/.test(TG[0].body.photo), 'Telegram: one photo card in the payments topic', TG.map(t => t.method));
|
|
const cap = TG[0].body.caption || '';
|
|
ok(/@owner boosted "Headline number own"/.test(cap) && /Level 1 10%: 4\.0000 POL → @one/.test(cap) && /Level 2 10%: 4\.0000 POL → @four \(place 3 in the line\)/.test(cap) && /ViralAdBlitz: 20\.0000 POL/.test(cap), 'card: buyer, ad, every level with POL and place, company', cap);
|
|
ok(/1 person in the line had not boosted yet and was passed over/.test(cap) && /This week: 2 Boosts · \d+ ads live · \d+ verified clicks/.test(cap) && /explorer\.invalid\/tx\/0x[0-9a-f]{64}/.test(cap) && /viraladblitz\.com\/ledger/.test(cap) && !/[\u2014\u2013]/.test(cap), 'card: passed-over line, week stats, verify + ledger links, no dashes', cap);
|
|
my = await OWN.json('/api/my'); ok(my.boosts.length === 1 && my.boosts[0].views === 6 && my.boosts[0].delivered === 0 && my.boosts[0].status === 'delivering', 'My page: the Boost with its guaranteed views', my.boosts);
|
|
my = await M[4].json('/api/my'); ok(my.earned.items.length === 1 && my.earned.items[0].level === 2 && my.earned.wei === b1.share.toString(), 'My page for @four: the level 2 share paid to them', my.earned);
|
|
const rc = await anon.json('/api/recent'); ok(rc.items.some(x => x.kind === 'boost' && x.name === 'owner' && x.levels === 5), 'toasts: the Boost with 5 sponsors paid', rc.items);
|
|
for (let i = 0; i < 30 && !HUB.got.length; i++) await sleep(150);
|
|
ok(HUB.got.length === 1 && HUB.got[0].route === '/v1/contract-bind' && HUB.got[0].body.contract === 'viraladblitz' && HUB.got[0].body.wallet === OWN.address && HUB.got[0].body.sponsorRef === w1.address.toLowerCase() && HUB.got[0].body.spentCents === 1000, 'hub report: contract-bind for the buyer with their direct sponsor', HUB.got);
|
|
CHAIN.replayAll = true; await sleep(800); CHAIN.replayAll = false;
|
|
led = await anon.json('/api/ledger'); ok(led.items.length === 1 && TG.length === 1, 'a flaky RPC re-sending old logs: no second record, no second Telegram post');
|
|
// an old Boost (block 3 hours ago) is recorded but never posted
|
|
const old = chainBoost({ buyer: w4.address, qty: 1, ref: 0, views: 500, blockAt: Math.floor(Date.now() / 1000) - 3 * 3600, pays: [[w5.address, 1]] });
|
|
for (let i = 0; i < 30; i++) { led = await anon.json('/api/ledger'); if (led.items.length === 2) break; await sleep(150); } await sleep(500);
|
|
ok(led.items.length === 2 && TG.length === 1, 'a Boost older than 2 hours is recorded but never posted to Telegram', TG.length);
|
|
my = await M[4].json('/api/my'); ok(my.boosts.length === 1 && my.boosts[0].adId === (await M[4].json('/api/my')).ad.id, 'a Boost with ref 0 attaches to the buyer\'s live ad', my.boosts);
|
|
|
|
console.log('11. Boost delivery');
|
|
fr = await anon.json('/api/wire?page=front');
|
|
ok(fr.ticker.some(t => t.id === OWNAD && t.boosted), 'the Boosted ad is starred on the ticker', fr.ticker.map(t => [t.id, t.boosted]));
|
|
mp = await anon.json('/api/wire?page=member&u=downline');
|
|
const mtop = await anon.json('/api/wire?page=member&u=topdog');
|
|
ok(mp.page.line[0] && mp.page.line[0].id === OWNAD && mp.page.line[0].boosted, 'downline page: the owner at level 1, starred', mp.page.line[0]);
|
|
{ const onPage = new Set([mp.page.ad.id].concat(mp.page.line.map(x => x.id))); ok(mp.page.boosted.every(x => !onPage.has(x.id)), 'downline page: a Boosted place never repeats an ad already on the page', mp.page.boosted.map(x => x.id)); }
|
|
ok(mtop.page.line.length === 0 && mtop.page.boosted.length === 2 && mtop.page.boosted.every(x => x.boosted) && mtop.page.boosted.some(x => x.id === OWNAD), 'top of the line (no upline): the 2 Boosted places show Boosted ads', mtop.page.boosted.map(x => x.id));
|
|
let delivered = 0; const views = [];
|
|
for (let i = 0; i < 7; i++) { const c = client(); const x = await view(c, 'front'); views.push(x.r.boostViews); }
|
|
my = await OWN.json('/api/my'); delivered = my.boosts[0].delivered;
|
|
ok(delivered === 6 && my.boosts[0].status === 'delivered' && my.boosts[0].remaining === 0, 'every verified visitor delivers one view; the Boost finishes at its 6 guaranteed views', { delivered, s: my.boosts[0].status, views });
|
|
const st = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
|
|
ok(st.rows.boostViews >= 6 + 7 && st.boosts.delivered >= 6, 'every counted Boost view is kept as an audit row', st.rows);
|
|
fr = await anon.json('/api/wire?page=front'); ok(!fr.ticker.some(t => t.id === OWNAD && t.boosted), 'a delivered Boost is no longer starred');
|
|
|
|
console.log('12. Network Ad Space finishing (stand-in NAS database)');
|
|
{
|
|
process.env.DATA_DIR = path.join(DATA, 'nas'); fs.mkdirSync(process.env.DATA_DIR, { recursive: true }); require(path.join(APP, 'config.js')).reset();
|
|
const vabnas = require(path.join(APP, 'vabnas.js')); const NAS = { rows: [], pays: [] };
|
|
const query = async (sql, args) => {
|
|
if (/^INSERT INTO payments/.test(sql)) { NAS.pays.push(args); return { insertId: NAS.pays.length }; }
|
|
if (/^INSERT INTO sponsorads/.test(sql)) { NAS.rows.push({ ID: NAS.rows.length + 100, sql, args, assigned: args[4], remaining: args[5] }); return { insertId: NAS.rows.length + 99 }; }
|
|
if (/^SELECT assigned, remaining/.test(sql)) { const x = NAS.rows.find(y => y.ID === args[0]); return x ? [{ assigned: x.assigned, remaining: x.remaining }] : []; }
|
|
return [];
|
|
};
|
|
const ad = { id: 9, status: 'live', headline: 'Late Boost ad', line1: 'Line one', line2: 'Line two' };
|
|
const boosts = [{ key: 'tx1:0', adId: 9, views: 500, delivered: 120, dueAt: Date.now() - 1000 }, { key: 'tx2:0', adId: 9, views: 500, delivered: 10, dueAt: Date.now() + 86400000 }, { key: 'tx3:0', adId: 9, views: 500, delivered: 500, dueAt: Date.now() - 1000 }];
|
|
vabnas.init({ boosts: () => boosts, remaining: b => Math.max(0, b.views - b.delivered - vabnas.boostServed(b.key)), ad: () => ad }, { query });
|
|
const t1 = await vabnas.tick();
|
|
ok(t1.placed === 1 && NAS.rows.length === 1 && NAS.rows[0].assigned === 380, 'a Boost past 30 days with 380 views owed gets one NAS text ad for exactly 380; one still in its window and one delivered are left alone', { t1, rows: NAS.rows.map(r2 => r2.assigned) });
|
|
const a0 = NAS.rows[0].args; ok(a0[1] === 'Late Boost ad' && a0[2] === 'Line one Line two' && a0[3] === 'https://viraladblitz.com/go/9?p=nas' && /,1,0,\?\)$/.test(NAS.rows[0].sql.replace(/\s+/g, '')), 'NAS text ad: headline = subject, lines = body, link through /go/<ad>?p=nas (clicks count here), pid 1 (text)', a0.slice(0, 4));
|
|
NAS.rows[0].remaining = 380 - 150; await vabnas.tick();
|
|
ok(vabnas.boostServed('tx1:0') === 150 && NAS.rows.length === 1, 'NAS impressions read back (assigned - remaining) count toward the Boost; no second NAS ad', vabnas.boostServed('tx1:0'));
|
|
NAS.rows[0].remaining = -40; await vabnas.tick(); ok(vabnas.boostServed('tx1:0') === 380, 'NAS counter drift above assigned is clamped');
|
|
}
|
|
|
|
console.log('13. old site links');
|
|
r = await anon.req('/api/admin/oldrefs', { method: 'POST', headers: { 'x-admin-token': ADMIN }, body: JSON.stringify({ oldrefs: { janie23: 'owner', 'bad key!': 'x', frank: '<b>' } }) });
|
|
const or = await r.json(); ok(or.ok && or.total === 1 && or.skipped === 2, 'admin loads the old-username map (bad rows skipped)', or);
|
|
for (const [from, to] of [['/?janie23', '/owner'], ['/?janie23&fbclid=x', '/owner'], ['/splashpg.php?pid=4&r=janie23', '/owner'], ['/lcp.php?pid=2&r=JANIE23', '/owner'], ['/?nobodyold', '/'], ['/members.php', '/'], ['/splashpg.php?pid=4&r=nobody', '/']]) {
|
|
r = await anon.req(from); ok(r.status === 301 && r.headers.get('location') === to, 'old link ' + from + ' -> ' + to, r.headers.get('location')); }
|
|
r = await anon.req('/?ref=owner'); ok(r.status === 200, '/?ref=<name> is not an old link');
|
|
|
|
console.log('14. admin');
|
|
r = await anon.req('/api/admin/status'); ok(r.status === 401, 'admin needs the token');
|
|
const sj = JSON.stringify(st);
|
|
ok(st.shop.vouchers && st.shop.keeper === KEEPER && !sj.includes(KEEPER_PK.slice(2)) && !sj.includes(HUB_SECRET) && !sj.includes('standin-token') && !sj.includes(SSO_SECRET), 'admin status: keeper address only, no key or secrets', st.shop);
|
|
const lk = await anon.json('/api/admin/member-lookup?q=four', undefined, { 'x-admin-token': ADMIN }); ok(lk.address === w4.address.toLowerCase() && lk.earned.items.length === 1 && lk.paidBy.length === 1, 'member lookup: earnings and who paid them', lk.earned);
|
|
const rm = await anon.json('/api/admin/ad', { id: (await M[7].json('/api/my')).ad.id, status: 'removed', note: 'smoke' }, { 'x-admin-token': ADMIN }); ok(rm.ok, 'admin removes an ad');
|
|
mp = await anon.json('/api/wire?page=member&u=owner'); ok(!mp.page.line.some(x => x.owner === '@seven') && mp.page.line.some(x => x.owner === '@topdog'), 'a removed ad leaves the member pages; the next one up (place 8) moves in', mp.page.line.map(x => [x.level, x.owner]));
|
|
|
|
console.log('14b. LinkSpin tracked links for text ads (lstrack.js)');
|
|
my = await M1.json('/api/my'); ok(my.ad.status === 'live' && my.linkspin && my.linkspin.on && my.linkspin.state === 'pending' && my.linkspin.track === true, 'LinkSpin not answering the endpoint yet: the ad is live, tracking pending (fails soft)', my.linkspin);
|
|
r = await anon.req('/go/' + ad1 + '?p=ticker'); ok(new URL(r.headers.get('location')).hostname === 'member-1.example-shop.com', 'while LinkSpin is down /go/<ad> sends to the member\'s own link', r.headers.get('location'));
|
|
LS.up = true; await sleep(1500);
|
|
my = await M1.json('/api/my'); const lsLink = my.linkspin && my.linkspin.link;
|
|
ok(my.linkspin.state === 'tracked' && lsLink === 'https://spin.test/r/' + (LS.links.get('one:' + ad1) || {}).code + '?s1=' + ad1 + '&placement=' + ad1, 'LinkSpin up: the retry sweep makes the tracked link on the member\'s own account', my.linkspin);
|
|
const ec = LS.calls.find(c => c.op === 'ensure' && c.username === 'one');
|
|
ok(ec && ec.links.length === 1 && ec.links[0].id === String(ad1) && ec.links[0].url === my.ad.link && !ec.email && LS.badSig === 0, 'the call: signed net.v1, network username, ad id as the item id, the ad link as destination (no email sent)', ec);
|
|
const clicksBefore = my.ad.clicks;
|
|
r = await anon.req('/go/' + ad1 + '?p=ticker'); ok(r.status === 302 && r.headers.get('location') === lsLink, '/go/<ad> now sends through the LinkSpin tracked link', r.headers.get('location'));
|
|
my = await M1.json('/api/my'); ok(my.ad.clicks === clicksBefore + 1, 'the click still counts here too');
|
|
{ const a5 = (await M[5].json('/api/my')); ok(a5.linkspin.state === 'macros' && !LS.calls.some(c => c.username === 'five'), 'an ad link with {clickid}/{placement} is not sent to LinkSpin (macros are filled here)', a5.linkspin); }
|
|
LS.stats.one = { [ad1]: { hits: 7, hits30: 3, unique30: 2 } }; await sleep(150);
|
|
my = await M1.json('/api/my'); ok(my.linkspin.clicks && my.linkspin.clicks.hits === 7 && my.linkspin.clicks.hits30 === 3 && my.linkspin.clicks.unique30 === 2, 'My page shows the ad\'s clicks as LinkSpin counts them', my.linkspin);
|
|
const code1 = (LS.links.get('one:' + ad1) || {}).code;
|
|
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://member-1.example-shop.com/new-offer' }));
|
|
ok(pa.ok && pa.linkspin === 'tracked' && LS.links.get('one:' + ad1).url === 'https://member-1.example-shop.com/new-offer' && LS.links.get('one:' + ad1).code === code1, 'editing the ad link updates the same LinkSpin link right away', pa);
|
|
LS.up = false;
|
|
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://member-1.example-shop.com/third' }));
|
|
r = await anon.req('/go/' + ad1); ok(pa.ok && pa.linkspin === 'pending' && r.headers.get('location') === 'https://member-1.example-shop.com/third', 'edited while LinkSpin is down: saved, and /go/<ad> never sends to the old tracked destination', [pa, r.headers.get('location')]);
|
|
LS.up = true; const n0 = LS.calls.length;
|
|
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://member-1.example-shop.com/third', track: false }));
|
|
r = await anon.req('/go/' + ad1); my = await M1.json('/api/my');
|
|
ok(pa.ok && pa.linkspin === 'off' && my.ad.track === false && my.linkspin.state === 'off' && r.headers.get('location') === 'https://member-1.example-shop.com/third', '"Track with LinkSpin" off: /go/<ad> sends straight to the link', [pa, my.linkspin]);
|
|
await sleep(900); ok(!LS.calls.slice(n0).some(c => c.op === 'ensure' && c.username === 'one'), 'tracking off: the sweep leaves that ad alone');
|
|
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://member-1.example-shop.com/third' }));
|
|
ok(pa.linkspin === 'off', 'an edit without the toggle keeps tracking off', pa);
|
|
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://member-1.example-shop.com/third', track: true }));
|
|
r = await anon.req('/go/' + ad1); ok(pa.linkspin === 'tracked' && r.headers.get('location').startsWith('https://spin.test/r/' + code1), 'switched back on: tracked again, same LinkSpin code', [pa, r.headers.get('location')]);
|
|
{ const NL = await walletMember({ hub: { username: 'nolsacct', sponsorId: idOwner } }); const q2 = await NL.json('/api/my/ad', adBody('nl')); const m2 = await NL.json('/api/my');
|
|
ok(q2.ok && q2.linkspin === 'no-account' && m2.linkspin.state === 'no-account', 'no LinkSpin account for the username: the ad works with its own link', m2.linkspin); }
|
|
{ const s2 = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN }); ok(s2.linkspin && s2.linkspin.on === true && s2.linkspin.ensured >= 3 && s2.linkspin.failed >= 1 && !JSON.stringify(s2.linkspin).includes(SSO_SECRET), 'admin status: LinkSpin tracking counters, no secret', s2.linkspin); }
|
|
|
|
console.log('14c. PolHunter mission (front page, How it works)');
|
|
{ const hr = await anon.req('/'); const hh = await hr.text(); const csp = hr.headers.get('content-security-policy') || '';
|
|
ok(/<script src="https:\/\/polhunter\.com\/embed\.js" data-slots="3" data-selector="\.steps \.step" async><\/script>/.test(hh) && (hh.match(/class="step"/g) || []).length === 3, 'front page carries the PolHunter embed on the 3 How it works steps');
|
|
ok(/script-src[^;]*https:\/\/polhunter\.com/.test(csp) && /connect-src[^;]*https:\/\/polhunter\.com/.test(csp), 'CSP admits polhunter.com in script-src and connect-src'); }
|
|
{ const H = client(); const before = (await M1.json('/api/my')).ad.views;
|
|
let w = await H.json('/api/wire?page=front&hunt=1'); ok(w._status === 200 && !w.ticket && w.hunt === true && w.ticker.length > 0, 'a hunter (hunt=1) gets the page but no visit ticket: never a verified view', { t: w.ticket, h: w.hunt });
|
|
w = await H.json('/api/wire?page=front&src=' + encodeURIComponent('https://polhunter.com/app')); ok(!w.ticket && w.hunt === true, 'a visit from polhunter.com gets no ticket either');
|
|
w = await H.json('/api/wire?page=member&u=owner&hunt=1'); ok(!w.ticket, 'hunt=1 on a member page: no ticket');
|
|
const r9 = await H.json('/api/visit/seen', { ticket: 'f'.repeat(24), visibleMs: 9000 }); ok(r9.verified === false, 'no ticket, no verified visit');
|
|
ok((await M1.json('/api/my')).ad.views === before, 'hunter visits add no views to any ad'); }
|
|
await sleep(1000); // the store writes 800 ms after a change; a Windows kill has no SIGINT flush
|
|
console.log('15. restart');
|
|
await stop(); await boot(); await sleep(500);
|
|
my = await OWN.json('/api/my'); ok(my.ad && my.ad.id === OWNAD && my.boosts[0].delivered === 6, 'after a restart: ads, Boosts and delivery are kept', my.boosts);
|
|
r = await anon.req('/go/' + ad1); ok(r.headers.get('location').startsWith('https://spin.test/r/'), 'after a restart: the tracked link is kept', r.headers.get('location'));
|
|
led = await anon.json('/api/ledger'); ok(led.items.length === 2 && TG.length === 1, 'after a restart: no re-record, no repost');
|
|
const again = await view(client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/9' }), 'front'); ok(!again.r.verified && again.r.why === 'ip', 'after a restart: the per-connection cap still holds (rebuilt from the visit rows)', again.r);
|
|
|
|
if (!process.env.SKIP_UI && fs.existsSync(PW)) {
|
|
console.log('16. Playwright renders (desktop 1280 + phone 390)');
|
|
const { chromium } = require(PW); const browser = await chromium.launch();
|
|
for (const [label, vp] of [['desktop', { width: 1280, height: 900 }], ['phone', { width: 390, height: 844 }]]) {
|
|
const ctx = await browser.newContext({ viewport: vp, isMobile: label === 'phone', userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36 SmokeUI-' + label });
|
|
// nothing leaves this machine; UI_FONTS=1 lets Google Fonts through so the screenshots show the real type (read-only font GETs)
|
|
await ctx.route(/^https:\/\//, rt => (process.env.UI_FONTS && /^https:\/\/fonts\.(googleapis|gstatic)\.com\//.test(rt.request().url())) ? rt.continue() : rt.abort());
|
|
const errs = []; const pg = await ctx.newPage(); pg.on('pageerror', e => errs.push(e.message));
|
|
for (const [p, sel] of [['/', '#boardCards .paper'], ['/how', '.dg svg[role=img]'], ['/owner', '#levels .lvl'], ['/boost', '#bQty option'], ['/ledger', '#rows tbody tr'], ['/contract', '#facts th'], ['/promote', '#kit .card'], ['/terms', '.legal .card'], ['/disclaimer', '.legal .card'], ['/privacy', '.legal .card']]) {
|
|
await pg.goto(BASE + p, { waitUntil: 'domcontentloaded' }); await pg.waitForSelector(sel, { timeout: 8000 }).catch(() => {});
|
|
const found = await pg.$$eval(sel, els => els.length);
|
|
const wide = await pg.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
|
|
ok(found > 0 && wide <= 1, label + ' ' + p + ': renders (' + sel + ') with no sideways scroll', { found, wide });
|
|
await pg.screenshot({ path: path.join(OUT, label + '-' + (p === '/' ? 'front' : p.slice(1)) + '.png'), fullPage: true });
|
|
}
|
|
{ const cerr = [], bad = []; const onC = m => { if (m.type() === 'error' && !/Failed to load resource|net::ERR_FAILED/.test(m.text())) cerr.push(m.text()); }; const onR = rs => { if (rs.url().startsWith(BASE) && rs.status() >= 400) bad.push(rs.status() + ' ' + rs.url()); };
|
|
pg.on('console', onC); pg.on('response', onR);
|
|
await pg.goto(BASE + '/how', { waitUntil: 'load' }); await pg.waitForSelector('#ticker .run a', { timeout: 8000 }).catch(() => {});
|
|
const hv = await pg.evaluate(() => ({ svgs: [...document.querySelectorAll('.dg svg')].map(s => Math.round(s.getBoundingClientRect().width)), dash: /[—–]/.test(document.body.innerText), nav: !!document.querySelector('nav.top a.on[href="/how"]'), foot: !!document.querySelector('footer a[href="/how"]'), wide: document.documentElement.scrollWidth - window.innerWidth }));
|
|
await pg.click('.faq details summary'); const opened = await pg.$eval('.faq details', d => d.open);
|
|
ok(hv.svgs.length === 3 && hv.svgs.every(w => w >= 280) && !hv.dash && hv.nav && hv.foot && hv.wide <= 1 && opened && !cerr.length && !bad.length, label + ' /how: 3 diagrams at readable width, no dashes, nav on, footer link, FAQ opens, no console errors, no failed same-origin requests', { hv, opened, cerr, bad });
|
|
pg.off('console', onC); pg.off('response', onR); }
|
|
await pg.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#ticker .run a', { timeout: 8000 }).catch(() => {});
|
|
ok((await pg.$$eval('#ticker .run a', els => els.length)) > 0 && (await pg.textContent('footer')).includes('TrustClickz') && /Part of the network/.test(await pg.textContent('footer')), label + ': ticker runs; footer has the company line and the network line');
|
|
await pg.goto(BASE + '/owner', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#levels .lvl a[data-go]', { timeout: 8000 }).catch(() => {});
|
|
await pg.waitForFunction(() => [...document.querySelectorAll('a[data-go]')].some(a => /[?&]v=[0-9a-f]{24}/.test(a.href)), null, { timeout: 9000 }).catch(() => {});
|
|
ok(await pg.evaluate(() => [...document.querySelectorAll('a[data-go]')].every(a => /[?&]v=[0-9a-f]{24}/.test(a.href))), label + ': after the dwell the visit verifies and every ad link carries the verified token');
|
|
ok(/LEVEL 1/.test(await pg.textContent('#levels')) && /Join free under @owner/.test(await pg.textContent('#join')), label + ': member page shows level rows and "Join free under @owner"');
|
|
await ctx.addCookies([{ name: 'vab.sid', value: OWN.jar['vab.sid'], url: BASE }]);
|
|
await pg.goto(BASE + '/my', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 }).catch(() => {});
|
|
const mt = await pg.textContent('#dash').catch(() => '');
|
|
ok(/@owner/.test(mt) && /viraladblitz\.com\/owner/.test(mt) && /6 of 6 delivered/.test(mt) && (await pg.inputValue('#fHead')) === 'Headline number own', label + ': My page (signed in): page link, ad form filled, Boost delivery');
|
|
await pg.screenshot({ path: path.join(OUT, label + '-my.png'), fullPage: true });
|
|
await pg.goto(BASE + '/boost', { waitUntil: 'domcontentloaded' }); await pg.waitForFunction(() => /about d/.test(document.getElementById('bPol').textContent), null, { timeout: 8000 }).catch(() => {});
|
|
ok(/about 20\.00 POL at today/.test(await pg.textContent('#bPol')) && !(await pg.isDisabled('#bBuy')), label + ': Boost page shows the live POL price and an open Buy button', await pg.textContent('#bPol'));
|
|
ok(errs.length === 0, label + ': no page errors', errs);
|
|
await ctx.close();
|
|
}
|
|
await browser.close();
|
|
} else console.log('16. (Playwright renders skipped)');
|
|
|
|
await stop();
|
|
console.log('\n' + pass + ' passed, ' + fail + ' failed');
|
|
fs.writeFileSync(path.join(OUT, 'smoke.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n');
|
|
process.exit(fail ? 1 : 0);
|
|
}
|
|
main().catch(e => { console.error('smoke crashed:', e.stack || e.message); fail++; process.exit(1); });
|