e4a7fa64c1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
349 lines
36 KiB
JavaScript
349 lines
36 KiB
JavaScript
// Banner Line local smoke test. Everything runs on this machine: a throwaway anvil chain, the REAL BannerLine
|
|
// contract (compiled artifacts read from ../contracts/out, nothing written there) with its mock $2000 feed,
|
|
// the app server against that chain, HTTP checks of every API, and Playwright page renders + a full UI gate run.
|
|
// No real network, no real wallet, no real money. Keys used are anvil's public test keys.
|
|
//
|
|
// node qa/smoke.mjs (needs ~/.foundry/bin/anvil.exe and contracts/out built)
|
|
// SKIP_UI=1 node qa/smoke.mjs (API checks only)
|
|
import { spawn } from 'node:child_process';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import zlib from 'node:zlib';
|
|
import os from 'node:os';
|
|
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 ART = path.resolve(APP, '..', 'contracts', 'out');
|
|
const ANVIL = process.env.ANVIL || path.join(os.homedir(), '.foundry', 'bin', 'anvil.exe');
|
|
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
|
const RPC_PORT = Number(process.env.SMOKE_RPC_PORT || 18645), APP_PORT = Number(process.env.SMOKE_APP_PORT || 3111), BASE = 'http://127.0.0.1:' + APP_PORT;
|
|
const ADMIN = 'smoke-admin';
|
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
let pass = 0, fail = 0; const procs = [];
|
|
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 300) : '')); } };
|
|
// stand-in network hub (POST /v1/resolve, signed as bannerline) and stand-in InstantAdPay member lookup (the fallback when the
|
|
// hub is unreachable). HUB.people: {id, username, wallet, sponsorId}; HUB.down makes every hub call fail with 503.
|
|
const HUB = { people: [], down: false, calls: 0, badSig: 0 }; const HUB_PORT = APP_PORT + 7, HUB_SECRET = 'b'.repeat(40);
|
|
const IAPNET = new Map(); const IAP_PORT = APP_PORT + 8;
|
|
const TG = []; const TG_PORT = APP_PORT + 9; // stand-in Telegram Bot API (trust pack 2026-11-14): never the real group
|
|
const hubView = p => p ? { id: p.id, username: p.username, wallet: p.wallet, sponsor: (x => x ? { id: x.id, username: x.username } : null)(HUB.people.find(y => y.id === p.sponsorId)), blocked: false, locked: false } : null;
|
|
function startStandIns() {
|
|
const http = require('node:http'); const crypto = require('node:crypto');
|
|
http.createServer((q, r) => { let b = ''; q.on('data', c => { b += c; }); q.on('end', () => { let j = {}; try { j = JSON.parse(b || '{}'); } catch (e) {}
|
|
TG.push({ method: q.url.split('/').pop(), token: q.url.split('/')[1], body: j }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); }); }).listen(TG_PORT, '127.0.0.1');
|
|
http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c;
|
|
r.setHeader('Content-Type', 'application/json');
|
|
// the real hub serves the footer's network list publicly, unsigned (GET /v1/network-sites)
|
|
if (q.method === 'GET' && q.url === '/v1/network-sites') return r.end(JSON.stringify([{ id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' }, { id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' },
|
|
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' }, { id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' }, { id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
|
|
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }, { id: 'newsite', name: 'Hub Test Site', url: 'https://example.org' }]));
|
|
HUB.calls++;
|
|
if (HUB.down) { r.statusCode = 503; return r.end('{"error":"superseded"}'); }
|
|
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'] !== 'bannerline') { HUB.badSig++; r.statusCode = 401; return r.end('{"error":"unauthorized"}'); }
|
|
if (q.url !== '/v1/resolve') { r.statusCode = 404; return r.end('{"error":"not_found"}'); }
|
|
const j = JSON.parse(b || '{}'); const ref = String(j.ref || '').toLowerCase();
|
|
const p = j.id ? HUB.people.find(x => x.id === j.id) : j.wallet ? HUB.people.find(x => x.wallet === String(j.wallet).toLowerCase()) : ref ? HUB.people.find(x => x.username === ref || x.wallet === ref) : null;
|
|
r.end(JSON.stringify({ person: hubView(p) })); }).listen(HUB_PORT, '127.0.0.1').unref();
|
|
http.createServer((q, r) => { const u = new URL(q.url, 'http://x'); const un = (u.searchParams.get('u') || '').toLowerCase(), a = (u.searchParams.get('a') || '').toLowerCase();
|
|
const hit = [...IAPNET].find(([n, w]) => n === un || w === a); r.setHeader('Content-Type', 'application/json');
|
|
r.end(JSON.stringify(hit ? { address: hit[1], username: hit[0] } : {})); }).listen(IAP_PORT, '127.0.0.1').unref();
|
|
}
|
|
function cleanup() { for (const p of procs) { try { p.kill(); } catch (e) {} } }
|
|
process.on('exit', cleanup);
|
|
|
|
// ---- tiny cookie-jar HTTP client ----
|
|
function client(ua) {
|
|
const jar = {};
|
|
return {
|
|
jar,
|
|
async req(p, opts = {}) {
|
|
const headers = Object.assign({ 'User-Agent': ua || 'Mozilla/5.0 smoke', Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, opts.headers || {});
|
|
const r = await fetch(BASE + p, { method: opts.method || 'GET', headers, body: opts.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, extraHeaders) { const r = await this.req(p, body === undefined ? { headers: extraHeaders } : { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extraHeaders), body: JSON.stringify(body) }); return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); }
|
|
};
|
|
}
|
|
function png(w, h) {
|
|
const crcT = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
|
|
const crc = b => { let c = 0xffffffff; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
|
|
const chunk = (t, d) => { const len = Buffer.alloc(4); len.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };
|
|
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
|
|
const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const o = y * (w * 3 + 1) + 1 + x * 3; raw[o] = 40 + x % 200; raw[o + 1] = 120; raw[o + 2] = 90 + y * 2; }
|
|
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
|
|
}
|
|
|
|
async function main() {
|
|
// ---- 1. chain ----
|
|
console.log('1. anvil + contract');
|
|
// never talk to someone else's node: the port must be free before our anvil starts
|
|
const busy = await fetch('http://127.0.0.1:' + RPC_PORT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}' }).then(() => true, () => false);
|
|
if (busy) throw new Error('port ' + RPC_PORT + ' is already in use; set SMOKE_RPC_PORT');
|
|
const appBusy = await fetch('http://127.0.0.1:' + APP_PORT).then(() => true, () => false);
|
|
if (appBusy) throw new Error('port ' + APP_PORT + ' is already in use; set SMOKE_APP_PORT');
|
|
const anvil = spawn(ANVIL, ['--port', String(RPC_PORT), '--silent'], { stdio: 'ignore' }); procs.push(anvil);
|
|
const provider = new ethers.JsonRpcProvider('http://127.0.0.1:' + RPC_PORT, 31337, { staticNetwork: true, pollingInterval: 200 });
|
|
for (let i = 0; i < 50; i++) { try { await provider.getBlockNumber(); break; } catch (e) { await sleep(200); } }
|
|
const W = Array.from({ length: 10 }, (_, i) => new ethers.NonceManager(ethers.HDNodeWallet.fromPhrase('test test test test test test test test test test test junk', undefined, "m/44'/60'/0'/0/" + i).connect(provider)));
|
|
const addr = await Promise.all(W.map(w => w.getAddress()));
|
|
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
|
|
const feedA = art('MockV3Aggregator'), lineA = art('BannerLine');
|
|
const feed = await (await new ethers.ContractFactory(feedA.abi, feedA.bytecode.object, W[0]).deploy(200000000000n)).waitForDeployment();
|
|
const deployBlock = await provider.getBlockNumber();
|
|
const line = await (await new ethers.ContractFactory(lineA.abi, lineA.bytecode.object, W[0]).deploy(addr[8], addr[9], addr[7], await feed.getAddress())).waitForDeployment();
|
|
const CA = await line.getAddress();
|
|
const q = await line.quoteWei(); ok(q === 2500000000000000n, 'quoteWei = 0.0025 POL at $2000', q.toString());
|
|
const send = q + q / 100n;
|
|
const [A, B, Cc, D, E, F] = [1, 2, 3, 4, 5, 6];
|
|
const buy = async (i, sponsor) => (await line.connect(W[i]).buy(sponsor, { value: send })).wait();
|
|
await buy(A, ethers.ZeroAddress); await buy(B, addr[A]); await buy(Cc, addr[B]); await buy(D, addr[B]);
|
|
await (await line.connect(W[F]).buyFor(addr[E], addr[A], { value: send })).wait();
|
|
await buy(A, ethers.ZeroAddress); await buy(0, ethers.ZeroAddress); // no-sponsor buys feed the momentum fund enough for one keeper buy
|
|
ok(Number(await line.spotCount()) === 7, '7 spots bought on anvil');
|
|
const paidTo = async a => (await line.queryFilter(line.filters.Paid(null, a), deployBlock)).reduce((t, e) => t + e.args.amount, 0n);
|
|
|
|
// ---- 2. server ----
|
|
console.log('2. server');
|
|
const DATA = path.join(OUT, 'data-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
|
|
// house list for tests: reserved example domains only, so no real site sees test traffic
|
|
fs.writeFileSync(path.join(DATA, 'house.json'), JSON.stringify([{ key: 'one', title: 'Test house 1', img: '/art/house-iap.svg', link: 'https://example.com/' }, { key: 'two', title: 'Test house 2', img: '/art/house-linkspin.svg', link: 'https://example.net/' }]));
|
|
const env = Object.assign({}, process.env, { PORT: String(APP_PORT), DATA_DIR: DATA, CHAIN_ID: '31337', RPC_URLS: 'http://127.0.0.1:' + RPC_PORT, CONTRACT_ADDRESS: CA,
|
|
DEPLOY_BLOCK: String(deployBlock), POLL_MS: '1000', ADMIN_TOKEN: ADMIN, KEEPER_ENABLED: '1', KEEPER_KEY: W[7].signer.privateKey, KEEPER_STALL_HOURS: '0.01', KEEPER_EVERY_MIN: '0.25', NODE_ENV: 'development',
|
|
HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'bannerline', HUB_ENABLED: '0', HUB_DOWN_MS: '400', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + IAP_PORT + '/api/network/member',
|
|
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT });
|
|
startStandIns();
|
|
const hid = n => 'h_' + String(n).padStart(16, '0');
|
|
const ZW = ethers.Wallet.createRandom().address.toLowerCase(); // a network member with no spot here
|
|
HUB.people.push({ id: hid(1), username: 'alpha', wallet: addr[A].toLowerCase(), sponsorId: null }, { id: hid(2), username: 'beta', wallet: addr[B].toLowerCase(), sponsorId: hid(1) },
|
|
{ id: hid(3), username: 'zed', wallet: ZW, sponsorId: hid(2) }, { id: hid(4), username: 'zeta', wallet: null, sponsorId: null });
|
|
IAPNET.set('iaponly', addr[Cc].toLowerCase()); IAPNET.set('iapfallback', addr[D].toLowerCase());
|
|
const srv = spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] }); procs.push(srv);
|
|
const log = fs.createWriteStream(path.join(OUT, 'server.log')); srv.stdout.pipe(log); srv.stderr.pipe(log);
|
|
const u = client();
|
|
for (let i = 0; i < 60; i++) { try { const s = await u.json('/api/stats'); if (s.totals && s.totals.spots >= 7) break; } catch (e) {} await sleep(300); }
|
|
const st = await u.json('/api/stats');
|
|
ok(st.totals && st.totals.spots === 7, 'index parsed 7 SpotBought', st.totals);
|
|
ok(st.totals && st.totals.members === 6, 'index parsed 6 MemberJoined (payer of a buyFor is not a member)', st.totals);
|
|
ok(BigInt(st.totals.paidInWei) === 7n * q, 'paid in = 7 x quote (refunds excluded)', st.totals.paidInWei);
|
|
const cfg = await u.json('/api/config'); ok(cfg.ready && cfg.sel.buy === '0xf088d547', '/api/config has contract + selectors');
|
|
const qq = await u.json('/api/quote'); ok(qq.wei === q.toString() && qq.source === 'contract.quoteWei', '/api/quote reads quoteWei()', qq);
|
|
for (const p of ['/', '/board', '/join', '/my', '/how', '/assets/site.css', '/art/house-line.svg']) { const r = await u.req(p); ok(r.status === 200, 'GET ' + p + ' 200'); }
|
|
const r404 = await u.req('/nope'); ok(r404.status === 404, 'unknown path 404');
|
|
// trust pack (2026-11-14): legal pages + the network list from the hub
|
|
for (const p of ['/terms', '/disclaimer', '/privacy']) { const r = await u.req(p); const h = await r.text();
|
|
ok(r.status === 200 && h.includes('TrustClickz, 615 Green Valley Drive, Moody, AL 35004') && !h.includes('—') && !/at most 10 times|\$2\.75/.test(h), 'GET ' + p + ' 200 (TrustClickz, no em dash, no cap)'); }
|
|
{ const legal = (await (await u.req('/terms')).text()) + (await (await u.req('/disclaimer')).text()) + (await (await u.req('/privacy')).text());
|
|
ok(/300 guaranteed views/.test(legal) && /ever billed again/.test(legal) && /final once confirmed/.test(legal) && /momentum fund/.test(legal) && /network hub/.test(legal) && /not an investment/.test(legal), 'legal pages state the real mechanics (advertising, one-time, no refunds on-chain, momentum fund, the hub)'); }
|
|
{ let ns; for (let i = 0; i < 20; i++) { ns = await (await u.req('/api/network-sites')).json(); if (Array.isArray(ns) && ns.length === 7) break; await sleep(150); }
|
|
ok(Array.isArray(ns) && ns.length === 7 && ns[6].name === 'Hub Test Site', '/api/network-sites serves the hub list (a site added on the hub shows up)', ns && ns.map(x => x.name)); }
|
|
// promo kit (2026-11-14): one public feed read by /promote and by InstantAdPay's promo center
|
|
{
|
|
const kr = await u.req('/api/promo-kit?u=alpha'); const k = await kr.json();
|
|
ok(kr.status === 200 && kr.headers.get('access-control-allow-origin') === '*', 'promo kit: GET /api/promo-kit 200 with CORS open', kr.status);
|
|
ok(k.username === 'alpha' && k.links.length === 3 && k.links.every(l => l.url.startsWith('https://downlinebanners.com/') && l.url.endsWith('?ref=alpha')), 'promo kit: every link carries ?ref=<username>', k.links);
|
|
ok(k.links.every(l => /^https:\/\/linkspin\.app\/r\/nwdlb\?src=dlb&s1=alpha(&s2=[a-z]+)?$/.test(l.tracked)) && k.links[0].tracked.indexOf('&s2=') < 0 && /&s2=how$/.test(k.links[1].tracked), 'promo kit: every link has a LinkSpin-tracked twin (network link nwdlb, source dlb, the member as s1, the page as s2)', k.links.map(l => l.tracked));
|
|
ok(k.lines.length === 5 && k.headlines.length === 3 && k.posts.length === 2 && k.email && k.email.body.includes('?ref=alpha'), 'promo kit: 5 lines, 3 headlines, 1 email, 2 posts, link filled in');
|
|
const words = JSON.stringify([k.lines, k.headlines, k.email, k.posts, k.note, k.tagline]);
|
|
ok(!/[—–]/.test(words) && !/passive income|guaranteed (income|returns|profit|earnings)|earn (cash|money)|make money/i.test(words) && /300 guaranteed views/.test(words) && /30%/.test(words) && /5\.5%/.test(words), 'promo kit copy: no dashes, no income promises, facts match the contract (300 views, 30%, 5.5%)');
|
|
ok(k.creatives.length === 21 && new Set(k.creatives.map(c => c.angle)).size === 3, 'promo kit: 21 creatives in 3 angles', k.creatives.length);
|
|
const badName = k.creatives.filter(c => /\d{2,4}x\d{2,4}|banner|[-_/]ads?[-_./]/i.test(c.url.replace('https://downlinebanners.com', '')));
|
|
ok(badName.length === 0, 'promo kit: creative paths are ad-blocker neutral', badName.map(c => c.url));
|
|
const bad = [];
|
|
for (const c of k.creatives) {
|
|
const rr = await u.req(new URL(c.url).pathname); const buf = Buffer.from(await rr.arrayBuffer());
|
|
if (rr.status !== 200 || rr.headers.get('content-type') !== 'image/png' || buf.readUInt32BE(16) !== c.w || buf.readUInt32BE(20) !== c.h) bad.push(c.key + ' ' + rr.status);
|
|
if (!c.html.includes('href="https://downlinebanners.com/?ref=alpha"')) bad.push(c.key + ' html');
|
|
}
|
|
ok(bad.length === 0, 'promo kit: every creative served as PNG at its exact size, HTML links to the member', bad);
|
|
ok((await u.req('/art/kit/../server.js')).status !== 200 && (await u.req('/art/kit/nope.png')).status === 404, 'promo kit: /art/kit serves kit files only');
|
|
const k2 = await (await u.req('/api/promo-kit?u=' + encodeURIComponent('<b>'))).json();
|
|
ok(k2.username === null && k2.links[0].url === 'https://downlinebanners.com/', 'promo kit: a bad username is ignored', k2.links[0]);
|
|
const pr = await u.req('/promote'); const ph = await pr.text(); ok(pr.status === 200 && /id="kit"/.test(ph), 'GET /promote serves the Promote page');
|
|
ok((await (await u.req('/sitemap.xml')).text()).includes('/promote'), 'sitemap lists /promote');
|
|
}
|
|
const myHdr = await u.req('/my'); ok(myHdr.headers.get('x-frame-options') === 'DENY' && !(await u.req('/')).headers.get('x-frame-options'), '/my not frameable, / frameable');
|
|
|
|
// ---- 3. gate (HTTP) ----
|
|
console.log('3. gate over HTTP (about 50 s of timers)');
|
|
const v = client(); await v.req('/?ref=' + addr[B]);
|
|
ok(!!v.jar['bl.ref'], 'ref cookie set from ?ref=');
|
|
const g = await v.json('/api/gate');
|
|
ok(!g.passed && g.steps && g.steps[0].role === 'sponsor', 'gate starts with the sponsor spot', g.steps && g.steps.map(s => s.role || s.type));
|
|
ok(g.steps && g.steps[1].type === 'board' && g.steps.filter(s => s.role === 'newest').length === 3, 'board step then 3 newest spots');
|
|
const early = await v.json('/api/gate/done', { gid: g.gid, i: 0 }); ok(early._status === 400, 'done before begin is refused');
|
|
let passedGate = false;
|
|
for (let i = 0; i < g.steps.length; i++) {
|
|
const s = g.steps[i];
|
|
await v.json('/api/gate/begin', { gid: g.gid, i });
|
|
if (s.type === 'visit') { const r = await v.req(s.open + '?g=' + g.gid + '&i=' + i); ok(r.status === 302, 'step ' + i + ' visit relays (302 to ' + r.headers.get('location') + ')'); }
|
|
if (i === 0) { const tooSoon = await v.json('/api/gate/done', { gid: g.gid, i }); ok(tooSoon._status === 400, 'done before the timer is refused'); }
|
|
await sleep(s.seconds * 1000);
|
|
const d = await v.json('/api/gate/done', { gid: g.gid, i });
|
|
if (d.passed) passedGate = true; else if (d.error) ok(false, 'step ' + i + ' done', d);
|
|
}
|
|
ok(passedGate && !!v.jar['bl.pass'], 'gate passed, pass cookie set');
|
|
ok((await v.json('/api/gate')).passed === true, 'gate reports passed on return');
|
|
const st2 = await u.json('/api/stats'); const day = Object.values(st2.daily || {}).pop() || {};
|
|
ok(day.views_gate >= 7 && day.clicks_gate >= 4, 'gate views + gate clicks stored apart', day);
|
|
const bot = client('Googlebot/2.1'); ok((await bot.json('/api/gate')).passed === true, 'bots skip the gate');
|
|
|
|
// ---- 4. organic board view ----
|
|
const bd = await v.json('/api/board'); ok(bd.tiles && bd.tiles.filter(t => t.t === 'spot').length >= 7 && bd.tiles[0].id > bd.tiles[1].id && bd.tiles.some(t => t.t === 'house'), 'board: all spots newest first + house fill', bd.tiles && bd.tiles.map(t => t.id || t.key));
|
|
const fast = await v.json('/api/board/seen', { token: bd.token }); ok(fast.counted === 0, 'board view before 5 s not counted');
|
|
const bd2 = await v.json('/api/board'); await sleep(5000);
|
|
const gateIds = new Set(g.steps[1].tiles.filter(t => t.t === 'spot').map(t => t.id)); const fresh = bd2.tiles.filter(t => t.t === 'spot' && !gateIds.has(t.id)).length; // a keeper spot may be new
|
|
const seen = await v.json('/api/board/seen', { token: bd2.token }); ok(seen.counted === fresh, 'same visitor within the hour: views not double counted', [seen, fresh]);
|
|
const v2 = client('Mozilla/5.0 other'); const bd3 = await v2.json('/api/board'); await sleep(5000);
|
|
const seen3 = await v2.json('/api/board/seen', { token: bd3.token }); ok(seen3.counted === bd3.tiles.filter(t => t.t === 'spot').length && seen3.counted > 0, 'new visitor organic views counted', seen3);
|
|
ok((await v2.json('/api/board/seen', { token: bd3.token })).counted === 0, 'board token is one-time');
|
|
|
|
// ---- 5. sign in + My Spots ----
|
|
console.log('5. sign-in + My Spots');
|
|
const m = client();
|
|
const ch = await m.json('/api/auth/challenge', { address: addr[A] });
|
|
const sig = await W[A].signer.signMessage(ch.message);
|
|
const bad = await m.json('/api/auth/verify', { address: addr[A], signature: await W[B].signer.signMessage(ch.message) }); ok(bad._status === 400, 'signature from another wallet refused');
|
|
const ch2 = await m.json('/api/auth/challenge', { address: addr[A] });
|
|
const ver = await m.json('/api/auth/verify', { address: addr[A], signature: await W[A].signer.signMessage(ch2.message) });
|
|
ok(ver.ok && !!m.jar['bl.sid'], 'wallet signature sign-in sets session', ver);
|
|
const my = await m.json('/api/my');
|
|
ok(my.spots && my.spots.length >= 2, 'A owns 2+ spots', my.spots && my.spots.length);
|
|
let my2 = my, onChain = await paidTo(addr[A]);
|
|
if (BigInt(my2.paidOutWei) !== onChain) { await sleep(2500); my2 = await m.json('/api/my'); onChain = await paidTo(addr[A]); } // a keeper buy may land in between
|
|
ok(BigInt(my2.paidOutWei) === onChain && onChain > 0n, 'A paid out matches Paid events on chain (' + ethers.formatEther(onChain) + ' POL)', my2.paidOutWei);
|
|
ok(BigInt(my.paidInWei) === 2n * q, 'A paid in = 2 spots', my.paidInWei);
|
|
ok(my.directs && my.directs.length === 2 && my.directs.some(x => x.address === addr[B].toLowerCase()), 'A directs = B and E (buyFor sponsor)', my.directs);
|
|
ok(my.share.endsWith('?ref=alpha'), 'share link uses the network username the hub has for the wallet', my.share);
|
|
const sid = my.spots[my.spots.length - 1].id;
|
|
ok((await m.json('/api/my/spot/' + sid, { link: 'http://example.org/' }))._status === 400, 'http link refused');
|
|
ok((await m.json('/api/my/spot/' + sid, { link: 'https://192.168.1.1/' }))._status === 400, 'IP link refused');
|
|
ok((await m.json('/api/my/spot/' + sid, { link: 'https://bit.ly/x' }))._status === 400, 'shortener refused');
|
|
ok((await m.json('/api/my/spot/' + sid, { link: 'javascript:alert(1)' }))._status === 400, 'javascript: refused');
|
|
ok((await m.json('/api/my/spot/' + sid, { link: 'https://example.org/landing' })).ok, 'https link saved');
|
|
const otherSpot = (await u.json('/api/stats')).recent.find(s => s.owner === addr[B].toLowerCase());
|
|
ok((await m.json('/api/my/spot/' + otherSpot.id, { link: 'https://example.org/' }))._status === 403, 'cannot edit someone else\'s spot');
|
|
const up = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(468, 60) })).json();
|
|
ok(up.ok && /^\/art\/u\//.test(up.img), 'PNG 468x60 upload saved', up);
|
|
ok((await m.req(up.img)).status === 200, 'uploaded image served');
|
|
const upBad = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(300, 250) })).json();
|
|
ok(!!upBad.error, 'wrong size refused', upBad);
|
|
const upBig = await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: Buffer.concat([png(468, 60), Buffer.alloc(160 * 1024)]) });
|
|
ok(upBig.status === 400, 'over 150 KB refused');
|
|
ok((await m.json('/api/my/default', { link: 'https://example.org/default' })).ok, 'default link saved');
|
|
const bd4 = await v.json('/api/board'); const t = bd4.tiles.find(x => x.id === sid);
|
|
ok(t && t.img === up.img, 'board shows the uploaded image for that spot');
|
|
const go = await v.req('/go/' + sid); ok(go.headers.get('location') === 'https://example.org/landing', 'click relay goes to the member link');
|
|
|
|
// ---- 5b. network hub lookups (Marty 2026-11-14: everything through the hub; InstantAdPay only when the hub is unreachable) ----
|
|
console.log('5b. network hub lookups');
|
|
const nb = [1, 2, 3].map(() => ethers.Wallet.createRandom().address.toLowerCase());
|
|
HUB.people.push({ id: hid(11), username: 'newone', wallet: nb[0], sponsorId: hid(1) }, { id: hid(12), username: 'newtwo', wallet: nb[1], sponsorId: hid(3) }, { id: hid(13), username: 'newthree', wallet: nb[2], sponsorId: hid(4) });
|
|
ok((await m.json('/api/my')).username === 'alpha', 'My Spots shows the network username the hub has for the wallet');
|
|
let sp = await u.json('/api/sponsor?ref=alpha'); ok(sp.address === addr[A].toLowerCase() && sp.member, '?ref=<username> resolves through the hub', sp);
|
|
sp = await u.json('/api/sponsor?ref=iaponly'); ok(sp.address === null, 'a username only InstantAdPay knows: unknown while the hub answers', sp);
|
|
const rv = client(); await rv.req('/?ref=' + addr[Cc]);
|
|
sp = await rv.json('/api/sponsor?for=' + nb[0]); ok(sp.address === addr[A].toLowerCase() && sp.via === 'hub', 'buyer the hub knows: the hub network sponsor (resolved to a wallet by hub id) beats the ?ref= cookie', sp);
|
|
sp = await rv.json('/api/sponsor?for=' + nb[1]); ok(sp.address === addr[B].toLowerCase() && sp.via === 'hub', 'network sponsor without a spot here: the next one up the network line who has one', sp);
|
|
sp = await rv.json('/api/sponsor?for=' + nb[2]); ok(sp.address === null && sp.via === 'hub', 'network sponsor with no wallet and nobody above: no sponsor (never the ?ref= cookie, never the company)', sp);
|
|
sp = await rv.json('/api/sponsor?for=' + ethers.Wallet.createRandom().address); ok(sp.address === addr[Cc].toLowerCase() && sp.via === 'ref', 'a wallet the hub does not know: the ?ref= cookie as before', sp);
|
|
sp = await rv.json('/api/sponsor?for=' + addr[E]); ok(sp.via === 'ref', 'already a member here: the hub does not pick (the contract keeps the bound sponsor)', sp);
|
|
const wc = 'smokewl0001'; ok((await u.json('/api/admin/welcome', { codes: { [wc]: { line: ['nobodyhere', 'zed', 'beta'] } } }, { 'x-admin-token': ADMIN })).ok, 'welcome code saved');
|
|
const wv = client(); await wv.req('/w/' + wc); sp = await wv.json('/api/sponsor');
|
|
ok(sp.address === addr[B].toLowerCase() && sp.via === 'line', '/w/ welcome line: usernames resolved through the hub, first one with a spot here', sp);
|
|
ok(HUB.badSig === 0 && HUB.calls > 0, 'every hub call is signed as bannerline with HUB_SECRET', HUB);
|
|
// Telegram payment proof (stand-in API): one message per sale, with this week's numbers and an image above the text
|
|
{ const stt = await u.json('/api/stats'); let msgs = []; for (let i = 0; i < 40; i++) { msgs = TG.filter(c => c.method === 'sendMessage'); if (msgs.length >= stt.totals.spots) break; await sleep(250); }
|
|
const txs = msgs.map(c => (String(c.body.text).match(/\/tx\/(0x[0-9a-f]{64})/) || [])[1]);
|
|
ok(msgs.length === stt.totals.spots && new Set(txs).size === msgs.length && txs.every(Boolean), 'one Telegram message per spot sale, never two for the same tx', { msgs: msgs.length, spots: stt.totals.spots });
|
|
ok(msgs.every(c => c.token === 'botstandin-token' && c.body.chat_id === '-100123' && c.body.message_thread_id === 632242 && /This week: \d+ spots? .*\d+ spots in the line/.test(c.body.text)
|
|
&& c.body.link_preview_options && /^https:\/\/[^/]+\/art\/kit\/dlb-(spot|line|instant)-social\.png$/.test(c.body.link_preview_options.url) && c.body.link_preview_options.show_above_text === true && !c.body.text.includes('—')),
|
|
'each message: payments topic, this week\'s spot numbers, a large kit image above the text', msgs[0] && msgs[0].body);
|
|
ok(new Set(msgs.map(c => c.body.link_preview_options && c.body.link_preview_options.url)).size > 1, 'the image rotates between messages'); }
|
|
HUB.down = true;
|
|
sp = await u.json('/api/sponsor?ref=iapfallback'); ok(sp.address === addr[D].toLowerCase(), 'hub unreachable: InstantAdPay answers the username lookup', sp);
|
|
const t0 = Date.now(); sp = await rv.json('/api/sponsor?for=' + ethers.Wallet.createRandom().address); ok(sp.via === 'ref' && Date.now() - t0 < 2000, 'hub unreachable: the sponsor pick falls back at once (no wait on the hub)', [sp, Date.now() - t0]);
|
|
const ah = await u.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
|
|
ok(ah.hubLookup && ah.hubLookup.on && ah.hubLookup.stats.failed >= 1 && !JSON.stringify(ah).includes(HUB_SECRET), 'admin status shows the hub lookup (failures counted, no secret)', ah.hubLookup);
|
|
HUB.down = false; await sleep(500);
|
|
HUB.people.push({ id: hid(21), username: 'later', wallet: addr[Cc].toLowerCase(), sponsorId: null });
|
|
sp = await u.json('/api/sponsor?ref=later'); ok(sp.address === addr[Cc].toLowerCase(), 'the hub answers again after it comes back', sp);
|
|
|
|
// ---- 6. keeper ----
|
|
console.log('6. keeper (stall set to 36 s for the test)');
|
|
const adm = await u.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
|
|
ok(adm.keeper && adm.keeper.enabled && !JSON.stringify(adm).includes(W[7].signer.privateKey.slice(2, 20)), 'keeper on, key never in output');
|
|
let fb = null;
|
|
for (let i = 0; i < 40 && !fb; i++) { const s = await u.json('/api/stats'); fb = (s.recent || []).find(x => x.kind === 2 || x.kind === 3); if (!fb) await sleep(2000); }
|
|
ok(fb && fb.kind === 2 && fb.owner === addr[A].toLowerCase(), 'keeper fundBuy gifted a spot to A (builder, longest wait)', fb);
|
|
const adm2 = await u.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
|
|
ok(adm2.keeper.log.some(e => e.status === 'mined'), 'keeper log shows the mined tx', adm2.keeper.log.slice(0, 3));
|
|
const logTxt = fs.readFileSync(path.join(OUT, 'server.log'), 'utf8');
|
|
ok(!logTxt.includes(W[7].signer.privateKey.slice(2)), 'keeper key not in server log');
|
|
|
|
// ---- 7. pages in a browser ----
|
|
if (!process.env.SKIP_UI) {
|
|
console.log('7. Playwright: page renders + full UI gate');
|
|
const { chromium } = require(PW);
|
|
const browser = await chromium.launch();
|
|
const errors = [];
|
|
const watch = (pg, name) => { pg.on('console', msg => { if (msg.type() === 'error') errors.push(name + ': ' + msg.text() + ' @ ' + ((msg.location() || {}).url || '')); }); pg.on('pageerror', e => errors.push(name + ': ' + e.message)); };
|
|
// member context: signed in, gate skipped
|
|
const ctxM = await browser.newContext(); await ctxM.addCookies([{ name: 'bl.sid', value: m.jar['bl.sid'], url: BASE }]);
|
|
for (const p of ['/', '/board', '/how', '/join', '/my', '/promote', '/terms', '/disclaimer', '/privacy']) {
|
|
const pg = await ctxM.newPage(); watch(pg, 'member ' + p);
|
|
await pg.goto(BASE + p, { waitUntil: 'networkidle' });
|
|
await pg.screenshot({ path: path.join(OUT, 'member' + (p === '/' ? '-home' : p.replace('/', '-')) + '.png'), fullPage: true });
|
|
const foot = await pg.textContent('footer').catch(() => ''); ok(/Part of the Crypto Team Build Network/.test(foot || ''), 'member ' + p + ' renders with footer');
|
|
if (p === '/my') { await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 }).catch(() => {}); ok(await pg.isVisible('#dash'), '/my dashboard visible'); ok((await pg.$$('.spot-ed')).length >= 3, '/my spot editors listed'); }
|
|
if (p === '/promote') { await pg.waitForSelector('#kit .kit-fig img', { timeout: 8000 }).catch(() => {}); const kt = await pg.textContent('#kit'); const who = await pg.inputValue('#whoIn');
|
|
ok(!!who && kt.includes('?ref=' + who) && (await pg.$$('#kit .kit-set:not([hidden]) .kit-fig')).length === 7, '/promote shows the kit with the signed-in member link (' + who + ')'); ok(!!(await pg.$('nav a[href="/promote"]')), 'nav links to Promote');
|
|
await pg.waitForTimeout(500); await pg.screenshot({ path: path.join(OUT, 'member-promote.png'), fullPage: true });
|
|
await pg.setViewportSize({ width: 390, height: 844 }); await pg.waitForTimeout(300); await pg.screenshot({ path: path.join(OUT, 'member-promote-phone.png'), fullPage: true }); }
|
|
if (p === '/join') { await pg.waitForSelector('#buyCard:not([hidden])', { timeout: 8000 }).catch(() => {}); const price = await pg.textContent('#price'); ok(/^0\.0025/.test(price), '/join shows price ' + price); }
|
|
if (p === '/how') { await pg.waitForFunction(() => /Hub Test Site/.test((document.querySelector('footer .netline') || {}).textContent || ''), null, { timeout: 6000 }).catch(() => {});
|
|
const ft = (await pg.textContent('footer')).replace(/\s+/g, ' '); const hrefs = await pg.$$eval('footer a', as => as.map(a => a.getAttribute('href')));
|
|
ok(['/terms', '/disclaimer', '/privacy', '/contract', '/ledger'].every(h => hrefs.includes(h)) && /Support/.test(ft) && /TrustClickz · 615 Green Valley Drive, Moody, AL 35004/.test(ft)
|
|
&& /Part of the network · One account across the network: InstantAdPay · LinkSpin · Downline Banners · Viral Banner Blitz · Stack POL · Earners Corner · Hub Test Site/.test(ft) && !/RM Circle|rmcircle/i.test(ft)
|
|
&& (await pg.textContent('footer .netline .here')) === 'Downline Banners', 'footer: legal + proof links, company line, the hub network list with DLB as current, never RM Circle', ft.slice(-420));
|
|
await pg.locator('footer').screenshot({ path: path.join(OUT, 'footer-desktop.png') });
|
|
await pg.setViewportSize({ width: 390, height: 844 }); await pg.waitForTimeout(200);
|
|
ok(await pg.evaluate(() => document.documentElement.scrollWidth <= 390), 'footer fits a phone (no sideways scroll)'); await pg.locator('footer').screenshot({ path: path.join(OUT, 'footer-phone.png') }); }
|
|
const em = await pg.evaluate(() => document.body.innerText.includes('\u2014')); ok(!em, p + ' has no em dash');
|
|
await pg.close();
|
|
}
|
|
// visitor context: full gate in the UI
|
|
const ctxV = await browser.newContext(); const pg = await ctxV.newPage(); watch(pg, 'visitor /');
|
|
await pg.goto(BASE + '/?ref=' + addr[B], { waitUntil: 'domcontentloaded' });
|
|
await pg.waitForSelector('#gate:not([hidden])');
|
|
for (let i = 0; i < 8; i++) {
|
|
try { await pg.waitForSelector('#gNext:not([hidden])', { timeout: 20000 }); }
|
|
catch (e) { await pg.screenshot({ path: path.join(OUT, 'visitor-gate-stuck.png'), fullPage: true }).catch(() => {}); console.log(' gate stuck at step', i, JSON.stringify(await pg.evaluate(() => ({ what: (document.getElementById('gWhat') || {}).textContent, status: (document.getElementById('status') || {}).textContent })).catch(() => null))); throw e; }
|
|
const label = await pg.textContent('#gNext'); await pg.click('#gNext');
|
|
if (label === 'Continue') break;
|
|
}
|
|
await pg.waitForSelector('#open:not([hidden])', { timeout: 5000 }).catch(() => {});
|
|
ok(await pg.isVisible('#joinBtn'), 'UI gate completes and Join unlocks');
|
|
await pg.screenshot({ path: path.join(OUT, 'visitor-after-gate.png'), fullPage: true });
|
|
const pj = await ctxV.newPage(); watch(pj, 'visitor /join'); await pj.goto(BASE + '/join', { waitUntil: 'networkidle' });
|
|
ok(await pj.isVisible('#buyCard'), 'visitor /join unlocked after gate');
|
|
// fresh visitor: /join is locked
|
|
// visitor = IP + UA, so a fresh visitor needs its own UA
|
|
const ctxL = await browser.newContext({ userAgent: 'Mozilla/5.0 (fresh visitor) Chrome/130' }); const pl = await ctxL.newPage(); watch(pl, 'locked /join'); await pl.goto(BASE + '/join', { waitUntil: 'networkidle' });
|
|
ok(await pl.isVisible('#locked'), 'fresh visitor /join is locked');
|
|
const pm = await ctxL.newPage(); watch(pm, 'signed-out /my'); await pm.goto(BASE + '/my', { waitUntil: 'networkidle' }); ok(await pm.isVisible('#signin'), 'signed-out /my shows sign-in');
|
|
await browser.close();
|
|
// example.com pages inside the gate frame may log their own errors; only ours count
|
|
const ours = errors.filter(e => !/example\.(com|net|org)/.test(e)); // gate frames load example.* sites; their own 404s (favicon) are not ours
|
|
ok(ours.length === 0, 'no console errors on our pages', ours);
|
|
}
|
|
console.log('\n' + pass + ' passed, ' + fail + ' failed. Output in ' + OUT);
|
|
cleanup(); process.exit(fail ? 1 : 0);
|
|
}
|
|
main().catch(e => { console.error(e); cleanup(); process.exit(1); });
|