86a84b9606
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
648 lines
72 KiB
JavaScript
648 lines
72 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, receipts: {} };
|
|
const QUOTE_SEL = ethers.id('quoteWei(uint256,uint256)').slice(0, 10); 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);
|
|
// quoteWei(sku, qty): $ cents x qty at a stand-in POL price of $0.25 (1 cent = 0.04 POL); a receipt for any hash in CHAIN.receipts
|
|
if (j.method === 'eth_call') { const d = j.params[0].data || ''; if (d.startsWith(QUOTE_SEL)) { const sku = Number(BigInt('0x' + d.slice(10, 74))), qty = Number(BigInt('0x' + d.slice(74, 138)));
|
|
const cents = { 1: 300, 2: 1000, 3: 200 }[sku] || 0; result = '0x' + (BigInt(cents * qty) * 4n * 10n ** 16n).toString(16).padStart(64, '0'); } }
|
|
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_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();
|
|
// stand-in network hub: records the signed reports (contract-bind / contract-spend), checks each signature, and answers
|
|
// POST /v1/resolve {wallet | ref | id | email} the way the real hub does for a site without emails. The hub knows every NET wallet
|
|
// (minus HUBSKIP: wallets only InstantAdPay knows), every sponsor wallet in NETSP, HUBONLY wallets, and HUBMAIL emails.
|
|
// HUB.down = every hub call fails with 503 (unreachable).
|
|
const HUB = { got: [], badSig: 0, resolves: 0, down: false }; const HUB_PORT = PORT + 3, HUB_SECRET = 'h'.repeat(40);
|
|
const HUBSKIP = new Set(), HUBONLY = new Set(), HUBMAIL = new Map();
|
|
const hubKnows = w => !!w && ((NET.has(w) && !HUBSKIP.has(w)) || HUBONLY.has(w) || [...NETSP.values()].includes(w));
|
|
const hubId = w => 'h_' + w.slice(2, 18);
|
|
const hubPerson = w => hubKnows(w) ? { id: hubId(w), username: 'net' + w.slice(2, 10), wallet: w, blocked: false,
|
|
sponsor: NETSP.get(w) && hubKnows(NETSP.get(w)) ? { id: hubId(NETSP.get(w)), username: 'net' + NETSP.get(w).slice(2, 10) } : null } : null;
|
|
const hubAll = () => [...new Set([...NET, ...HUBONLY, ...NETSP.values()])].filter(hubKnows);
|
|
require('node:http').createServer(async (q, r) => { let b = ''; for await (const c of q) b += c;
|
|
r.setHeader('Content-Type', 'application/json');
|
|
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'] !== 'vbb') { HUB.badSig++; r.statusCode = 401; return r.end('{}'); }
|
|
if (q.url === '/v1/resolve') { HUB.resolves++; const j = JSON.parse(b || '{}'); const ref = String(j.ref || '').toLowerCase(); let w = null;
|
|
if (j.wallet) w = String(j.wallet).toLowerCase(); else if (j.id) w = hubAll().find(x => hubId(x) === j.id); else if (ref) w = hubAll().find(x => x === ref || 'net' + x.slice(2, 10) === ref);
|
|
else if (j.email && HUBMAIL.has(j.email)) return r.end(JSON.stringify({ person: { id: 'h_' + '9'.repeat(16), username: HUBMAIL.get(j.email), wallet: null, sponsor: null, blocked: false } }));
|
|
return r.end(JSON.stringify({ person: hubPerson(w) })); }
|
|
HUB.got.push({ route: q.url, body: JSON.parse(b) }); r.end(JSON.stringify({ id: 'p' + HUB.got.length })); }).listen(HUB_PORT, '127.0.0.1').unref();
|
|
// stand-in LinkSpin partner API (/api/partner/bl/spins, the Banner Spins call): checks the NETWORK_SSO_SECRET signature and
|
|
// site 'vbb', answers like LinkSpin (account by wallet, else by network username; 125x125 + 250x250 spins only). LSA: wallet ->
|
|
// { username, spins: [{ id, name, code, size, paused, banners }] }; LS.tamper(use) may change a "use" answer (bad size, bad host).
|
|
const LS = { calls: [], badSig: 0, tamper: null }; const LSA = new Map(); const LS_PORT = PORT + 4, LS_HOST = 'rubav-standin.com';
|
|
require('node:http').createServer(async (q, r) => { let b = ''; for await (const c of q) b += c;
|
|
r.setHeader('Content-Type', 'application/json');
|
|
const ts = String(q.headers['x-net-ts'] || ''), want = crypto.createHmac('sha256', SSO_SECRET).update('net.v1.' + ts + '\n' + b).digest('hex');
|
|
if (q.url !== '/api/partner/bl/spins' || q.headers['x-net-sig'] !== want || Math.abs(Date.now() - Number(ts)) > 300000) { LS.badSig++; r.statusCode = 401; return r.end('{"error":"unauthorized"}'); }
|
|
const j = JSON.parse(b || '{}'); LS.calls.push(j);
|
|
let a = LSA.get(j.wallet); if (a && a.byName) a = null;
|
|
if (!a && j.username) a = [...LSA.values()].find(x => x.byName && x.username === j.username);
|
|
if (!a) return r.end('{"account":false}');
|
|
const sp = a.spins.filter(x => j.site === 'vbb' ? ['125x125', '250x250'].includes(x.size) : x.size === '468x60');
|
|
const out = { account: true, username: a.username, host: LS_HOST, spins: sp };
|
|
if (j.spinId != null) {
|
|
const x = sp.find(y => y.id === j.spinId); if (!x) { r.statusCode = 404; return r.end('{"error":"No such 125x125 (or 250x250) Banner Spin on this LinkSpin account."}'); }
|
|
out.use = { spinId: x.id, name: x.name, size: x.size, img: 'https://' + LS_HOST + '/i/' + x.code + '.gif', link: 'https://' + LS_HOST + '/c/' + x.code + '?clickid={clickid}&placement={spot}&s1={type}', otherSource: !!x.otherSource };
|
|
if (LS.tamper) LS.tamper(out.use);
|
|
}
|
|
r.end(JSON.stringify(out)); }).listen(LS_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', LS_PARTNER_URL: 'http://127.0.0.1:' + LS_PORT, LS_SPINS_FIRST_MS: '300', LS_SPINS_EVERY_MS: '700',
|
|
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',
|
|
HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'vbb', HUB_TICK_MS: '300', HUB_DOWN_MS: '400' });
|
|
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 && !o.hubOnly) NET.add(w.address.toLowerCase());
|
|
if (o.hubOnly) HUBONLY.add(w.address.toLowerCase()); if (o.iapOnly) HUBSKIP.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,"sku":1},{"credits":40,"usd":10,"sku":2}]' && cfg.lookUsd === 2 && cfg.lookSku === 3 && 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');
|
|
// promo kit (2026-11-14): one public feed read by /promote and by InstantAdPay's promo center
|
|
{
|
|
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') === '*', 'promo kit: GET /api/promo-kit 200 with CORS open', kr.status);
|
|
ok(k.username === 'smokeleader' && k.links.length === 3 && k.links.every(l => l.url.startsWith('https://viralbannerblitz.com/') && l.url.endsWith('?ref=smokeleader')), 'promo kit: every link carries ?ref=<username>', k.links);
|
|
ok(k.links.every(l => /^https:\/\/linkspin\.app\/r\/nwvbb\?src=vbb&s1=smokeleader(&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 nwvbb, source vbb, 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.subject && k.email.body.includes('?ref=smokeleader'), '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) && !/\$50|passive income|guaranteed (income|returns|profit)|earn (cash|money)|make money/i.test(words) && /at least \$20/.test(words), 'promo kit copy: no dashes, no cap, no income promises, pot shown as at least $20');
|
|
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://viralbannerblitz.com', '')));
|
|
ok(badName.length === 0, 'promo kit: creative paths are ad-blocker neutral (no size tokens, no banner/ad words)', badName.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 || rr.headers.get('content-type') !== 'image/png' || w !== c.w || h !== c.h) { dimOk = false; dimBad.push(c.key + ' ' + rr.status + ' ' + w + 'x' + h); }
|
|
if (!c.html.includes('href="https://viralbannerblitz.com/?ref=smokeleader"')) { dimOk = false; dimBad.push(c.key + ' html'); }
|
|
}
|
|
ok(dimOk, 'promo kit: every creative is served as PNG at its exact size, HTML links to the member', dimBad);
|
|
const k2 = await (await anon.req('/api/promo-kit?u=' + encodeURIComponent('<b>x</b>'))).json();
|
|
ok(k2.username === null && k2.links[0].url === 'https://viralbannerblitz.com/', 'promo kit: a bad username is ignored (plain links)', k2.links[0]);
|
|
r = await anon.req('/promote'); const ph = await r.text();
|
|
ok(r.status === 200 && /id="kit"/.test(ph) && /kitpage\.js/.test(ph), 'GET /promote serves the Promote page');
|
|
r = await anon.req('/no-such-page'); const nf = await r.text();
|
|
ok(r.status === 404 && /Back to the loop/.test(nf), '404 page served');
|
|
ok(/script-src[^;]*https:\/\/linkspin\.app/.test(r.headers.get('content-security-policy') || ''), 'CSP admits linkspin.app (network zones)');
|
|
r = await anon.req('/sitemap.xml'); ok((await r.text()).includes('/promote'), 'sitemap lists /promote');
|
|
}
|
|
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;
|
|
HUBMAIL.set('leader@example.org', 'smokeleader'); // the hub knows this network member by email (wallet not linked there yet)
|
|
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('4b. network hub: membership + sponsors (InstantAdPay only when the hub is unreachable)');
|
|
const HO = await walletMember({ hubOnly: true }); let mh = await HO.json('/api/my');
|
|
ok(mh.netVerified === true && mh.credits === 1, 'a wallet only the hub knows is network-verified: one free credit', mh);
|
|
const IO = await walletMember({ iapOnly: true }); mh = await IO.json('/api/my');
|
|
ok(mh.netVerified === false && mh.credits === 0, 'a wallet only InstantAdPay knows is not verified while the hub answers', mh);
|
|
const L2 = client(); r = await L2.req('/sso/start?mode=go&via=linkspin&to=%2Fmy'); const st2 = new URL(r.headers.get('location') || 'https://x/').searchParams.get('st');
|
|
r = await L2.req('/sso/in?t=' + encodeURIComponent(nsso.mint({ iss: 'linkspin', aud: 'vbb', email: 'nobody@example.org', wallet: ethers.Wallet.createRandom().address.toLowerCase(), name: 'smokenobody', st: st2, to: '/my' })));
|
|
mh = await L2.json('/api/my'); ok(L2.jar['vbb.sid'] && mh.netVerified === false && mh.credits === 0, 'a network sign-in the hub does not know (wallet or email): signed in, no free credit', mh);
|
|
ok(HUB.resolves > 0 && HUB.badSig === 0, 'hub lookups are signed as vbb with HUB_SECRET', HUB);
|
|
HUB.down = true;
|
|
const FB = await walletMember(); mh = await FB.json('/api/my');
|
|
ok(mh.netVerified === true && mh.credits === 1, 'hub unreachable: InstantAdPay verifies the wallet (fallback)', mh);
|
|
const fbSp = ethers.Wallet.createRandom().address.toLowerCase(); const FBV = await walletMember({ sponsor: fbSp }); let vh = await FBV.json('/api/my/voucher');
|
|
ok(vh._status === 200 && vh.voucher === null && vh.why === 'hub-unavailable', 'hub unreachable: no sponsor voucher (never a sponsor the hub did not give)', vh);
|
|
const ah = await anon.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);
|
|
vh = await FBV.json('/api/my/voucher'); ok(vh.voucher && vh.voucher.sponsor.toLowerCase() === fbSp, 'hub back: the voucher names the hub network sponsor, its wallet resolved by hub id', vh);
|
|
|
|
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);
|
|
// the network hub's member lookup (2026-11-14, read-only)
|
|
const ml = await anon.json('/api/admin/member-lookup?q=' + V.address, undefined, { 'x-admin-token': ADMIN });
|
|
ok(ml._status === 200 && ml.known && ml.record && ml.purchases.length === 2 && ml.purchases.every(x => x.tx === tx1) && ml.credits === credits0 + 60 && ml.contract === ethers.getAddress(SHOP), 'admin member lookup by wallet: record, credits, 2 purchases with tx', ml);
|
|
const mls = await anon.json('/api/admin/member-lookup?q=' + spW, undefined, { 'x-admin-token': ADMIN });
|
|
ok(mls._status === 200 && mls.sponsored.length === 2 && !mls.record, 'admin member lookup: the sponsor wallet shows the sales it was paid on', mls);
|
|
r = await anon.req('/api/admin/member-lookup?q=' + V.address, { headers: { 'x-admin-token': 'wrong-token-x' } }); ok(r.status === 401, 'admin member lookup refuses a wrong token');
|
|
// 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(cfgNow.shop && cfgNow.shop.live === true && cfgNow.shop.contract === ethers.getAddress(SHOP), 'public config offers the shop (purchases live)', cfgNow.shop);
|
|
|
|
// ---- 12a. buying: quote, the member's buy() call, the banner look, the teaser ----
|
|
console.log('12a. buying: quote, order, banner look, teaser');
|
|
const BUY_IF = new ethers.Interface(['function buy(uint256 sku, uint256 qty, uint256 ref, address sponsor, uint256 deadline, bytes sig) payable returns (uint256)']);
|
|
let qt = await anon.json('/api/quote?sku=1&qty=1');
|
|
ok(qt._status === 200 && qt.wei === (300n * 4n * 10n ** 16n).toString() && qt.sendWei === (BigInt(qt.wei) + BigInt(qt.wei) / 100n).toString() && qt.usd === 3, 'quote: quoteWei from the contract, +1% to send, $3', qt);
|
|
qt = await anon.json('/api/quote?sku=9&qty=1'); ok(qt._status === 400, 'quote: unknown package refused');
|
|
qt = await anon.json('/api/quote?sku=3&qty=2'); ok(qt._status === 400, 'quote: one banner look at a time');
|
|
r = await anon.req('/api/my/order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"sku":1}' }); ok(r.status === 401, 'order needs sign-in');
|
|
let od = await V.json('/api/my/order', { sku: 2, qty: 1 });
|
|
let dec = od.data ? BUY_IF.decodeFunctionData('buy', od.data) : null;
|
|
ok(od._status === 200 && od.to === ethers.getAddress(SHOP) && od.buyer === V.address && BigInt(od.value) === BigInt(od.sendWei) && od.sponsor === true && dec && Number(dec[0]) === 2 && Number(dec[1]) === 1 && Number(dec[2]) === 0 && dec[3].toLowerCase() === spW,
|
|
'order: buy(2, 1, 0, sponsor, deadline, sig) for the member, with the hub sponsor', od);
|
|
ok(dec && ethers.verifyTypedData(vdom, vt, { buyer: ethers.getAddress(V.address), sponsor: dec[3], deadline: dec[4] }, dec[5]) === keeperAddr, 'order: the voucher inside the call is the keeper\'s EIP-712 signature');
|
|
od = await A.json('/api/my/order', { sku: 1, qty: 1 }); dec = od.data ? BUY_IF.decodeFunctionData('buy', od.data) : null;
|
|
ok(od._status === 200 && od.sponsor === false && od.why === 'no-sponsor' && dec && dec[3] === ethers.ZeroAddress && dec[5] === '0x', 'order: no network sponsor = buy without a voucher (zero sponsor, empty sig)', od);
|
|
od = await V.json('/api/my/order', { sku: 1, qty: 11 }); ok(od._status === 400, 'order: at most 10 packs');
|
|
// banner look: V posts a banner, orders the look for it; a stranger's banner and a cycled banner are refused
|
|
const vb = await postBanner(V, 7); const vbId = vb.banner && vb.banner.id;
|
|
od = await V.json('/api/my/order', { sku: 3, ref: vbId }); dec = od.data ? BUY_IF.decodeFunctionData('buy', od.data) : null;
|
|
ok(od._status === 200 && dec && Number(dec[0]) === 3 && Number(dec[2]) === vbId && od.usd === 2, 'order: banner look = buy(3, 1, banner id)', od);
|
|
od = await A.json('/api/my/order', { sku: 3, ref: vbId }); ok(od._status === 400 && /not yours/.test(od.error), 'order: a look for someone else\'s banner is refused', od);
|
|
r = await V.json('/api/my/banners/' + vbId + '/teaser', { teaser: 'Hello' }); ok(r._status === 400, 'teaser needs the look first', r);
|
|
CHAIN.replayAll = false;
|
|
CHAIN.logs.push(mkLog({ orderId: 3, buyer: V.address, sku: 3, qty: 1, ref: vbId, credits: 0, usdCents: 200, wei: 8n * 10n ** 18n, sponsor: spW, sponsorPaid: 24n * 10n ** 17n, block: 14, tx: '0x' + 'ef'.repeat(32), logIndex: 1 }));
|
|
CHAIN.head = 15; await sleep(900);
|
|
my = await V.json('/api/my'); const lkb = (my.banners || []).find(x => x.id === vbId);
|
|
ok(lkb && lkb.look === true && lkb.teaser === "" && lkb.teaserDefault === "example-member.com", "a banner-look Purchase gives that banner the look", lkb);
|
|
od = await V.json('/api/my/order', { sku: 3, ref: vbId }); ok(od._status === 400 && /already/.test(od.error), 'order: a second look for the same banner is refused', od);
|
|
let spl = await anon.json('/api/splash'); let lt = [...spl.loop, ...spl.queue].find(x => x.id === vbId);
|
|
ok(lt && lt.look === true && lt.teaser === 'example-member.com', 'the loop shows the look, teaser = the link\'s site until the member writes one', lt);
|
|
r = await V.json('/api/my/banners/' + vbId + '/teaser', { teaser: ' Free <b>traffic</b> tools\n inside ' });
|
|
ok(r.ok && r.teaser === 'Free btraffic/b tools inside', 'teaser saved as plain text (no tags, one line)', r);
|
|
r = await V.json('/api/my/banners/' + vbId + '/teaser', { teaser: 'x'.repeat(41) }); ok(r._status === 400, 'teaser: 40 characters at most');
|
|
r = await A.json('/api/my/banners/' + vbId + '/teaser', { teaser: 'mine now' }); ok(r._status === 404, 'teaser: only the owner');
|
|
spl = await anon.json('/api/splash'); lt = [...spl.loop, ...spl.queue].find(x => x.id === vbId); ok(lt && lt.teaser === 'Free btraffic/b tools inside', 'the loop shows the member\'s teaser', lt);
|
|
CHAIN.receipts['0x' + '12'.repeat(32)] = { status: '0x1', blockNumber: '0xe', to: SHOP, from: V.address };
|
|
r = await anon.json('/api/tx/0x' + '12'.repeat(32)); ok(r.found === true && r.status === '0x1', '/api/tx answers a receipt', r);
|
|
r = await anon.json('/api/tx/0x' + '34'.repeat(32)); ok(r.found === false, '/api/tx: not mined yet = found false');
|
|
r = await anon.json('/api/gas'); ok(BigInt(r.maxPriorityFeePerGas || 0) >= 30n * 10n ** 9n, 'gas: at least the 30 gwei Polygon tip floor', r);
|
|
r = await V.json('/api/my/paid', {}); ok(r.ok === true, 'paid nudge answers');
|
|
// this week's pot now counts the sales: 600 + 1000 + 200 cents = $18, 10% = $1.80, so still the $20 floor
|
|
const pzn = await anon.json('/api/prizes'); ok(pzn.current && pzn.current.pot === 20 && pzn.current.atFloor === true && Array.isArray(pzn.past) && pzn.past.length === 0, 'prizes: this week at the $20 floor, no past winners yet', pzn);
|
|
const apz = await anon.json('/api/admin/prizes', undefined, { 'x-admin-token': ADMIN });
|
|
ok(apz.current && apz.current.salesUsd === 18 && apz.current.purchases === 3 && apz.current.shareUsd === 1.8 && apz.current.topUpUsd === 18.2 && apz.prize && apz.prize.keyOn === false, 'admin prizes: week sales $18 from 3 purchases, 10% $1.80, top-up $18.20, no prize key here', apz.current);
|
|
r = await anon.json('/api/admin/prizes/prepare', { week: apz.week }, { 'x-admin-token': ADMIN }); ok(r._status === 400 && /not finished/.test(r.error), 'prizes: the current week cannot be prepared', r);
|
|
r = await anon.json('/api/admin/prizes/pay', { week: apz.lastWeek }, { 'x-admin-token': ADMIN }); ok(r._status === 400 && /confirm/.test(r.error), 'prizes: paying needs {week, confirm: week}', r);
|
|
r = await anon.json('/api/admin/prizes/pay', { week: apz.lastWeek, confirm: apz.lastWeek }, { 'x-admin-token': ADMIN }); ok(r._status === 400 && !r.ok, 'prizes: without a prepared plan with winners (and without PRIZE_KEY) nothing is paid', r);
|
|
r = await anon.json('/api/admin/prizes/pay', { week: apz.lastWeek, confirm: apz.lastWeek }); ok(r._status === 401, 'prizes: paying needs the admin token');
|
|
|
|
// ---- 12b. hub report: each purchase reported once, signed as vbb (first = bind with the sponsor, later = spend) ----
|
|
console.log('12b. hub report');
|
|
await sleep(1200);
|
|
const binds = HUB.got.filter(x => x.route === '/v1/contract-bind'), spends = HUB.got.filter(x => x.route === '/v1/contract-spend');
|
|
ok(HUB.badSig === 0 && binds.length === 1 && binds[0].body.contract === 'viralbannerblitz' && binds[0].body.wallet === V.address && binds[0].body.sponsorRef === spW && binds[0].body.spentCents === 600 && binds[0].body.tx === tx1, 'hub: the first purchase is a signed contract-bind with the sponsor wallet and 600 cents', HUB);
|
|
ok(spends.length === 2 && spends[0].body.wallet === V.address && spends[0].body.cents === 1000 && spends[1].body.cents === 200, 'hub: later purchases are contract-spends (1000 cents, then the 200-cent banner look)', spends);
|
|
const adh = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
|
|
ok(adh.hub && adh.hub.enabled && adh.hub.sent === 3 && adh.hub.site === 'vbb' && !JSON.stringify(adh).includes(HUB_SECRET), 'admin status shows the hub report (3 sent), never the secret', adh.hub);
|
|
|
|
// ---- 12c. old site links + health ----
|
|
console.log('12c. old site links + health');
|
|
r = await anon.req('/health'); let hj = await r.json(); ok(r.status === 200 && hj.ok === true && hj.store === 'files', '/health answers ok (files in the smoke test)', hj);
|
|
r = await anon.json('/api/admin/oldrefs', { oldrefs: { oldguy: 'netguy', 'bad key!': 'x', other: 'bad value!' } }); ok(r._status === 401, 'loading old refs needs the admin token');
|
|
r = await anon.json('/api/admin/oldrefs', { oldrefs: { oldguy: 'netguy', '224411': 'berninisonia80', 'bad key!': 'x', other: 'bad value!' } }, { 'x-admin-token': ADMIN });
|
|
ok(r.ok && r.total === 2 && r.skipped === 2, 'admin loads the old username map, bad rows skipped', r);
|
|
const oloc = async q => { const x = await anon.req(q); return x.status + ' ' + x.headers.get('location'); };
|
|
ok(await oloc('/?oldguy') === '301 /?ref=netguy', '/?<old username> -> /?ref=<network username>');
|
|
ok(await oloc('/?OldGuy&fbclid=abc') === '301 /?ref=netguy', 'old username is case-insensitive and fbclid may follow');
|
|
ok(await oloc('/?224411') === '301 /?ref=berninisonia80', 'a numeric old username maps too');
|
|
ok(await oloc('/splashpg.php?pid=3&r=oldguy') === '301 /?ref=netguy', '/splashpg.php?pid=N&r=<old> -> /?ref=<network>');
|
|
ok(await oloc('/lcp.php?pid=12&r=oldguy') === '301 /?ref=netguy', '/lcp.php?pid=N&r=<old> -> /?ref=<network>');
|
|
ok(await oloc('/?nobodyhere') === '301 /', 'an unknown old username goes home');
|
|
ok(await oloc('/splashpg.php?pid=3&r=nobodyhere') === '301 /', 'an unknown old splash ref goes home');
|
|
ok(await oloc('/members.php') === '301 /' && await oloc('/login.php?x=1') === '301 /', 'any other old *.php page goes home');
|
|
r = await anon.req('/?ref=netguy'); ok(r.status === 200, 'the new ?ref= link is served, not redirected');
|
|
r = await anon.req('/'); ok(r.status === 200, 'the plain home page is served');
|
|
const adr = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN }); ok(adr.oldrefs === 2, 'admin status counts the old refs', adr.oldrefs);
|
|
|
|
// ---- 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');
|
|
await pg.waitForFunction(() => /POL right now/.test(document.getElementById('pk').textContent), null, { timeout: 6000 }).catch(() => {});
|
|
const pkt = await pg.textContent('#pk');
|
|
ok(/10 post credits/.test(pkt) && /\$3/.test(pkt) && /40 post credits/.test(pkt) && /\$10/.test(pkt) && /\$2 per banner/.test(pkt) && /about 12\.00 POL right now/.test(pkt) && /about 40\.00 POL right now/.test(pkt), name + ': packages page shows USD prices and the live POL price', pkt.slice(0, 300));
|
|
const buys = await pg.$$eval('#pk button[data-pk=buy]', els => els.map(b => [b.textContent, b.disabled]));
|
|
ok(buys.length === 2 && buys[0][0] === 'Buy 10 credits' && buys[1][0] === 'Buy 40 credits' && buys.every(b => !b[1]), name + ': two live Buy buttons', buys);
|
|
const soon = (await pg.textContent('main')).match(/coming soon/gi) || [];
|
|
ok(soon.length === 1 && /Tokens[\s\S]*Coming soon/i.test(pkt), name + ': only Tokens still says coming soon', soon.length);
|
|
ok(/SafePal or any other crypto wallet/.test(await pg.textContent('main')) && /Never a subscription/i.test(await pg.textContent('main')), name + ': packages copy: SafePal or any other crypto wallet, never a subscription');
|
|
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 });
|
|
// Promote page, signed in: the kit fills in the member's username
|
|
await pg.goto(BASE + '/promote', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#kit .kit-fig img', { timeout: 8000 });
|
|
ok((await pg.textContent('#kit')).includes('?ref=smokeleader') && (await pg.inputValue('#whoIn')) === 'smokeleader', name + ': Promote page shows the kit with the member links');
|
|
ok(!!(await pg.$('nav a[href="/promote"]')), name + ': nav links to Promote');
|
|
await pg.waitForTimeout(600); await pg.screenshot({ path: path.join(OUT, 'promote-' + name + '.png'), fullPage: true });
|
|
// trust pack (2026-11-14): footer legal + proof links, company line, network line; ledger + contract + legal pages render
|
|
await pg.goto(BASE + '/how', { waitUntil: 'domcontentloaded' }); await pg.waitForFunction(() => /Earners Corner/.test((document.querySelector('footer .netline') || {}).textContent || ''), null, { timeout: 6000 }).catch(() => {});
|
|
const ft = await pg.textContent('footer.foot'); const hrefs = await pg.$$eval('footer.foot 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/.test(ft.replace(/\s+/g, ' ')) && !/RM Circle|rmcircle/i.test(ft)
|
|
&& (await pg.textContent('footer .netline .here')) === 'Viral Banner Blitz', name + ': footer: legal + proof links, company line, network line with VBB as current, never RM Circle', ft.slice(-400));
|
|
const sw = await pg.evaluate(() => document.documentElement.scrollWidth); ok(sw <= pg.viewportSize().width, name + ': footer fits the screen (no sideways scroll)', sw);
|
|
await pg.locator('footer.foot').screenshot({ path: path.join(OUT, 'footer-' + name + '.png') });
|
|
for (const lp of ['/terms', '/disclaimer', '/privacy']) { await pg.goto(BASE + lp, { waitUntil: 'domcontentloaded' }); ok((await pg.textContent('main')).includes('TrustClickz') && !!(await pg.$('footer.foot')), name + ': ' + lp + ' renders with the footer'); }
|
|
await pg.goto(BASE + '/ledger', { waitUntil: 'domcontentloaded' }); await pg.waitForFunction(() => !/Loading/.test(document.querySelector('#rows tbody').textContent), null, { timeout: 8000 }).catch(() => {});
|
|
ok(!!(await pg.$('#totals .stat')) && !/Loading/.test(await pg.textContent('#rows')), name + ': /ledger renders its totals and rows', (await pg.textContent('#rows')).slice(0, 200));
|
|
await pg.screenshot({ path: path.join(OUT, 'ledger-' + name + '.png'), fullPage: true });
|
|
await pg.goto(BASE + '/contract', { waitUntil: 'domcontentloaded' }); await pg.waitForFunction(() => !/Reading the contract/.test(document.getElementById('facts').textContent), null, { timeout: 8000 }).catch(() => {});
|
|
ok(!/Reading the contract/.test(await pg.textContent('#facts')) && /30%/.test(await pg.textContent('main')), name + ': /contract renders', (await pg.textContent('#facts')).slice(0, 200));
|
|
await pg.screenshot({ path: path.join(OUT, 'contract-' + name + '.png'), fullPage: true });
|
|
await pg.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await pg.waitForTimeout(300);
|
|
ok(!(await pg.$('script[src*="linkspin.app/z.js"]')), name + ': no network zone on the loop page');
|
|
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 + ')');
|
|
|
|
// ---- 14. LinkSpin Banner Spins: post one as a banner, and members' spins fill empty space (never loop banners) ----
|
|
console.log('14. LinkSpin Banner Spins (stand-in LinkSpin)');
|
|
{ // unit: the fill picks (Downline Banners dedupe: one per member, no member already on the page, no image twice)
|
|
const lsu = require(path.join(APP, 'lsspins.js'));
|
|
lsu.set([{ owner: '0xa', img: 'https://h.com/i/aaa.gif', link: 'https://h.com/c/aaa', owner_name: 'a' }, { owner: '0xb', img: 'https://h.com/i/bbb.gif', link: 'https://h.com/c/bbb' },
|
|
{ owner: '0xc', img: 'https://h.com/i/bbb.gif', link: 'https://h.com/c/bbb' }, { owner: '0xd', img: 'https://h.com/i/ddd.gif', link: 'https://h.com/c/ddd' }, { owner: '0xe', img: 'https://h.com/i/eee.gif', link: 'https://h.com/c/eee' }]);
|
|
let f = lsu.fill({ openPlaces: 2, queueSlots: 8, pageOwners: ['0xa'], pageImgs: ['https://h.com/i/eee.gif'] }); const all = f.loop.concat(f.queue);
|
|
ok(f.loop.length === 2 && all.length === 2 && all.every(t => t.t === 'spin') && !all.some(t => /aaa|eee/.test(t.img)) && new Set(all.map(t => t.img)).size === all.length,
|
|
'fill: a member on the page and an image on the page are left out, the same image never twice', all.map(t => t.img));
|
|
f = lsu.fill({ openPlaces: 1, queueSlots: 8, pageOwners: [], pageImgs: [] });
|
|
ok(f.loop.length === 1 && f.queue.length === 3, 'fill: open places first, the rest into the empty waiting line (4 different images)', [f.loop.length, f.queue.length]);
|
|
ok(lsu.fill({ openPlaces: 0, queueSlots: 0, pageOwners: [], pageImgs: [] }).loop.length === 0, 'fill: no gap, no fill');
|
|
}
|
|
const SP1 = await walletMember(); await SP1.json('/api/my');
|
|
LSA.set(SP1.address, { username: 'spinner1', spins: [{ id: 11, name: 'Main spin', code: 'qk7spin1', size: '125x125', paused: false, banners: 2 }, { id: 12, name: 'Sharp spin', code: 'qk7spin2', size: '250x250', paused: false, banners: 1 },
|
|
{ id: 13, name: 'Wide spin', code: 'qk7wide1', size: '468x60', paused: false, banners: 3 }, { id: 14, name: 'Resting', code: 'qk7rest1', size: '125x125', paused: true, banners: 1 }] });
|
|
let ls = await SP1.json('/api/my/lsspins');
|
|
ok(ls._status === 200 && ls.account && ls.spins.length === 3 && ls.spins.every(x => ['125x125', '250x250'].includes(x.size)) && !JSON.stringify(ls).includes('qk7'), 'My Banners lists the 125x125 + 250x250 spins only (no codes sent to the browser)', ls);
|
|
ok(LS.badSig === 0 && LS.calls.length > 0 && LS.calls.every(c => c.site === 'vbb'), 'LinkSpin calls are signed with NETWORK_SSO_SECRET and say site vbb', { bad: LS.badSig, n: LS.calls.length });
|
|
const anonLs = await anon.json('/api/my/lsspins'); ok(anonLs._status === 401, 'the spin list needs a sign-in');
|
|
const NOLS = await walletMember(); await NOLS.json('/api/my'); ls = await NOLS.json('/api/my/lsspins');
|
|
ok(ls._status === 200 && ls.account === false, 'no LinkSpin account for this wallet: account false', ls);
|
|
const nc = LS.calls.filter(c => c.wallet === NOLS.address).slice(-1)[0] || {}; ok(nc.username && /^net[0-9a-f]{8}$/.test(nc.username), 'a network-verified member is also looked up by network username', nc);
|
|
// username fallback: LinkSpin knows this member by network username, not by this wallet
|
|
const UN = await walletMember(); await UN.json('/api/my'); LSA.set('0x' + 'f'.repeat(40), { username: 'net' + UN.address.slice(2, 10), byName: true, spins: [{ id: 31, name: 'By name', code: 'qk7name1', size: '125x125', paused: false, banners: 0 }] });
|
|
ls = await UN.json('/api/my/lsspins'); ok(ls.account === true && ls.spins.length === 1, 'LinkSpin finds the account by network username when no account holds the wallet', ls);
|
|
const STR = await walletMember({ stranger: true }); await STR.json('/api/my'); await STR.json('/api/my/lsspins');
|
|
const sc = LS.calls.filter(c => c.wallet === STR.address); ok(sc.length > 0 && sc.every(c => !c.username), 'a member the network does not know is looked up by wallet only', sc.slice(-1));
|
|
// posting a spin: one credit, image + link from LinkSpin, straight into the loop / the line like any banner
|
|
let cr0 = (await SP1.json('/api/my')).credits;
|
|
let ps = await SP1.json('/api/my/banners', { spinId: 13 }); ok(ps._status === 400 && /125x125/.test(ps.error), 'a 468x60 spin cannot be posted', ps);
|
|
ps = await SP1.json('/api/my/banners', { spinId: 99 }); ok(ps._status === 400 && /No such/.test(ps.error), 'an unknown spin is refused with LinkSpin\'s reason', ps);
|
|
LS.tamper = u => { u.size = '468x60'; }; ps = await SP1.json('/api/my/banners', { spinId: 11 }); ok(ps._status === 400 && /125x125/.test(ps.error), 'a wrong size in LinkSpin\'s answer is refused', ps);
|
|
LS.tamper = u => { u.img = 'https://elsewhere-images.com/x.gif'; }; ps = await SP1.json('/api/my/banners', { spinId: 11 }); ok(ps._status === 400, 'an image on another host than the spin link is refused', ps);
|
|
LS.tamper = u => { u.link = 'http://' + LS_HOST + '/c/x'; }; ps = await SP1.json('/api/my/banners', { spinId: 11 }); ok(ps._status === 400, 'a plain http spin link is refused', ps);
|
|
LS.tamper = null;
|
|
ok((await SP1.json('/api/my')).credits === cr0, 'refused spin posts use no credit', cr0);
|
|
ps = await SP1.json('/api/my/banners', { spinId: 11, img: 'https://evil-images.com/x.png', link: 'https://evil-target.com/' });
|
|
ok(ps.ok && ps.credits === cr0 - 1, 'posting a spin uses one credit', ps);
|
|
my = await SP1.json('/api/my'); const sb = my.banners.find(x => x.id === ps.banner.id);
|
|
ok(sb && sb.img === 'https://' + LS_HOST + '/i/qk7spin1.gif' && sb.link.startsWith('https://' + LS_HOST + '/c/qk7spin1?') && sb.spin && sb.spin.name === 'Main spin', 'the banner is the spin: its rotating image + click link (never what the browser sent)', sb);
|
|
ps = await SP1.json('/api/my/banners', { spinId: 12 }); ok(ps._status === 400 && /no post credits/i.test(ps.error), 'no credits left: a spin post is refused too', ps);
|
|
r = await anon.req('/go/' + sb.id); const gl = new URL(r.headers.get('location') || 'https://x/');
|
|
ok(r.status === 302 && gl.hostname === LS_HOST && /^[0-9a-f]{16}$/.test(gl.searchParams.get('clickid') || '') && gl.searchParams.get('placement') === String(sb.id) && ['loop', 'waiting'].includes(gl.searchParams.get('s1')),
|
|
'a click goes through the spin link with {clickid}, {spot} and {type} filled (counts in LinkSpin Reports)', r.headers.get('location'));
|
|
// fill: a bigger loop (restart with 40 places) leaves open places and nobody waiting
|
|
const SP2 = await walletMember(), SP3 = await walletMember(), SP4 = await walletMember(), SP5 = await walletMember();
|
|
for (const m of [SP2, SP3, SP4, SP5]) await m.json('/api/my');
|
|
LSA.set(SP2.address, { username: 'spinner2', spins: [{ id: 21, name: 'Two', code: 'qk7fill2', size: '125x125', paused: false, banners: 1 }] });
|
|
LSA.set(SP3.address, { username: 'spinner3', spins: [{ id: 22, name: 'Three', code: 'qk7fill2', size: '125x125', paused: false, banners: 1 }] }); // same image as SP2
|
|
LSA.set(SP4.address, { username: 'spinner4', spins: [{ id: 23, name: 'Four', code: 'qk7fill4', size: '250x250', paused: false, banners: 2 }] });
|
|
LSA.set(SP5.address, { username: 'spinner5', spins: [{ id: 24, name: 'Paused', code: 'qk7fill5', size: '125x125', paused: true, banners: 1 }] });
|
|
const loopBefore = (await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN }));
|
|
await sleep(1200); ENV.LOOP_SIZE = '40'; await stop(); await boot(); await sleep(1600);
|
|
sp = await anon.json('/api/splash'); const fl = (sp.fill || { loop: [], queue: [] }); const fall = fl.loop.concat(fl.queue);
|
|
ok(sp.loop.length < 39 && sp.waiting === 0, 'restart with 40 places: open places, nobody waiting', { loop: sp.loop.length, waiting: sp.waiting });
|
|
ok(fall.length === 2 && fall.every(t => t.t === 'spin' && t.img.includes(LS_HOST)) && fall.some(t => t.img.includes('qk7fill4')) && fall.some(t => t.img.includes('qk7fill2')),
|
|
'the gaps show members\' spins: one per image (SP2 and SP3 share one), none paused, none for a member with a banner on the page', fall.map(t => t.img + ' ' + t.owner));
|
|
ok(!fall.some(t => t.img.includes('qk7spin1')), 'SP1 has a banner in the loop, so no fill tile for SP1');
|
|
ok(fl.loop.length === 2 && fl.queue.length === 0, 'open loop places are filled first', [fl.loop.length, fl.queue.length]);
|
|
ok(fall.every(t => /\/c\/qk7fill\d\?placement=fill&s1=fill$/.test(t.href)), 'a fill tile clicks straight through the spin link (placement=fill)', fall.map(t => t.href));
|
|
ok(!sp.loop.some(t => fall.some(f => f.img === t.img)), 'fill tiles are not in the loop list');
|
|
let st0 = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
|
|
ok(st0.loop.filled === sp.loop.length && st0.totals.cycles === loopBefore.totals.cycles && st0.lsSpins && st0.lsSpins.fill >= 2, 'fill never changes the loop, its size or the cycles; admin status counts the fill spins', { filled: st0.loop.filled, cyc: [loopBefore.totals.cycles, st0.totals.cycles], ls: st0.lsSpins });
|
|
const sp2 = await anon.json('/api/splash'); ok(JSON.stringify(sp2.fill) === JSON.stringify(sp.fill), 'the same fill on the next poll (no reshuffle every 8 seconds)');
|
|
if (!process.env.SKIP_UI && fs.existsSync(PW)) {
|
|
const { chromium } = require(PW); const browser = await chromium.launch(); const errs = [];
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36 SmokeUI-spin' });
|
|
await ctx.route('https://' + LS_HOST + '/**', rt => rt.fulfill({ status: 200, contentType: 'image/png', body: png(125, 125, 4) })); // nothing leaves this machine
|
|
const pg = await ctx.newPage(); pg.on('pageerror', e => errs.push(e.message));
|
|
await pg.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#loop .tile.fill', { timeout: 8000 }).catch(() => {});
|
|
const ft = await pg.$$eval('#loop .tile.fill', els => els.map(e => [e.querySelector('.pos') && e.querySelector('.pos').textContent, e.getAttribute('href')]));
|
|
ok(ft.length === 2 && ft.every(x => x[0] === 'SPIN' && x[1].includes(LS_HOST)), 'splash: open places show SPIN tiles', ft);
|
|
ok(await pg.isVisible('#fillNote') && /never shift it, never cycle and never earn/.test(await pg.textContent('#fillNote')), 'splash: the note says spins are not loop banners');
|
|
ok((await pg.$$eval('#loop .tile.open', els => els.length)) >= 1 && (await pg.textContent('#loop .tile.open')).includes('post yours'), 'splash: an open place still says "post yours"');
|
|
await pg.screenshot({ path: path.join(OUT, 'splash-spins.png'), fullPage: true });
|
|
await ctx.addCookies([{ name: 'vbb.sid', value: SP4.jar['vbb.sid'], url: BASE }]);
|
|
await pg.goto(BASE + '/my', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 });
|
|
await pg.click('#lsBtn'); await pg.waitForSelector('#lsPick button[data-spin]', { timeout: 8000 }).catch(() => {});
|
|
const bts = await pg.$$eval('#lsPick button[data-spin]', els => els.map(e => e.textContent));
|
|
ok(bts.length === 1 && /Four \(250x250, 2 images\)/.test(bts[0]), 'My Banners: "Use my LinkSpin Banner Spin" lists the spin', bts);
|
|
await pg.screenshot({ path: path.join(OUT, 'my-spins.png'), fullPage: true });
|
|
await pg.click('#lsPick button[data-spin]'); await pg.waitForFunction(() => /Posted\. Your Banner Spin/.test(document.body.textContent), null, { timeout: 8000 }).catch(() => {});
|
|
ok(/Posted\. Your Banner Spin went straight into the loop/.test(await pg.textContent('body')), 'My Banners: one tap posts the spin into the loop');
|
|
await pg.waitForSelector('.pill.spin', { timeout: 8000 }).catch(() => {});
|
|
ok(/LinkSpin Banner Spin: Four/.test(await pg.textContent('#mine')), 'My Banners: the banner shows as a Banner Spin');
|
|
ok(errs.length === 0, 'no page errors (spins)', errs);
|
|
await browser.close();
|
|
}
|
|
|
|
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); });
|