Files
vbb/qa/smoke.mjs
T

349 lines
34 KiB
JavaScript

// VBB local smoke test. Boots the app in prototype mode (no DOCSTORE_URL: files in a throwaway data dir under qa/out),
// with a tiny loop (5 places, 3 visitors per shift) so shifts and cycles happen in seconds, then checks the splash,
// verified visitors (bots, early, repeats, the per-IP cap), shifts + a cycle + the reward ledger, posting banners
// (upload, checks, credits), network sign-in, the leaderboard, the admin endpoint, a restart, the VBBShop hooks (sponsor vouchers,
// purchase crediting from a fake chain), and page renders.
// Nothing leaves this machine: the network lookup and the chain are local stand-ins, the link probe is off, no real wallet, no money.
//
// node qa/smoke.mjs (Playwright renders too, if it is 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 zlib from 'node:zlib';
import crypto from 'node:crypto';
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 || 3217), BASE = 'http://127.0.0.1:' + PORT;
const ADMIN = 'smoke-admin-token', SSO_SECRET = crypto.randomBytes(32).toString('hex');
// stand-in for the network member lookup: wallets in NET are network members, everyone else is a stranger
// NETSP: wallet -> that member's network sponsor wallet (the hub's `sponsor` field)
const NET = new Set(); const NETSP = new Map(); const LOOKUP_PORT = PORT + 1;
require('node:http').createServer((q, r) => { const a = (new URL(q.url, 'http://x').searchParams.get('a') || '').toLowerCase();
r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify(NET.has(a) ? { address: a, username: 'net' + a.slice(2, 10), sponsor: NETSP.get(a) || null } : {})); }).listen(LOOKUP_PORT, '127.0.0.1').unref();
// stand-in Polygon JSON-RPC for the purchase watcher: CHAIN.logs are served by block range (or all of them when replayAll is on,
// like a flaky RPC re-sending old logs). Nothing here is a real chain.
const CHAIN = { head: 1, logs: [], replayAll: false }; const CHAIN_PORT = PORT + 2;
const SHOP = '0x00000000000000000000000000000000000B0B05', KEEPER_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d'; // anvil's public test key #1
require('node:http').createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; const j = JSON.parse(b || '{}'); let result = null;
if (j.method === 'eth_blockNumber') result = '0x' + CHAIN.head.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.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, result })); }).listen(CHAIN_PORT, '127.0.0.1').unref();
const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '',
LOOP_SIZE: '5', VISITORS_PER_SHIFT: '3', VIEWS_PER_CYCLE: '150', VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '2', LINK_PROBE: '0', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + (PORT + 1) + '/api/network/member',
NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid',
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' });
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).slice(0, 400) : '')); } };
process.on('exit', () => { try { srv && srv.kill(); } catch (e) {} });
// ---- tiny cookie-jar HTTP client; each client is one "visitor" (its own IP via X-Forwarded-For and its own user agent) ----
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(() => ({}))); }
};
}
function png(w, h, seed) {
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 s = seed || 0; 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; const band = ((x + y + s * 17) >> 4) & 1; raw[o] = band ? 255 : 20 + s * 30; raw[o + 1] = band ? 91 + s * 20 : 30; raw[o + 2] = band ? 46 : 80 + y; }
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 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 < 60; i++) { try { const r = await fetch(BASE + '/api/config'); 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 signed-in member by wallet signature
async function walletMember(o = {}) {
const w = ethers.Wallet.createRandom(); const c = client(); if (!o.stranger) NET.add(w.address.toLowerCase());
if (o.sponsor) NETSP.set(w.address.toLowerCase(), o.sponsor === 'self' ? w.address.toLowerCase() : o.sponsor.toLowerCase());
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 = w.address.toLowerCase(); c.ok = v.ok === true && !!c.jar['vbb.sid'];
return c;
}
async function upload(c, buf) { const r = await c.req('/api/my/upload', { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: buf }); return Object.assign({ _status: r.status }, await r.json()); }
async function postBanner(c, seed, link) { const u = await upload(c, png(125, 125, seed)); return c.json('/api/my/banners', { img: u.img, link: link || 'https://example-member.com/offer?id=' + seed }); }
// one verified visit: ticket, wait, seen
async function visit(c, o = {}) {
const s = await c.json('/api/visit/start', { ref: o.ref || '', src: o.src || '' });
if (!s.ticket) return { counted: false, why: 'no-ticket', start: s };
await sleep(o.wait != null ? o.wait : 2100);
return Object.assign({ start: s }, await c.json('/api/visit/seen', { ticket: s.ticket, visibleMs: o.visibleMs != null ? o.visibleMs : 2100 }));
}
async function main() {
const appBusy = await fetch(BASE).then(() => true, () => false);
if (appBusy) throw new Error('port ' + PORT + ' is already in use; set SMOKE_APP_PORT');
console.log('data dir', DATA);
console.log('1. copy rules (no em dashes, no MetaMask recommendation, no income promises)');
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')]);
ok(texts.every(([, t]) => !/[\u2014\u2013]/.test(t)), 'no em or en dashes in any page or script', 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/i.test(html), 'no income promises in page copy');
ok(/never a subscription/i.test(html), 'packages page says never a subscription');
console.log('2. boot (prototype mode, temp data dir)');
await boot();
const cfg = await (await fetch(BASE + '/api/config')).json();
ok(cfg.loopSize === 5 && cfg.perShift === 3 && cfg.viewsPerCycle === 150 && cfg.visitSeconds === 2, 'config from env', cfg);
ok(fs.readFileSync(path.join(OUT, 'server.log'), 'utf8').includes('files (prototype mode)'), 'server says prototype mode (no DOCSTORE_URL)');
ok(JSON.stringify(cfg.packs) === '[{"credits":10,"usd":3},{"credits":40,"usd":10}]' && cfg.lookUsd === 2 && cfg.freeCreditsPerDay === 1, 'approved defaults: packs 10 for $3 + 40 for $10, look $2, 1 free credit a day', cfg);
ok(cfg.prizes && cfg.prizes.pot === 20 && JSON.stringify(cfg.prizes.visitors) === '[5,3,2]' && JSON.stringify(cfg.prizes.sources) === '[5,3,2]', 'prize pot: $20 floor with no sales, $5/$3/$2 per board', cfg.prizes);
ok(!JSON.stringify(cfg).includes('capUsd') && !JSON.stringify(cfg).includes('"cap'), 'public config never shows the prize cap', cfg);
console.log('3. splash');
const anon = client();
let r = await anon.req('/');
const home = await r.text();
ok(r.status === 200 && /Viral Banner Blitz/.test(home) && /id="loop"/.test(home) && /id="bar"/.test(home), 'GET / serves the splash (loop grid + shift bar)');
ok(!r.headers.get('x-frame-options'), 'splash stays frameable (traffic exchanges)');
ok(/og:image" content="https:\/\/viralbannerblitz\.com\/art\/og-share\.png/.test(home) && /application\/ld\+json/.test(home), 'splash has Open Graph + JSON-LD');
let sp = await anon.json('/api/splash');
ok(sp.loopSize === 5 && sp.perShift === 3 && sp.progress === 0 && sp.loop.length === 0 && sp.waiting === 0, 'empty loop at start', sp);
for (const pth of ['/leaders', '/how', '/packages', '/robots.txt', '/sitemap.xml', '/art/mark.svg', '/assets/vbb.css', '/assets/splash.js']) { r = await anon.req(pth); ok(r.status === 200, 'GET ' + pth + ' 200', r.status); }
r = await anon.req('/my'); ok(r.status === 200 && r.headers.get('x-frame-options') === 'DENY', '/my served, never framed');
r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in');
console.log('4. members: wallet sign-in and network sign-in');
const A = await walletMember();
ok(A.ok, 'wallet signature sign-in sets a session');
let my = await A.json('/api/my');
ok(my.credits === 1 && my.freeToday === true && my.netVerified === true, 'network wallet, first sign-in of the day: one free post credit', my);
const X = await walletMember({ stranger: true }); let mx = await X.json('/api/my');
ok(mx.credits === 0 && mx.netVerified === false && mx.grantedNow === false, 'a wallet the network does not know gets no free credit', mx);
mx = await X.json('/api/my'); ok(mx.credits === 0, 'still none on the next visit', mx);
my = await A.json('/api/my'); ok(my.credits === 1 && my.grantedNow === false, 'no second free credit the same day');
const bad = client(); const w0 = ethers.Wallet.createRandom(), w1 = ethers.Wallet.createRandom();
const ch0 = await bad.json('/api/auth/challenge', { address: w0.address });
const v0 = await bad.json('/api/auth/verify', { address: w0.address, signature: await w1.signMessage(ch0.message) });
ok(v0._status === 400 && !bad.jar['vbb.sid'], 'signature from another wallet is refused');
// network sign-in from InstantAdPay: /sso/start -> (IAP mints a token) -> /sso/in
const L = client(); const lw = ethers.Wallet.createRandom().address.toLowerCase();
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=vbb'), 'network sign-in hops to InstantAdPay', loc);
const st = new URL(loc).searchParams.get('st');
const nsso = require(path.join(APP, 'networksso.js'));
process.env.NETWORK_SSO_SECRET = SSO_SECRET;
const tok = nsso.mint({ iss: 'iap', aud: 'vbb', email: 'leader@example.org', wallet: lw, name: 'smokeleader', st, to: '/my' });
r = await L.req('/sso/in?t=' + encodeURIComponent(tok));
ok(r.status === 302 && r.headers.get('location') === '/my' && !!L.jar['vbb.sid'], 'network token signs the member in', { s: r.status, l: r.headers.get('location') });
r = await L.req('/sso/in?t=' + encodeURIComponent(tok)); ok(!r.headers.get('set-cookie') || !/vbb\.sid=[0-9a-f]{64}/.test(String(r.headers.get('set-cookie'))), 'a network token works only once');
const me = await L.json('/api/me'); ok(me.signedIn && me.username === 'smokeleader' && me.address === lw, 'network member keeps the network username', me);
my = await L.json('/api/my'); ok(my.credits === 1 && my.share === 'https://viralbannerblitz.com/?ref=smokeleader', 'referral link is ?ref=<network username>', my.share);
console.log('5. posting banners (checks + credits)');
let u = await upload(A, png(468, 60)); ok(u._status === 400 && /125x125/.test(u.error), 'a 468x60 upload is refused', u);
u = await upload(A, Buffer.concat([png(125, 125), Buffer.alloc(101 * 1024)])); ok(u._status === 400 && /100 KB/.test(u.error), 'an upload over 100 KB is refused', u);
u = await upload(A, Buffer.from('GIF89a not really')); ok(u._status === 400, 'a broken image is refused');
u = await upload(A, png(250, 250)); ok(u._status === 200 && /^\/u\/[a-z0-9-]+\.png$/.test(u.img), '250x250 (retina) upload accepted', u);
let p = await A.json('/api/my/banners', { img: u.img, link: 'http://plain-http.com/' }); ok(p._status === 400 && /https/.test(p.error), 'http link refused', p);
p = await A.json('/api/my/banners', { img: u.img, link: 'https://bit.ly/abc' }); ok(p._status === 400 && /shortener/.test(p.error), 'shortener link refused', p);
p = await A.json('/api/my/banners', { img: u.img, link: 'https://192.168.1.10/' }); ok(p._status === 400, 'IP-address link refused', p);
p = await A.json('/api/my/banners', { img: 'http://example-member.com/x.png', link: 'https://example-member.com/' }); ok(p._status === 400 && /https/.test(p.error), 'http image address refused', p);
p = await A.json('/api/my/banners', { img: '/u/00000000-aaaaaaaaaaaa.png', link: 'https://example-member.com/' }); ok(p._status === 400, 'someone else\'s (or a missing) upload is refused', p);
const B1 = await postBanner(A, 1, 'https://example-member.com/offer?id=1');
ok(B1.ok && B1.banner.state === 'loop' && B1.credits === 0, 'first banner enters the open loop at once and uses the credit', B1);
p = await postBanner(A, 9); ok(p._status === 400 && /no post credits/i.test(p.error), 'no credits left: post refused', p);
// four more members fill the loop (5 places), a sixth waits
const M = [A]; const banners = [B1.banner.id];
for (let i = 2; i <= 6; i++) { const m = await walletMember(); await m.json('/api/my'); const b = await postBanner(m, i); M.push(m); banners.push(b.banner && b.banner.id); }
sp = await anon.json('/api/splash');
ok(sp.loop.length === 5 && sp.waiting === 1 && sp.queue[0].id === banners[5], 'loop full (5), sixth banner waits at #1', { loop: sp.loop.map(x => x.id), q: sp.queue.map(x => x.id) });
ok(sp.loop[0].id === banners[4] && sp.loop[4].id === banners[0], 'newest at the front, first banner at the back (next out)', sp.loop.map(x => x.id));
my = await M[5].json('/api/my'); ok(my.banners[0].state === 'queued' && my.banners[0].position === 1, 'My Banners shows queued + position', my.banners[0]);
my = await A.json('/api/my'); ok(my.banners[0].state === 'loop' && my.banners[0].place === 5 && my.banners[0].shiftsToRideOut === 1, 'My Banners shows place in the loop', my.banners[0]);
console.log('6. verified unique visitors -> shifts -> a cycle');
const botC = client({ ua: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' });
let s = await botC.json('/api/visit/start', { ref: 'smokeleader' }); ok(!s.ticket, 'bots get no visit ticket');
const early = client(); let vv = await visit(early, { wait: 300 }); ok(!vv.counted && vv.why === 'early', 'a visit sent before the timer does not count', vv);
const v1c = client(); vv = await visit(v1c, { ref: 'smokeleader', src: 'https://www.exchange-one.com/surf' }); ok(vv.counted && vv.progress === 1, 'verified visitor 1 counts (1/3)', vv);
vv = await visit(v1c, { ref: 'smokeleader' }); ok(!vv.counted && (vv.why === 'already' || vv.start.already), 'the same visitor does not count twice in 24 h', vv);
const [v2c, v3c] = [client(), client()];
const [x2, x3] = await Promise.all([visit(v2c, { ref: 'smokeleader', src: 'https://exchange-two.net/' }), visit(v3c, { ref: 'smokeleader', src: 'https://exchange-one.com/other' })]);
ok(x2.counted && x3.counted, 'visitors 2 and 3 count', [x2, x3]);
ok([x2, x3].some(x => x.shifted && x.cycled === banners[0]), 'the third visitor shifts the loop and banner #' + banners[0] + ' cycles', [x2, x3]);
sp = await anon.json('/api/splash');
ok(sp.progress === 0 && sp.waiting === 0 && sp.loop.length === 5 && sp.loop[0].id === banners[5] && !sp.loop.some(t => t.id === banners[0]), 'after the shift: sixth banner at the front, first banner gone, bar reset', { p: sp.progress, loop: sp.loop.map(x => x.id) });
ok(sp.today.shifts === 1 && sp.today.cycles === 1 && sp.today.visits === 3, 'today counters: 1 shift, 1 cycle, 3 visitors', sp.today);
my = await A.json('/api/my');
ok(my.banners[0].state === 'cycled' && my.rewards.length === 1 && my.rewards[0].views === 150 && my.rewards[0].status === 'recorded' && my.rewardViews === 150, 'owner sees the cycle: 150 network views recorded', my.rewards);
// per-IP cap: VISITS_PER_IP_DAY=2 distinct browsers on one connection
const shared = '198.51.100.7';
const sv = [];
for (let i = 0; i < 3; i++) sv.push(client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/' + i }));
const svr = await Promise.all(sv.map(c => visit(c)));
ok(svr.filter(x => x.counted).length === 2 && svr.some(x => x.why === 'ip' || (x.start && x.start.already)), 'only 2 browsers per connection count per day', svr.map(x => [x.counted, x.why]));
// forged X-Forwarded-For prefixes are ignored (rightmost entry = the proxy's)
const forge = client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/forger' });
const fs1 = await forge.req('/api/visit/start', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Forwarded-For': '1.2.3.4, ' + shared }, body: '{}' });
ok((await fs1.json()).already === true, 'a forged X-Forwarded-For entry does not make a new visitor');
sp = await anon.json('/api/splash');
ok(sp.progress === 2 && !sp.held, 'bar at 2/3 after the shared-connection visits', sp.progress);
// bar full with nobody waiting: it holds; the next post shifts at once
vv = await visit(client()); sp = await anon.json('/api/splash');
ok(vv.counted && !vv.shifted && sp.progress === 3 && sp.held === true, 'bar full with an empty queue holds (nothing to push in)', { vv, p: sp.progress, held: sp.held });
const G = await walletMember(); await G.json('/api/my');
const gb = await postBanner(G, 7);
sp = await anon.json('/api/splash');
ok(gb.ok && gb.banner.state === 'loop' && sp.progress === 0 && sp.loop[0].id === gb.banner.id && !sp.loop.some(t => t.id === banners[1]), 'a post while the bar is full shifts at once; banner #' + banners[1] + ' cycles', { gb, loop: sp.loop.map(x => x.id) });
console.log('7. weekly leaderboard');
const lb = await anon.json('/api/leaders');
ok(/^\d{4}-\d{2}-\d{2}$/.test(lb.week), 'week key (Central time Monday)', lb.week);
ok(lb.visitors[0] && lb.visitors[0].name === '@smokeleader' && lb.visitors[0].visitors === 3 && lb.visitors[0].sources === 2, 'top visitors: @smokeleader, 3 visitors, 2 sources', lb.visitors);
ok(lb.sources[0] && lb.sources[0].name === '@smokeleader' && lb.sources[0].sources === 2, 'top sources: @smokeleader with 2 distinct referring sites', lb.sources);
ok(lb.visitors.length === 1, 'visitors with no ref credit nobody', lb.visitors);
my = await L.json('/api/my'); ok(my.week.visitors === 3 && my.week.sources === 2, 'member sees their week (3 visitors, 2 sources)', my.week);
console.log('8. click relay');
r = await anon.req('/go/' + banners[2]); ok(r.status === 302 && r.headers.get('location') === 'https://example-member.com/offer?id=3', '/go/<id> sends to the banner link', r.headers.get('location'));
my = await M[2].json('/api/my'); ok(my.banners[0].clicks === 1, 'the click is counted once', my.banners[0].clicks);
await anon.req('/go/' + banners[2]); my = await M[2].json('/api/my'); ok(my.banners[0].clicks === 1, 'a repeat click within the hour is not counted again');
console.log('9. admin');
r = await anon.req('/api/admin/status'); ok(r.status === 401, 'admin status needs the token');
r = await anon.req('/api/admin/status', { headers: { 'x-admin-token': 'wrong-token-x' } }); ok(r.status === 401, 'a wrong token is refused');
const ad = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(ad.loop && ad.loop.filled === 5 && ad.queue.length === 0 && ad.today.shifts === 2 && ad.today.cycles === 2 && ad.totals.cycles === 2, 'admin status: loop, queue, shifts and cycles today', ad);
ok(ad.config.split.sponsorPct === 30 && ad.config.split.companyPct === 70, 'planned split kept in config: 30% sponsor, 70% company', ad.config.split);
ok(ad.ledger.entries === 2 && ad.ledger.views === 300 && ad.ledger.credited === 0 && ad.ledger.viewsByStatus.recorded === 300, 'admin ledger totals: 2 cycles, 300 views recorded, 0 credited', ad.ledger);
const al = await anon.json('/api/admin/ledger', undefined, { 'x-admin-token': ADMIN });
ok(al.entries.length === 2 && al.entries[0].bannerId === banners[1] && al.members.length === 2, 'admin ledger lists the cycles newest first', al.entries.map(e => e.bannerId));
r = await anon.req('/admin'); ok(r.status === 200 && r.headers.get('x-frame-options') === 'DENY', '/admin page served, never framed');
console.log('10. restart keeps everything (atomic file store)');
const before = await anon.json('/api/splash');
await sleep(1200); // let the debounced save land: on Windows a kill skips the SIGINT flush
await stop(); await boot();
const after = await anon.json('/api/splash');
ok(JSON.stringify(after.loop.map(x => x.id)) === JSON.stringify(before.loop.map(x => x.id)) && after.progress === before.progress && after.totals.cycles === 2, 'loop, bar and totals survive a restart', { before: before.loop.map(x => x.id), after: after.loop.map(x => x.id) });
my = await A.json('/api/my'); ok(my.rewards.length === 1 && my.banners[0].state === 'cycled', 'sessions, banners and rewards survive a restart');
vv = await visit(v1c); ok(!vv.counted, 'the 24-hour visitor check survives a restart', vv);
ok(!fs.readdirSync(DATA).some(f => f.endsWith('.tmp')), 'no leftover temp files in the data dir');
console.log('11. unit: frame check');
const safety = require(path.join(APP, 'safety.js'));
ok(safety.frameVerdict({}) === true && safety.frameVerdict({ 'x-frame-options': 'DENY' }) === false && safety.frameVerdict({ 'content-security-policy': "frame-ancestors 'self'" }) === false && safety.frameVerdict({ 'content-security-policy': 'frame-ancestors *' }) === true, 'frameVerdict reads X-Frame-Options and frame-ancestors');
ok(safety.privateIp('10.1.2.3') && safety.privateIp('127.0.0.1') && safety.privateIp('::1') && safety.privateIp('169.254.1.1') && !safety.privateIp('8.8.8.8'), 'private address check');
console.log('12. VBBShop hooks: sponsor vouchers + purchase crediting (fake chain)');
const shopUnit = require(path.join(APP, 'shop.js')); shopUnit.init({ contractAddress: '', chainRpc: '', chainId: 137 });
ok(!shopUnit.watching() && !shopUnit.voucherOn(), 'without CONTRACT_ADDRESS / CHAIN_RPC the watcher is off; without the key, vouchers are off');
const keeperAddr = new ethers.Wallet(KEEPER_PK).address;
const spW = ethers.Wallet.createRandom().address.toLowerCase();
const V = await walletMember({ sponsor: spW });
let vo = await V.json('/api/my/voucher');
const vt = { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'sponsor', type: 'address' }, { name: 'deadline', type: 'uint256' }] };
const vdom = { name: 'VBBShop', version: '1', chainId: 137, verifyingContract: ethers.getAddress(SHOP) };
ok(vo.voucher && vo.voucher.buyer.toLowerCase() === V.address && vo.voucher.sponsor.toLowerCase() === spW && vo.voucher.contract === ethers.getAddress(SHOP) && vo.voucher.chainId === 137, 'voucher names the member, their network sponsor, the contract and the chain', vo);
ok(vo.voucher && ethers.verifyTypedData(vdom, vt, { buyer: vo.voucher.buyer, sponsor: vo.voucher.sponsor, deadline: vo.voucher.deadline }, vo.voucher.sig) === keeperAddr, 'voucher is an EIP-712 signature by the keeper key');
const nowS = Math.floor(Date.now() / 1000);
ok(vo.voucher && vo.voucher.deadline > nowS + 1700 && vo.voucher.deadline <= nowS + 1801, 'voucher is good for 30 minutes', vo.voucher && vo.voucher.deadline - nowS);
ok(!JSON.stringify(vo).includes(KEEPER_PK.slice(2, 12)), 'the key never appears in the answer');
vo = await A.json('/api/my/voucher'); ok(vo._status === 200 && vo.voucher === null && vo.why === 'no-sponsor', 'no network sponsor known: no voucher', vo);
const SELF = await walletMember({ sponsor: 'self' }); vo = await SELF.json('/api/my/voucher'); ok(vo.voucher === null && vo.why === 'no-sponsor', 'the hub naming the member as their own sponsor: no voucher', vo);
vo = await X.json('/api/my/voucher'); ok(vo.voucher === null, 'a wallet the network does not know: no voucher', vo);
r = await anon.req('/api/my/voucher'); ok(r.status === 401, 'voucher needs sign-in');
// a Purchase log for V: 2 x pack10 = 20 credits
const SHOP_IF = new ethers.Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 credits, uint256 usdCents, uint256 weiPaid, address sponsor, uint256 sponsorPaid)']);
const mkLog = o => { const e = SHOP_IF.encodeEventLog('Purchase', [o.orderId, o.buyer, o.sku, o.qty, o.ref || 0, o.credits, o.usdCents, o.wei, o.sponsor || ethers.ZeroAddress, o.sponsorPaid || 0]);
return { address: o.address || SHOP, topics: e.topics, data: e.data, blockNumber: '0x' + o.block.toString(16), transactionHash: o.tx, logIndex: '0x' + o.logIndex.toString(16), removed: false }; };
const credits0 = (await V.json('/api/my')).credits;
const tx1 = '0x' + 'ab'.repeat(32);
CHAIN.logs.push(mkLog({ orderId: 1, buyer: V.address, sku: 1, qty: 2, credits: 20, usdCents: 600, wei: 70000000000000000000n, sponsor: spW, sponsorPaid: 21000000000000000000n, block: 3, tx: tx1, logIndex: 4 }));
CHAIN.head = 5; await sleep(900);
my = await V.json('/api/my'); ok(my.credits === credits0 + 20, 'a Purchase event credits the pack (2 x 10 credits)', { before: credits0, after: my.credits });
// the same log again: in a later block range, and re-sent on every poll
CHAIN.logs.push(Object.assign({}, CHAIN.logs[0], { blockNumber: '0x7' })); CHAIN.replayAll = true; CHAIN.head = 9; await sleep(900);
my = await V.json('/api/my'); ok(my.credits === credits0 + 20, 'the same txHash:logIndex delivered again credits nothing', my.credits);
// a log from another contract address is ignored; a second real order credits
CHAIN.logs.push(mkLog({ address: '0x000000000000000000000000000000000000dEaD', orderId: 9, buyer: V.address, sku: 2, qty: 1, credits: 40, usdCents: 1000, wei: 1n, block: 10, tx: '0x' + 'cd'.repeat(32), logIndex: 0 }));
CHAIN.logs.push(mkLog({ orderId: 2, buyer: V.address, sku: 2, qty: 1, credits: 40, usdCents: 1000, wei: 118000000000000000000n, sponsor: spW, sponsorPaid: 35400000000000000000n, block: 10, tx: tx1, logIndex: 9 }));
CHAIN.head = 12; await sleep(900);
my = await V.json('/api/my'); ok(my.credits === credits0 + 60, 'another contract log is ignored; a second order (same tx, other log index) credits 40', my.credits);
const ads = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(ads.shop && ads.shop.watching && ads.shop.vouchers && ads.shop.purchases === 2 && ads.shop.creditsSold === 60 && ads.shop.dupes >= 2 && ads.shop.lastBlock === 12 && ads.shop.keeper === keeperAddr && !JSON.stringify(ads).includes(KEEPER_PK.slice(2, 12)), 'admin sees the watcher: 2 purchases, 60 credits, duplicates skipped, no key', ads.shop);
// restart: the dedupe marks survive, the replaying RPC still credits nothing
await sleep(1200); await stop(); await boot(); await sleep(900);
my = await V.json('/api/my'); ok(my.credits === credits0 + 60, 'after a restart the replayed logs still credit nothing', my.credits);
const cfgNow = await (await fetch(BASE + '/api/config')).json(); ok(!JSON.stringify(cfgNow).toLowerCase().includes(SHOP.slice(2).toLowerCase()), 'public config does not offer the contract yet (packages stay coming soon)');
// ---- 13. page renders (Playwright, if installed) ----
if (!process.env.SKIP_UI && fs.existsSync(PW)) {
console.log('13. page renders (Playwright)');
const { chromium } = require(PW);
const browser = await chromium.launch();
const errs = [];
for (const [name, vp] of [['desktop', { width: 1280, height: 900 }], ['phone', { width: 390, height: 844 }]]) {
const ctx = await browser.newContext({ viewport: vp, userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36 SmokeUI-' + name });
const pg = await ctx.newPage(); pg.on('pageerror', e => errs.push(name + ': ' + e.message));
pg.on('console', m => { if (m.type() === 'error' && !/fonts\.g|Failed to load resource/.test(m.text())) errs.push(name + ' console: ' + m.text()); });
await pg.goto(BASE + '/?ref=smokeleader', { waitUntil: 'domcontentloaded' });
await pg.waitForSelector('#loop .tile', { timeout: 8000 });
const tiles = await pg.$$eval('#loop .tile', els => els.length);
ok(tiles === 5, name + ': splash renders 5 loop tiles', tiles);
const wide = await pg.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1);
ok(wide, name + ': no horizontal scroll');
await pg.waitForFunction(() => /Counted|already counted/.test(document.getElementById('visitNote').textContent), null, { timeout: 9000 }).catch(() => {});
const note = await pg.textContent('#visitNote');
ok(/Counted|already counted/.test(note), name + ': the page reports the verified visit', note);
await pg.screenshot({ path: path.join(OUT, 'splash-' + name + '.png'), fullPage: true });
await pg.goto(BASE + '/leaders', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#lbVisitors table', { timeout: 8000 });
ok((await pg.textContent('#lbVisitors')).includes('@smokeleader'), name + ': leaderboard page shows the leader');
await pg.screenshot({ path: path.join(OUT, 'leaders-' + name + '.png'), fullPage: true });
ok(/1st: \$5 in POL/.test(await pg.textContent('#pz')) && /at least \$20, and it grows with sales/.test(await pg.textContent('#prizes')) && !/50/.test(await pg.textContent('#prizes')), name + ': leaderboard page shows the pot, never the cap');
await pg.goto(BASE + '/packages', { waitUntil: 'domcontentloaded' }); await pg.waitForTimeout(400);
const pk = await pg.textContent('#pk');
ok(/10 post credits for \$3/.test(pk) && /40 post credits for \$10/.test(pk) && /\$2 per banner/.test(pk) && /Coming soon/i.test(pk), name + ': packages page shows the planned prices as coming soon', pk.slice(0, 200));
ok(!(await pg.$('#pk button, #pk form')), name + ': no purchase controls on the packages page');
await pg.screenshot({ path: path.join(OUT, 'packages-' + name + '.png'), fullPage: true });
// My Banners, signed in as the network member (cookie copied from the HTTP client)
await ctx.addCookies([{ name: 'vbb.sid', value: L.jar['vbb.sid'], url: BASE }]);
await pg.goto(BASE + '/my', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 });
ok((await pg.inputValue('#share')).endsWith('?ref=smokeleader'), name + ': My Banners shows the share link');
await pg.screenshot({ path: path.join(OUT, 'my-' + name + '.png'), fullPage: true });
await ctx.close();
}
ok(errs.length === 0, 'no page errors', errs);
await browser.close();
} else console.log('13. page renders skipped (SKIP_UI or no Playwright at ' + PW + ')');
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); });