Files
banner-line/qa/smoke.mjs
T
martbost 387997864a Remove street mailing address from public pages (Marty 2026-11-16)
Pages, footers and the site assistant now name only TrustClickz; the footer
reads "(c) 2026 TrustClickz". Contact stays the network support link.
QA checks updated to assert no street address is shown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:52:41 -06:00

528 lines
58 KiB
JavaScript

// Banner Line local smoke test. Everything runs on this machine: a throwaway anvil chain, the REAL BannerLine
// contract (compiled artifacts read from ../contracts/out, nothing written there) with its mock $2000 feed,
// the app server against that chain, HTTP checks of every API, and Playwright page renders + a full UI gate run.
// No real network, no real wallet, no real money. Keys used are anvil's public test keys.
//
// node qa/smoke.mjs (needs ~/.foundry/bin/anvil.exe and contracts/out built)
// SKIP_UI=1 node qa/smoke.mjs (API checks only)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import os from 'node:os';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const { ethers } = require('ethers');
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
// stand-in internet for the link check (2026-11-16): preloaded into the app (NODE_OPTIONS --require), it answers safety.js's https.get
// calls (the ones with a lookup) and the DNS lookups those make, so every edit gets the full check with nothing leaving this machine. Like Node 20,
// the request asks the lookup for every address (all: true) and needs an array back (the VBB/ViralAdBlitz bug of 2026-11-15).
// Hosts: private.* -> 10.0.0.5 (refused), down.* unreachable, e404.* answers 404, redir.* 302 to https://example.org/landed,
// redir-http.* 302 to an http address, small.* a 125x125 image, anything else 200 (an image path gets a real 468x60 PNG).
const PROBE_STUB = `const https = require('https'), dns = require('dns'), fs = require('fs'), zlib = require('zlib'), { EventEmitter } = require('events'), { PassThrough } = require('stream');
const LOG = process.env.PROBE_LOG;
let probing = false; const dnsLookup = dns.lookup; // only lookups made by a link check are answered here; the app's other traffic resolves as usual
dns.lookup = function (h, o, cb) { if (!probing) return dnsLookup.apply(this, arguments); if (typeof o === 'function') { cb = o; o = {}; } const list = [{ address: String(h).startsWith('private.') ? '10.0.0.5' : '93.184.216.34', family: 4 }]; setImmediate(() => o && o.all ? cb(null, list) : cb(null, list[0].address, 4)); };
function png(w, h) {
const T = 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 = T[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
const ch = (t, d) => { const l = Buffer.alloc(4); l.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([l, td, c]); };
const ih = Buffer.alloc(13); ih.writeUInt32BE(w, 0); ih.writeUInt32BE(h, 4); ih[8] = 8; ih[9] = 2;
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), ch('IHDR', ih), ch('IDAT', zlib.deflateSync(Buffer.alloc((w * 3 + 1) * h))), ch('IEND', Buffer.alloc(0))]);
}
const orig = https.get;
https.get = function (url, opts, cb) {
if (!opts || typeof opts.lookup !== 'function') return orig.apply(this, arguments);
const u = new URL(url); const req = new EventEmitter(); req.destroy = () => {};
if (LOG) fs.appendFileSync(LOG, u.href + '\\n');
probing = true; try { opts.lookup(u.hostname, { all: true, family: 0 }, (err, list) => {
if (err) return req.emit('error', err);
if (!Array.isArray(list)) return req.emit('error', new Error('lookup answered ' + typeof list + ', not the array Node 20 asks for'));
const h = u.hostname; if (h.startsWith('down.')) return req.emit('error', new Error('ECONNREFUSED'));
const res = new PassThrough(); res.headers = {}; res.statusCode = 200; let body = Buffer.from('<!doctype html><title>ok</title>');
if (h.startsWith('e404.')) res.statusCode = 404;
else if (h.startsWith('redir-http.')) { res.statusCode = 302; res.headers.location = 'http://plain-http.com/'; }
else if (h.startsWith('redir.')) { res.statusCode = 302; res.headers.location = 'https://example.org/landed'; }
else if (/\\.(png|gif|jpe?g)$/i.test(u.pathname)) { body = h.startsWith('small.') ? png(125, 125) : png(468, 60); res.headers['content-type'] = 'image/png'; }
res.location = res.headers.location; const destroy = res.destroy.bind(res); res.destroy = () => destroy();
cb(res); res.end(body);
}); } finally { probing = false; }
return req;
};`;
const PROBE_LOG = path.join(OUT, 'probe-' + Date.now() + '.log'); const PROBE_FILE = path.join(OUT, 'probe-stub.cjs'); fs.writeFileSync(PROBE_FILE, PROBE_STUB);
const ART = path.resolve(APP, '..', 'contracts', 'out');
const ANVIL = process.env.ANVIL || path.join(os.homedir(), '.foundry', 'bin', 'anvil.exe');
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const RPC_PORT = Number(process.env.SMOKE_RPC_PORT || 18645), APP_PORT = Number(process.env.SMOKE_APP_PORT || 3111), BASE = 'http://127.0.0.1:' + APP_PORT;
const ADMIN = 'smoke-admin';
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pass = 0, fail = 0; const procs = [];
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 300) : '')); } };
// stand-in network hub (POST /v1/resolve, signed as bannerline) and stand-in InstantAdPay member lookup (the fallback when the
// hub is unreachable). HUB.people: {id, username, wallet, sponsorId}; HUB.down makes every hub call fail with 503.
const HUB = { people: [], down: false, calls: 0, badSig: 0, got: [] }; const HUB_PORT = APP_PORT + 7, HUB_SECRET = 'b'.repeat(40);
const IAPNET = new Map(); const IAP_PORT = APP_PORT + 8;
const TG = []; const TG_PORT = APP_PORT + 9; // stand-in Telegram Bot API (trust pack 2026-11-14): never the real group
const hubView = p => p ? { id: p.id, username: p.username, wallet: p.wallet, sponsor: (x => x ? { id: x.id, username: x.username } : null)(HUB.people.find(y => y.id === p.sponsorId)), blocked: false, locked: false } : null;
function startStandIns() {
const http = require('node:http'); const crypto = require('node:crypto');
http.createServer((q, r) => { let b = ''; q.on('data', c => { b += c; }); q.on('end', () => { let j = {}; try { j = JSON.parse(b || '{}'); } catch (e) {}
TG.push({ method: q.url.split('/').pop(), token: q.url.split('/')[1], body: j }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); }); }).listen(TG_PORT, '127.0.0.1');
http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c;
r.setHeader('Content-Type', 'application/json');
// the real hub serves the footer's network list publicly, unsigned (GET /v1/network-sites)
if (q.method === 'GET' && q.url === '/v1/network-sites') return r.end(JSON.stringify([{ id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' }, { id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' },
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' }, { id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' }, { id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }, { id: 'newsite', name: 'Hub Test Site', url: 'https://example.org' }]));
HUB.calls++;
if (HUB.down) { r.statusCode = 503; return r.end('{"error":"superseded"}'); }
const want = crypto.createHmac('sha256', HUB_SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
if (q.headers['x-hub-sig'] !== want || q.headers['x-hub-site'] !== 'bannerline') { HUB.badSig++; r.statusCode = 401; return r.end('{"error":"unauthorized"}'); }
if (q.url === '/v1/sso/signout') { HUB.got.push({ route: q.url, body: JSON.parse(b || '{}') }); return r.end('{"ok":true,"ended":1}'); } // Sign out everywhere (2026-11-16)
if (q.url !== '/v1/resolve') { r.statusCode = 404; return r.end('{"error":"not_found"}'); }
const j = JSON.parse(b || '{}'); const ref = String(j.ref || '').toLowerCase();
const p = j.id ? HUB.people.find(x => x.id === j.id) : j.wallet ? HUB.people.find(x => x.wallet === String(j.wallet).toLowerCase()) : ref ? HUB.people.find(x => x.username === ref || x.wallet === ref) : null;
r.end(JSON.stringify({ person: hubView(p) })); }).listen(HUB_PORT, '127.0.0.1').unref();
http.createServer((q, r) => { const u = new URL(q.url, 'http://x'); const un = (u.searchParams.get('u') || '').toLowerCase(), a = (u.searchParams.get('a') || '').toLowerCase();
const hit = [...IAPNET].find(([n, w]) => n === un || w === a); r.setHeader('Content-Type', 'application/json');
r.end(JSON.stringify(hit ? { address: hit[1], username: hit[0] } : {})); }).listen(IAP_PORT, '127.0.0.1').unref();
}
function cleanup() { for (const p of procs) { try { p.kill(); } catch (e) {} } }
process.on('exit', cleanup);
// ---- tiny cookie-jar HTTP client ----
function client(ua) {
const jar = {};
return {
jar,
async req(p, opts = {}) {
const headers = Object.assign({ 'User-Agent': ua || 'Mozilla/5.0 smoke', Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, opts.headers || {});
const r = await fetch(BASE + p, { method: opts.method || 'GET', headers, body: opts.body, redirect: 'manual' });
for (const c of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv] = c.split(';'); const i = kv.indexOf('='); jar[kv.slice(0, i)] = kv.slice(i + 1); }
return r;
},
async json(p, body, extraHeaders) { const r = await this.req(p, body === undefined ? { headers: extraHeaders } : { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extraHeaders), body: JSON.stringify(body) }); return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); }
};
}
function png(w, h) {
const crcT = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
const crc = b => { let c = 0xffffffff; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
const chunk = (t, d) => { const len = Buffer.alloc(4); len.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const o = y * (w * 3 + 1) + 1 + x * 3; raw[o] = 40 + x % 200; raw[o + 1] = 120; raw[o + 2] = 90 + y * 2; }
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
}
async function main() {
// ---- 1. chain ----
console.log('1. anvil + contract');
// never talk to someone else's node: the port must be free before our anvil starts
const busy = await fetch('http://127.0.0.1:' + RPC_PORT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}' }).then(() => true, () => false);
if (busy) throw new Error('port ' + RPC_PORT + ' is already in use; set SMOKE_RPC_PORT');
const appBusy = await fetch('http://127.0.0.1:' + APP_PORT).then(() => true, () => false);
if (appBusy) throw new Error('port ' + APP_PORT + ' is already in use; set SMOKE_APP_PORT');
const anvil = spawn(ANVIL, ['--port', String(RPC_PORT), '--silent'], { stdio: 'ignore' }); procs.push(anvil);
const provider = new ethers.JsonRpcProvider('http://127.0.0.1:' + RPC_PORT, 31337, { staticNetwork: true, pollingInterval: 200 });
for (let i = 0; i < 50; i++) { try { await provider.getBlockNumber(); break; } catch (e) { await sleep(200); } }
const W = Array.from({ length: 10 }, (_, i) => new ethers.NonceManager(ethers.HDNodeWallet.fromPhrase('test test test test test test test test test test test junk', undefined, "m/44'/60'/0'/0/" + i).connect(provider)));
const addr = await Promise.all(W.map(w => w.getAddress()));
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
const feedA = art('MockV3Aggregator'), lineA = art('BannerLine');
const feed = await (await new ethers.ContractFactory(feedA.abi, feedA.bytecode.object, W[0]).deploy(200000000000n)).waitForDeployment();
const deployBlock = await provider.getBlockNumber();
const line = await (await new ethers.ContractFactory(lineA.abi, lineA.bytecode.object, W[0]).deploy(addr[8], addr[9], addr[7], await feed.getAddress())).waitForDeployment();
const CA = await line.getAddress();
const q = await line.quoteWei(); ok(q === 2500000000000000n, 'quoteWei = 0.0025 POL at $2000', q.toString());
const send = q + q / 100n;
const [A, B, Cc, D, E, F] = [1, 2, 3, 4, 5, 6];
const buy = async (i, sponsor) => (await line.connect(W[i]).buy(sponsor, { value: send })).wait();
await buy(A, ethers.ZeroAddress); await buy(B, addr[A]); await buy(Cc, addr[B]); await buy(D, addr[B]);
await (await line.connect(W[F]).buyFor(addr[E], addr[A], { value: send })).wait();
await buy(A, ethers.ZeroAddress); await buy(0, ethers.ZeroAddress); // no-sponsor buys feed the momentum fund enough for one keeper buy
ok(Number(await line.spotCount()) === 7, '7 spots bought on anvil');
const paidTo = async a => (await line.queryFilter(line.filters.Paid(null, a), deployBlock)).reduce((t, e) => t + e.args.amount, 0n);
// ---- 2. server ----
console.log('2. server');
const DATA = path.join(OUT, 'data-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
// house list for tests: reserved example domains only, so no real site sees test traffic
fs.writeFileSync(path.join(DATA, 'house.json'), JSON.stringify([{ key: 'one', title: 'Test house 1', img: '/art/house-iap.svg', link: 'https://example.com/' }, { key: 'two', title: 'Test house 2', img: '/art/house-linkspin.svg', link: 'https://example.net/' }]));
const env = Object.assign({}, process.env, { PORT: String(APP_PORT), DATA_DIR: DATA, CHAIN_ID: '31337', RPC_URLS: 'http://127.0.0.1:' + RPC_PORT, CONTRACT_ADDRESS: CA,
DEPLOY_BLOCK: String(deployBlock), POLL_MS: '1000', ADMIN_TOKEN: ADMIN, KEEPER_ENABLED: '1', KEEPER_KEY: W[7].signer.privateKey, KEEPER_STALL_HOURS: '0.01', KEEPER_EVERY_MIN: '0.25', NODE_ENV: 'development',
HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'bannerline', HUB_ENABLED: '0', NETKB: '0', HUB_DOWN_MS: '400', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + IAP_PORT + '/api/network/member',
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT,
PROBE_LOG, NODE_OPTIONS: '--require ' + JSON.stringify(PROBE_FILE).slice(1, -1) }); // the link check runs on every edit against the stand-in internet (probe-stub.cjs)
startStandIns();
const hid = n => 'h_' + String(n).padStart(16, '0');
const ZW = ethers.Wallet.createRandom().address.toLowerCase(); // a network member with no spot here
HUB.people.push({ id: hid(1), username: 'alpha', wallet: addr[A].toLowerCase(), sponsorId: null }, { id: hid(2), username: 'beta', wallet: addr[B].toLowerCase(), sponsorId: hid(1) },
{ id: hid(3), username: 'zed', wallet: ZW, sponsorId: hid(2) }, { id: hid(4), username: 'zeta', wallet: null, sponsorId: null });
IAPNET.set('iaponly', addr[Cc].toLowerCase()); IAPNET.set('iapfallback', addr[D].toLowerCase());
const srv = spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] }); procs.push(srv);
const log = fs.createWriteStream(path.join(OUT, 'server.log')); srv.stdout.pipe(log); srv.stderr.pipe(log);
const u = client();
for (let i = 0; i < 60; i++) { try { const s = await u.json('/api/stats'); if (s.totals && s.totals.spots >= 7) break; } catch (e) {} await sleep(300); }
const st = await u.json('/api/stats');
ok(st.totals && st.totals.spots === 7, 'index parsed 7 SpotBought', st.totals);
ok(st.totals && st.totals.members === 6, 'index parsed 6 MemberJoined (payer of a buyFor is not a member)', st.totals);
ok(BigInt(st.totals.paidInWei) === 7n * q, 'paid in = 7 x quote (refunds excluded)', st.totals.paidInWei);
const cfg = await u.json('/api/config'); ok(cfg.ready && cfg.sel.buy === '0xf088d547', '/api/config has contract + selectors');
// the site assistant (2026-11-15): widget on every page, canned answers without AI, account problems hand off, admin KB behind the token
{ const home = await (await u.req('/')).text();
ok(/<script src="\/assets\/chat\.js\?v=\d+" defer><\/script>/.test(home) && (await u.req('/assets/chat.js')).status === 200 && (await u.req('/assets/chat.css')).status === 200, 'chat widget on the page, its script and styles served');
const ch = async m => (await u.req('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: m }) })).json();
const a1 = await ch('Where does the $5 go?'); ok(a1.canned && /\$0\.275/.test(a1.reply) && /\$1\.50/.test(a1.reply), 'chat: canned split answer', a1);
const a2 = await ch('my spot did not show up'); ok(a2.handoff === true && /^https:\/\/instantadpay\.com\/support\?from=bannerline/.test(a2.support || ''), 'chat: account problem hands off to network support', a2);
ok((await u.req('/api/admin/kb')).status === 401, 'admin KB needs the token'); }
const qq = await u.json('/api/quote'); ok(qq.wei === q.toString() && qq.source === 'contract.quoteWei', '/api/quote reads quoteWei()', qq);
for (const p of ['/', '/board', '/join', '/my', '/how', '/assets/site.css', '/art/house-line.svg']) { const r = await u.req(p); ok(r.status === 200, 'GET ' + p + ' 200'); }
const r404 = await u.req('/nope'); ok(r404.status === 404, 'unknown path 404');
// trust pack (2026-11-14): legal pages + the network list from the hub
for (const p of ['/terms', '/disclaimer', '/privacy']) { const r = await u.req(p); const h = await r.text();
ok(r.status === 200 && h.includes('TrustClickz') && !/Green Valley|Moody|35004/.test(h) && !h.includes('—') && !/at most 10 times|\$2\.75/.test(h), 'GET ' + p + ' 200 (TrustClickz, no em dash, no cap)'); }
{ const legal = (await (await u.req('/terms')).text()) + (await (await u.req('/disclaimer')).text()) + (await (await u.req('/privacy')).text());
ok(/300 guaranteed views/.test(legal) && /ever billed again/.test(legal) && /final once confirmed/.test(legal) && /momentum fund/.test(legal) && /network hub/.test(legal) && /not an investment/.test(legal), 'legal pages state the real mechanics (advertising, one-time, no refunds on-chain, momentum fund, the hub)'); }
{ let ns; for (let i = 0; i < 20; i++) { ns = await (await u.req('/api/network-sites')).json(); if (Array.isArray(ns) && ns.length === 7) break; await sleep(150); }
ok(Array.isArray(ns) && ns.length === 7 && ns[6].name === 'Hub Test Site', '/api/network-sites serves the hub list (a site added on the hub shows up)', ns && ns.map(x => x.name)); }
// promo kit (2026-11-14): one public feed read by /promote and by InstantAdPay's promo center
{
const kr = await u.req('/api/promo-kit?u=alpha'); const k = await kr.json();
ok(kr.status === 200 && kr.headers.get('access-control-allow-origin') === '*', 'promo kit: GET /api/promo-kit 200 with CORS open', kr.status);
ok(k.username === 'alpha' && k.links.length === 3 && k.links.every(l => l.url.startsWith('https://downlinebanners.com/') && l.url.endsWith('?ref=alpha')), 'promo kit: every link carries ?ref=<username>', k.links);
ok(k.links.every(l => /^https:\/\/linkspin\.app\/r\/nwdlb\?src=dlb&s1=alpha(&s2=[a-z]+)?$/.test(l.tracked)) && k.links[0].tracked.indexOf('&s2=') < 0 && /&s2=how$/.test(k.links[1].tracked), 'promo kit: every link has a LinkSpin-tracked twin (network link nwdlb, source dlb, the member as s1, the page as s2)', k.links.map(l => l.tracked));
ok(k.lines.length === 5 && k.headlines.length === 3 && k.posts.length === 2 && k.email && k.email.body.includes('?ref=alpha'), 'promo kit: 5 lines, 3 headlines, 1 email, 2 posts, link filled in');
const words = JSON.stringify([k.lines, k.headlines, k.email, k.posts, k.note, k.tagline]);
ok(!/[—–]/.test(words) && !/passive income|guaranteed (income|returns|profit|earnings)|earn (cash|money)|make money/i.test(words) && /300 guaranteed views/.test(words) && /30%/.test(words) && /5\.5%/.test(words), 'promo kit copy: no dashes, no income promises, facts match the contract (300 views, 30%, 5.5%)');
ok(k.creatives.length === 27 && new Set(k.creatives.map(c => c.angle)).size === 3, 'promo kit: 27 creatives in 3 angles', k.creatives.length);
const badName = k.creatives.filter(c => /\d{2,4}x\d{2,4}|banner|[-_/]ads?[-_./]/i.test(c.url.replace('https://downlinebanners.com', '')));
ok(badName.length === 0, 'promo kit: creative paths are ad-blocker neutral', badName.map(c => c.url));
const bad = [];
for (const c of k.creatives) {
const rr = await u.req(new URL(c.url).pathname); const buf = Buffer.from(await rr.arrayBuffer());
if (rr.status !== 200 || rr.headers.get('content-type') !== 'image/png' || buf.readUInt32BE(16) !== c.w || buf.readUInt32BE(20) !== c.h) bad.push(c.key + ' ' + rr.status);
if (!c.html.includes('href="https://downlinebanners.com/?ref=alpha"')) bad.push(c.key + ' html');
}
ok(bad.length === 0, 'promo kit: every creative served as PNG at its exact size, HTML links to the member', bad);
ok((await u.req('/art/kit/../server.js')).status !== 200 && (await u.req('/art/kit/nope.png')).status === 404, 'promo kit: /art/kit serves kit files only');
const k2 = await (await u.req('/api/promo-kit?u=' + encodeURIComponent('<b>'))).json();
ok(k2.username === null && k2.links[0].url === 'https://downlinebanners.com/', 'promo kit: a bad username is ignored', k2.links[0]);
const pr = await u.req('/promote'); const ph = await pr.text(); ok(pr.status === 200 && /id="kit"/.test(ph), 'GET /promote serves the Promote page');
ok((await (await u.req('/sitemap.xml')).text()).includes('/promote'), 'sitemap lists /promote');
}
const myHdr = await u.req('/my'); ok(myHdr.headers.get('x-frame-options') === 'DENY' && !(await u.req('/')).headers.get('x-frame-options'), '/my not frameable, / frameable');
// ---- 3. gate (HTTP) ----
console.log('3. gate over HTTP (about 50 s of timers)');
const v = client(); await v.req('/?ref=' + addr[B]);
ok(!!v.jar['bl.ref'], 'ref cookie set from ?ref=');
const g = await v.json('/api/gate');
ok(!g.passed && g.steps && g.steps[0].role === 'sponsor', 'gate starts with the sponsor spot', g.steps && g.steps.map(s => s.role || s.type));
ok(g.steps && g.steps[1].type === 'board' && g.steps.filter(s => s.role === 'newest').length === 3, 'board step then 3 newest spots');
const early = await v.json('/api/gate/done', { gid: g.gid, i: 0 }); ok(early._status === 400, 'done before begin is refused');
let passedGate = false;
for (let i = 0; i < g.steps.length; i++) {
const s = g.steps[i];
await v.json('/api/gate/begin', { gid: g.gid, i });
if (s.type === 'visit') { const r = await v.req(s.open + '?g=' + g.gid + '&i=' + i); ok(r.status === 302, 'step ' + i + ' visit relays (302 to ' + r.headers.get('location') + ')'); }
if (i === 0) { const tooSoon = await v.json('/api/gate/done', { gid: g.gid, i }); ok(tooSoon._status === 400, 'done before the timer is refused'); }
await sleep(s.seconds * 1000);
const d = await v.json('/api/gate/done', { gid: g.gid, i });
if (d.passed) passedGate = true; else if (d.error) ok(false, 'step ' + i + ' done', d);
}
ok(passedGate && !!v.jar['bl.pass'], 'gate passed, pass cookie set');
ok((await v.json('/api/gate')).passed === true, 'gate reports passed on return');
const st2 = await u.json('/api/stats'); const day = Object.values(st2.daily || {}).pop() || {};
ok(day.views_gate >= 7 && day.clicks_gate >= 4, 'gate views + gate clicks stored apart', day);
const bot = client('Googlebot/2.1'); ok((await bot.json('/api/gate')).passed === true, 'bots skip the gate');
// ---- 4. organic board view ----
const bd = await v.json('/api/board'); ok(bd.tiles && bd.tiles.filter(t => t.t === 'spot').length >= 7 && bd.tiles[0].id > bd.tiles[1].id && bd.tiles.some(t => t.t === 'house'), 'board: all spots newest first + house fill', bd.tiles && bd.tiles.map(t => t.id || t.key));
const fast = await v.json('/api/board/seen', { token: bd.token }); ok(fast.counted === 0, 'board view before 5 s not counted');
const bd2 = await v.json('/api/board'); await sleep(5000);
const gateIds = new Set(g.steps[1].tiles.filter(t => t.t === 'spot').map(t => t.id)); const fresh = bd2.tiles.filter(t => t.t === 'spot' && !gateIds.has(t.id)).length; // a keeper spot may be new
const seen = await v.json('/api/board/seen', { token: bd2.token }); ok(seen.counted === fresh, 'same visitor within the hour: views not double counted', [seen, fresh]);
const v2 = client('Mozilla/5.0 other'); const bd3 = await v2.json('/api/board'); await sleep(5000);
const seen3 = await v2.json('/api/board/seen', { token: bd3.token }); ok(seen3.counted === bd3.tiles.filter(t => t.t === 'spot').length && seen3.counted > 0, 'new visitor organic views counted', seen3);
ok((await v2.json('/api/board/seen', { token: bd3.token })).counted === 0, 'board token is one-time');
// ---- 5. sign in + My Spots ----
console.log('5. sign-in + My Spots');
const m = client();
const ch = await m.json('/api/auth/challenge', { address: addr[A] });
const sig = await W[A].signer.signMessage(ch.message);
const bad = await m.json('/api/auth/verify', { address: addr[A], signature: await W[B].signer.signMessage(ch.message) }); ok(bad._status === 400, 'signature from another wallet refused');
const ch2 = await m.json('/api/auth/challenge', { address: addr[A] });
const ver = await m.json('/api/auth/verify', { address: addr[A], signature: await W[A].signer.signMessage(ch2.message) });
ok(ver.ok && !!m.jar['bl.sid'], 'wallet signature sign-in sets session', ver);
const my = await m.json('/api/my');
ok(my.spots && my.spots.length >= 2, 'A owns 2+ spots', my.spots && my.spots.length);
let my2 = my, onChain = await paidTo(addr[A]);
if (BigInt(my2.paidOutWei) !== onChain) { await sleep(2500); my2 = await m.json('/api/my'); onChain = await paidTo(addr[A]); } // a keeper buy may land in between
ok(BigInt(my2.paidOutWei) === onChain && onChain > 0n, 'A paid out matches Paid events on chain (' + ethers.formatEther(onChain) + ' POL)', my2.paidOutWei);
ok(BigInt(my.paidInWei) === 2n * q, 'A paid in = 2 spots', my.paidInWei);
ok(my.directs && my.directs.length === 2 && my.directs.some(x => x.address === addr[B].toLowerCase()), 'A directs = B and E (buyFor sponsor)', my.directs);
ok(my.share.endsWith('?ref=alpha'), 'share link uses the network username the hub has for the wallet', my.share);
const sid = my.spots[my.spots.length - 1].id;
ok((await m.json('/api/my/spot/' + sid, { link: 'http://example.org/' }))._status === 400, 'http link refused');
ok((await m.json('/api/my/spot/' + sid, { link: 'https://192.168.1.1/' }))._status === 400, 'IP link refused');
ok((await m.json('/api/my/spot/' + sid, { link: 'https://bit.ly/x' }))._status === 400, 'shortener refused');
ok((await m.json('/api/my/spot/' + sid, { link: 'javascript:alert(1)' }))._status === 400, 'javascript: refused');
ok((await m.json('/api/my/spot/' + sid, { link: 'https://example.org/landing' })).ok, 'https link saved');
const otherSpot = (await u.json('/api/stats')).recent.find(s => s.owner === addr[B].toLowerCase());
ok((await m.json('/api/my/spot/' + otherSpot.id, { link: 'https://example.org/' }))._status === 403, 'cannot edit someone else\'s spot');
const up = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(468, 60) })).json();
ok(up.ok && /^\/art\/u\//.test(up.img), 'PNG 468x60 upload saved', up);
ok((await m.req(up.img)).status === 200, 'uploaded image served');
const upBad = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(300, 250) })).json();
ok(!!upBad.error, 'wrong size refused', upBad);
const upBig = await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: Buffer.concat([png(468, 60), Buffer.alloc(160 * 1024)]) });
ok(upBig.status === 400, 'over 150 KB refused');
ok((await m.json('/api/my/default', { link: 'https://example.org/default' })).ok, 'default link saved');
const bd4 = await v.json('/api/board'); const t = bd4.tiles.find(x => x.id === sid);
ok(t && t.img === up.img, 'board shows the uploaded image for that spot');
const go = await v.req('/go/' + sid); ok(go.headers.get('location') === 'https://example.org/landing', 'click relay goes to the member link');
// ---- 5b. network hub lookups (Marty 2026-11-14: everything through the hub; InstantAdPay only when the hub is unreachable) ----
console.log('5b. network hub lookups');
const nb = [1, 2, 3].map(() => ethers.Wallet.createRandom().address.toLowerCase());
HUB.people.push({ id: hid(11), username: 'newone', wallet: nb[0], sponsorId: hid(1) }, { id: hid(12), username: 'newtwo', wallet: nb[1], sponsorId: hid(3) }, { id: hid(13), username: 'newthree', wallet: nb[2], sponsorId: hid(4) });
ok((await m.json('/api/my')).username === 'alpha', 'My Spots shows the network username the hub has for the wallet');
let sp = await u.json('/api/sponsor?ref=alpha'); ok(sp.address === addr[A].toLowerCase() && sp.member, '?ref=<username> resolves through the hub', sp);
sp = await u.json('/api/sponsor?ref=iaponly'); ok(sp.address === null, 'a username only InstantAdPay knows: unknown while the hub answers', sp);
const rv = client(); await rv.req('/?ref=' + addr[Cc]);
sp = await rv.json('/api/sponsor?for=' + nb[0]); ok(sp.address === addr[A].toLowerCase() && sp.via === 'hub', 'buyer the hub knows: the hub network sponsor (resolved to a wallet by hub id) beats the ?ref= cookie', sp);
sp = await rv.json('/api/sponsor?for=' + nb[1]); ok(sp.address === addr[B].toLowerCase() && sp.via === 'hub', 'network sponsor without a spot here: the next one up the network line who has one', sp);
sp = await rv.json('/api/sponsor?for=' + nb[2]); ok(sp.address === null && sp.via === 'hub', 'network sponsor with no wallet and nobody above: no sponsor (never the ?ref= cookie, never the company)', sp);
sp = await rv.json('/api/sponsor?for=' + ethers.Wallet.createRandom().address); ok(sp.address === addr[Cc].toLowerCase() && sp.via === 'ref', 'a wallet the hub does not know: the ?ref= cookie as before', sp);
sp = await rv.json('/api/sponsor?for=' + addr[E]); ok(sp.via === 'ref', 'already a member here: the hub does not pick (the contract keeps the bound sponsor)', sp);
const wc = 'smokewl0001'; ok((await u.json('/api/admin/welcome', { codes: { [wc]: { line: ['nobodyhere', 'zed', 'beta'] } } }, { 'x-admin-token': ADMIN })).ok, 'welcome code saved');
const wv = client(); await wv.req('/w/' + wc); sp = await wv.json('/api/sponsor');
ok(sp.address === addr[B].toLowerCase() && sp.via === 'line', '/w/ welcome line: usernames resolved through the hub, first one with a spot here', sp);
ok(HUB.badSig === 0 && HUB.calls > 0, 'every hub call is signed as bannerline with HUB_SECRET', HUB);
// Telegram payment proof (stand-in API): one message per sale, with this week's numbers and an image above the text
{ const stt = await u.json('/api/stats'); let msgs = []; for (let i = 0; i < 40; i++) { msgs = TG.filter(c => c.method === 'sendMessage'); if (msgs.length >= stt.totals.spots) break; await sleep(250); }
const txs = msgs.map(c => (String(c.body.text).match(/\/tx\/(0x[0-9a-f]{64})/) || [])[1]);
ok(msgs.length === stt.totals.spots && new Set(txs).size === msgs.length && txs.every(Boolean), 'one Telegram message per spot sale, never two for the same tx', { msgs: msgs.length, spots: stt.totals.spots });
ok(msgs.every(c => c.token === 'botstandin-token' && c.body.chat_id === '-100123' && c.body.message_thread_id === 632242 && /This week: \d+ spots? .*\d+ spots in the line/.test(c.body.text)
&& c.body.link_preview_options && /^https:\/\/[^/]+\/art\/kit\/dlb-(spot|line|instant)-social\.png$/.test(c.body.link_preview_options.url) && c.body.link_preview_options.show_above_text === true && !c.body.text.includes('—')),
'each message: payments topic, this week\'s spot numbers, a large kit image above the text', msgs[0] && msgs[0].body);
ok(new Set(msgs.map(c => c.body.link_preview_options && c.body.link_preview_options.url)).size > 1, 'the image rotates between messages'); }
HUB.down = true;
sp = await u.json('/api/sponsor?ref=iapfallback'); ok(sp.address === addr[D].toLowerCase(), 'hub unreachable: InstantAdPay answers the username lookup', sp);
const t0 = Date.now(); sp = await rv.json('/api/sponsor?for=' + ethers.Wallet.createRandom().address); ok(sp.via === 'ref' && Date.now() - t0 < 2000, 'hub unreachable: the sponsor pick falls back at once (no wait on the hub)', [sp, Date.now() - t0]);
const ah = await u.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(ah.hubLookup && ah.hubLookup.on && ah.hubLookup.stats.failed >= 1 && !JSON.stringify(ah).includes(HUB_SECRET), 'admin status shows the hub lookup (failures counted, no secret)', ah.hubLookup);
HUB.down = false; await sleep(500);
HUB.people.push({ id: hid(21), username: 'later', wallet: addr[Cc].toLowerCase(), sponsorId: null });
sp = await u.json('/api/sponsor?ref=later'); ok(sp.address === addr[Cc].toLowerCase(), 'the hub answers again after it comes back', sp);
// ---- 6. keeper ----
console.log('6. keeper (stall set to 36 s for the test)');
const adm = await u.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(adm.keeper && adm.keeper.enabled && !JSON.stringify(adm).includes(W[7].signer.privateKey.slice(2, 20)), 'keeper on, key never in output');
let fb = null;
for (let i = 0; i < 40 && !fb; i++) { const s = await u.json('/api/stats'); fb = (s.recent || []).find(x => x.kind === 2 || x.kind === 3); if (!fb) await sleep(2000); }
ok(fb && fb.kind === 2 && fb.owner === addr[A].toLowerCase(), 'keeper fundBuy gifted a spot to A (builder, longest wait)', fb);
const adm2 = await u.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(adm2.keeper.log.some(e => e.status === 'mined'), 'keeper log shows the mined tx', adm2.keeper.log.slice(0, 3));
// the network hub's member lookup (2026-11-14, read-only)
const ml = await u.json('/api/admin/member-lookup?q=' + addr[A], undefined, { 'x-admin-token': ADMIN });
ok(ml._status === 200 && ml.known && ml.spots.length >= 1 && ml.spots.every(x => /^0x[0-9a-f]{64}$/.test(x.tx)) && ml.contract, 'admin member lookup by wallet: spots with tx hashes', ml);
const ml2 = await u.json('/api/admin/member-lookup?q=' + ml.spots[0].id, undefined, { 'x-admin-token': ADMIN });
ok(ml2._status === 200 && ml2.address === addr[A].toLowerCase() && ml2.via === 'spot', 'admin member lookup by spot id finds the owner', ml2.address);
ok((await u.json('/api/admin/member-lookup?q=' + addr[A], undefined, { 'x-admin-token': 'wrong' }))._status === 401, 'admin member lookup refuses a wrong token');
const ml3 = await u.json('/api/admin/member-lookup?q=' + ethers.Wallet.createRandom().address, undefined, { 'x-admin-token': ADMIN });
ok(ml3._status === 200 && ml3.known === false && ml3.spots.length === 0, 'admin member lookup: an unknown wallet is known: false', ml3);
const logTxt = fs.readFileSync(path.join(OUT, 'server.log'), 'utf8');
ok(!logTxt.includes(W[7].signer.privateKey.slice(2)), 'keeper key not in server log');
// ---- 7. pages in a browser ----
if (!process.env.SKIP_UI) {
console.log('7. Playwright: page renders + full UI gate');
const { chromium } = require(PW);
const browser = await chromium.launch();
const errors = [];
const watch = (pg, name) => { pg.on('console', msg => { if (msg.type() === 'error') errors.push(name + ': ' + msg.text() + ' @ ' + ((msg.location() || {}).url || '')); }); pg.on('pageerror', e => errors.push(name + ': ' + e.message)); };
// member context: signed in, gate skipped
const ctxM = await browser.newContext(); await ctxM.addCookies([{ name: 'bl.sid', value: m.jar['bl.sid'], url: BASE }]);
for (const p of ['/', '/board', '/how', '/join', '/my', '/promote', '/terms', '/disclaimer', '/privacy']) {
const pg = await ctxM.newPage(); watch(pg, 'member ' + p);
await pg.goto(BASE + p, { waitUntil: 'networkidle' });
await pg.screenshot({ path: path.join(OUT, 'member' + (p === '/' ? '-home' : p.replace('/', '-')) + '.png'), fullPage: true });
const foot = await pg.textContent('footer').catch(() => ''); ok(/Part of the Crypto Team Build Network/.test(foot || ''), 'member ' + p + ' renders with footer');
if (p === '/my') { await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 }).catch(() => {}); ok(await pg.isVisible('#dash'), '/my dashboard visible'); ok((await pg.$$('.spot-ed')).length >= 3, '/my spot editors listed'); }
if (p === '/promote') { await pg.waitForSelector('#kit .kit-fig img', { timeout: 8000 }).catch(() => {}); const kt = await pg.textContent('#kit'); const who = await pg.inputValue('#whoIn');
ok(!!who && kt.includes('?ref=' + who) && (await pg.$$('#kit .kit-set:not([hidden]) .kit-fig')).length === 9, '/promote shows the kit with the signed-in member link (' + who + ')'); ok(!!(await pg.$('nav a[href="/promote"]')), 'nav links to Promote');
await pg.waitForTimeout(500); await pg.screenshot({ path: path.join(OUT, 'member-promote.png'), fullPage: true });
await pg.setViewportSize({ width: 390, height: 844 }); await pg.waitForTimeout(300); await pg.screenshot({ path: path.join(OUT, 'member-promote-phone.png'), fullPage: true }); }
if (p === '/join') { await pg.waitForSelector('#buyCard:not([hidden])', { timeout: 8000 }).catch(() => {}); const price = await pg.textContent('#price'); ok(/^0\.0025/.test(price), '/join shows price ' + price); }
if (p === '/how') { await pg.waitForFunction(() => /Hub Test Site/.test((document.querySelector('footer .netline') || {}).textContent || ''), null, { timeout: 6000 }).catch(() => {});
const ft = (await pg.textContent('footer')).replace(/\s+/g, ' '); const hrefs = await pg.$$eval('footer a', as => as.map(a => a.getAttribute('href')));
ok(['/terms', '/disclaimer', '/privacy', '/contract', '/ledger'].every(h => hrefs.includes(h)) && /Support/.test(ft) && /© 2026 TrustClickz/.test(ft) && !/Green Valley/.test(ft)
&& /Part of the network · One account across the network: InstantAdPay · LinkSpin · Downline Banners · Viral Banner Blitz · Stack POL · Earners Corner · Hub Test Site/.test(ft) && !/RM Circle|rmcircle/i.test(ft)
&& (await pg.textContent('footer .netline .here')) === 'Downline Banners', 'footer: legal + proof links, company line, the hub network list with DLB as current, never RM Circle', ft.slice(-420));
await pg.locator('footer').screenshot({ path: path.join(OUT, 'footer-desktop.png') });
await pg.setViewportSize({ width: 390, height: 844 }); await pg.waitForTimeout(200);
ok(await pg.evaluate(() => document.documentElement.scrollWidth <= 390), 'footer fits a phone (no sideways scroll)'); await pg.locator('footer').screenshot({ path: path.join(OUT, 'footer-phone.png') }); }
const em = await pg.evaluate(() => document.body.innerText.includes('\u2014')); ok(!em, p + ' has no em dash');
await pg.close();
}
// visitor context: full gate in the UI
const ctxV = await browser.newContext(); const pg = await ctxV.newPage(); watch(pg, 'visitor /');
await pg.goto(BASE + '/?ref=' + addr[B], { waitUntil: 'domcontentloaded' });
await pg.waitForSelector('#gate:not([hidden])');
for (let i = 0; i < 8; i++) {
try { await pg.waitForSelector('#gNext:not([hidden])', { timeout: 20000 }); }
catch (e) { await pg.screenshot({ path: path.join(OUT, 'visitor-gate-stuck.png'), fullPage: true }).catch(() => {}); console.log(' gate stuck at step', i, JSON.stringify(await pg.evaluate(() => ({ what: (document.getElementById('gWhat') || {}).textContent, status: (document.getElementById('status') || {}).textContent })).catch(() => null))); throw e; }
const label = await pg.textContent('#gNext'); await pg.click('#gNext');
if (label === 'Continue') break;
}
await pg.waitForSelector('#open:not([hidden])', { timeout: 5000 }).catch(() => {});
ok(await pg.isVisible('#joinBtn'), 'UI gate completes and Join unlocks');
await pg.screenshot({ path: path.join(OUT, 'visitor-after-gate.png'), fullPage: true });
const pj = await ctxV.newPage(); watch(pj, 'visitor /join'); await pj.goto(BASE + '/join', { waitUntil: 'networkidle' });
ok(await pj.isVisible('#buyCard'), 'visitor /join unlocked after gate');
// fresh visitor: /join is locked
// visitor = IP + UA, so a fresh visitor needs its own UA
const ctxL = await browser.newContext({ userAgent: 'Mozilla/5.0 (fresh visitor) Chrome/130' }); const pl = await ctxL.newPage(); watch(pl, 'locked /join'); await pl.goto(BASE + '/join', { waitUntil: 'networkidle' });
ok(await pl.isVisible('#locked'), 'fresh visitor /join is locked');
const pm = await ctxL.newPage(); watch(pm, 'signed-out /my'); await pm.goto(BASE + '/my', { waitUntil: 'networkidle' }); ok(await pm.isVisible('#signin'), 'signed-out /my shows sign-in');
await browser.close();
// example.com pages inside the gate frame may log their own errors; only ours count
const ours = errors.filter(e => !/example\.(com|net|org)/.test(e)); // gate frames load example.* sites; their own 404s (favicon) are not ours
ok(ours.length === 0, 'no console errors on our pages', ours);
}
console.log('9. network hub events (sign out everywhere, block, erase end sessions here)');
{ const crypto = require('node:crypto'); const admin = (p, body) => client().json(p, body, { 'x-admin-token': ADMIN }); let hseq = 900000; let hn = 700;
const signAs = async (w, name) => { const c = client('Mozilla/5.0 hook ' + (hn++)); const a = w.address.toLowerCase(); const xf = { 'X-Forwarded-For': '198.51.100.' + (hn % 250) };
if (name) { c.hubId = hid(hn); HUB.people.push({ id: c.hubId, username: name, wallet: a, sponsorId: null }); }
const ch = await c.json('/api/auth/challenge', { address: w.address }, xf);
const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) }, xf);
c.address = a; c.wallet = w; c.ok = v.ok === true && !!c.jar['bl.sid']; return c; };
const walletMember = o => signAs((o && o.wallet) || ethers.Wallet.createRandom(), o && o.hub && o.hub.username); const signedIn = async c => (await c.json('/api/me')).signedIn === true;
const hook = async (events, o = {}) => { const raw = JSON.stringify({ events }); const ts = String(o.ts || Date.now());
const sig = o.sig || crypto.createHmac('sha256', o.secret || HUB_SECRET).update(ts + '\n' + raw).digest('hex');
const r = await fetch(BASE + '/api/hub/events', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, body: raw }); return r.status; };
const ev = (type, personId, data, at) => ({ seq: ++hseq, at: at || Date.now(), type, personId, data: data || {} });
const H1 = await walletMember({ hub: { username: 'hookone' } }); const H1b = await walletMember({ wallet: H1.wallet }); const H2 = await walletMember({ hub: { username: 'hooktwo' } });
const H3 = await walletMember({ hub: { username: 'hookthree' } }); const H4 = await walletMember({ hub: { username: 'hookfour' } });
ok(H1.ok && H1b.ok && H2.ok && H3.ok && H4.ok && await signedIn(H1) && await signedIn(H1b), 'setup: hub members signed in here (one of them in two browsers)');
ok(await hook([ev('member.signedout', H1.hubId)], { secret: 'x'.repeat(40) }) === 401 && await hook([ev('member.signedout', H1.hubId)], { ts: Date.now() - 600000 }) === 401, 'a hook signed with another key, or 10 minutes old, is refused (401)');
ok(await signedIn(H1), 'a refused hook ends nothing');
const so = ev('member.signedout', H1.hubId);
ok(await hook([so]) === 200 && !(await signedIn(H1)) && !(await signedIn(H1b)) && await signedIn(H2), 'member.signedout: every session of that wallet ends (both browsers), nobody else\'s');
const H1c = await walletMember({ wallet: H1.wallet });
ok(await hook([so]) === 200 && await signedIn(H1c), 'the same event sent twice: applied once, a fresh sign-in stays');
ok(await hook([ev('member.signedout', H1.hubId, {}, Date.now() - 60000)]) === 200 && await signedIn(H1c), 'an event older than a session never ends it (only sessions made before the event)');
ok(await hook([ev('member.blocked', H2.hubId)]) === 200 && !(await signedIn(H2)) && await signedIn(H3), 'member.blocked: that member is signed out here');
const wh = crypto.createHash('sha256').update(H3.address).digest('hex'); HUB.people = HUB.people.filter(x => x.id !== H3.hubId);
ok(await hook([ev('member.erased', H3.hubId, { emailHash: 'a'.repeat(64), walletHashes: [wh] })]) === 200 && !(await signedIn(H3)) && await signedIn(H4), 'member.erased: found by the wallet hash in the event (the hub no longer knows them), signed out');
ok(await hook([ev('member.joined', H4.hubId), ev('member.signedout', 'h_' + 'f'.repeat(16))]) === 200 && await signedIn(H4), 'other events and unknown people are ignored');
HUB.down = true; const late = ev('member.signedout', H4.hubId);
ok(await hook([late]) === 503 && await signedIn(H4), 'the hub lookup failing answers 503 (the hub sends it again), nothing ended');
HUB.down = false; ok(await hook([late]) === 200 && !(await signedIn(H4)), 'resent once the hub answers: signed out');
const E1 = await walletMember({ hub: { username: 'hookfive' } }); const E2 = await walletMember({ wallet: E1.wallet }); const g0 = HUB.got.length;
const eo = await E1.json('/api/auth/logout-everywhere', {});
const call = HUB.got.slice(g0).find(x => x.route === '/v1/sso/signout');
ok(eo.ok && eo.everywhere === true && !(await signedIn(E1)) && !(await signedIn(E2)) && call && call.body.wallet === E1.address, 'Sign out everywhere: the hub is told (signed, by wallet) and every session of that wallet here ends', { eo, call });
ok(/id="outAllBtn"[^>]*>Sign out everywhere</.test(await (await client().req('/my')).text()), '/my has a Sign out everywhere button next to Sign out');
const st2 = await admin('/api/admin/status');
ok(st2.hubEvents && st2.hubEvents.on && st2.hubEvents.stats.ended >= 5 && st2.hubEvents.stats.refused >= 2 && !JSON.stringify(st2.hubEvents).includes(HUB_SECRET), 'admin status shows the hub events (counts only, no secret)', st2.hubEvents);
}
console.log('10. spot edits (unlimited, full check, logged) + admin takedown and restore');
{ const ADM = (q, body) => u.json(q, body, { 'x-admin-token': ADMIN });
const probes = () => { try { return fs.readFileSync(PROBE_LOG, 'utf8').split('\n').filter(Boolean); } catch (e) { return []; } };
// the Node 20 lookup shape (VBB and ViralAdBlitz broke on it 2026-11-15): this copy answers an array when asked for all
const safety = require(path.join(APP, 'safety.js')); const dns = require('node:dns'); const dl = dns.lookup;
dns.lookup = (h, o, cb) => { const list = [{ address: String(h).startsWith('private.') ? '10.0.0.5' : '93.184.216.34', family: 4 }]; cb(null, o && o.all ? list : list[0].address, 4); };
const look = (h, o) => new Promise(r => safety.safeLookup(h, o, (e, a, f) => r({ e: e && e.message, a, f })));
const l1 = await look('pub.com', { all: true }), l2 = await look('pub.com', {}), l3 = await look('private.com', { all: true }); dns.lookup = dl;
ok(Array.isArray(l1.a) && l1.a[0].address === '93.184.216.34' && l2.a === '93.184.216.34' && l2.f === 4 && /private/.test(l3.e || ''), 'safeLookup: an array when asked for every address (Node 20), one address otherwise, a private address refused', { l1, l2, l3 });
const p0 = probes().length; const linkNow = async () => ((await m.json('/api/my')).spots.find(x => x.id === sid) || {}).link;
let e = await m.json('/api/my/spot/' + sid, { link: 'https://edit-one.com/a' });
ok(e.ok && e.edit && e.edit.what === 'link' && e.edit.old.link === 'https://example.org/landing' && e.edit.new.link === 'https://edit-one.com/a' && e.edit.at > 0, 'an edit is logged on the spot: old and new link, time', e.edit);
ok(probes().slice(p0).some(l => l.includes('edit-one.com')), 'the new link was fetched (the full check ran on the edit)');
let all = true; for (let i = 2; i <= 6; i++) { e = await m.json('/api/my/spot/' + sid, { link: 'https://edit-' + i + '.com/p' }); all = all && !!e.ok; }
ok(all && await linkNow() === 'https://edit-6.com/p', 'edits are unlimited: five more in a row all saved');
const refuse = [['https://down.edit-x.com/', /could not reach/], ['https://e404.edit-x.com/', /error \(404\)/], ['https://private.edit-x.com/', /private network/], ['https://redir-http.edit-x.com/', /must start with https/], ['https://bit.ly/abc', /shortener/]];
for (const [l, re] of refuse) { const r = await m.json('/api/my/spot/' + sid, { link: l }); ok(r._status === 400 && re.test(r.error || ''), 'edit refused by the full check: ' + l, r); }
ok(await linkNow() === 'https://edit-6.com/p', 'a refused edit changes nothing');
e = await m.json('/api/my/spot/' + sid, { link: 'https://redir.edit-x.com/go' }); ok(e.ok && probes().some(l => l.startsWith('https://example.org/landed')), 'a redirecting link is followed and its target checked too', e);
e = await m.json('/api/my/spot/' + sid, { img: 'https://img.edit-x.com/b.png' });
ok(e.ok && e.edit.what === 'img' && e.edit.new.img === 'https://img.edit-x.com/b.png' && probes().some(l => l.includes('img.edit-x.com')), 'an image address is downloaded and checked (468x60), then saved and logged', e.edit);
for (const [im, re] of [['https://small.edit-x.com/b.png', /468x60/], ['https://e404.edit-x.com/b.png', /answered 404/], ['https://down.edit-x.com/b.png', /could not download/]]) { const r = await m.json('/api/my/spot/' + sid, { img: im }); ok(r._status === 400 && re.test(r.error || ''), 'image refused: ' + im, r); }
e = await m.json('/api/my/spot/' + sid, { link: 'https://redir.edit-x.com/go' }); ok(e.ok && !e.edit, 'saving the same link again changes nothing and logs nothing', e);
const upE = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(468, 60) })).json(); ok(upE.ok, 'upload (edit by file)');
const mine = (await m.json('/api/my')).spots.find(x => x.id === sid);
ok(mine.edits.length === 10 && mine.edits[0].via === 'upload' && mine.edits[0].old.img === 'https://img.edit-x.com/b.png' && mine.edits[0].new.img === upE.img, 'the owner sees the newest edits first (an upload is logged too)', mine.edits.slice(0, 2));
const de = await m.json('/api/my/default', { link: 'https://e404.def-x.com/' }); const de2 = await m.json('/api/my/default', { link: 'https://def-ok.com/x' });
ok(de._status === 400 && de2.ok && de2.edit && de2.edit.old.link === 'https://example.org/default', 'the default link gets the same check and log', { de, de2 });
console.log('10b. admin takedown and restore');
const tilesOf = async () => (await v.json('/api/board')).tiles;
const t0 = await tilesOf(); const i0 = t0.findIndex(x => x.id === sid);
ok(i0 >= 0, 'the spot is on the board before', t0.map(x => x.id || x.t));
let r = await u.json('/api/admin/spots?q=%23' + sid); ok(r._status === 401, 'admin find needs the token');
const f1 = await ADM('/api/admin/spots?q=%23' + sid), f2 = await ADM('/api/admin/spots?q=' + addr[A]), f3 = await ADM('/api/admin/spots?q=alpha');
ok(f1.spots && f1.spots[0].id === sid && f1.spots[0].edits.length >= 10 && f1.spots[0].defaultEdits.length >= 1 && [f2, f3].every(f => f.spots && f.spots.some(x => x.id === sid)), 'admin finds the spot by #number, wallet and username, with its edit log', { f2: f2.spots && f2.spots.length, f3: f3.error || f3.spots.length });
ok((await ADM('/api/admin/spots?q=nobodyhere')).error, 'nothing found for an unknown username');
const P = '/api/admin/spots/' + sid;
ok((await u.json(P + '/takedown', { reason: 'test', credit: 'none' }))._status === 401, 'takedown needs the token');
ok((await ADM(P + '/takedown', { reason: '', credit: 'none' }))._status === 400, 'a reason is required');
ok((await ADM(P + '/takedown', { reason: 'Broken landing page' }))._status === 400, 'a credit choice is required');
const cb = await ADM(P + '/takedown', { reason: 'Broken landing page', credit: 'back' });
ok(cb._status === 400 && /Marty decides/.test(cb.error) && !(await ADM('/api/admin/spots?q=%23' + sid)).spots[0].down, 'credit back is refused (not defined for Downline Banners yet) and nothing is taken down', cb.error);
const views0 = f1.spots[0].views;
const td = await ADM(P + '/takedown', { reason: 'Misleading offer on the landing page', credit: 'none', by: 'smoke' });
ok(td.ok && td.down.reason === 'Misleading offer on the landing page' && td.log.action === 'takedown' && td.log.credit === 'none' && td.spot.showing.from === 'down', 'taken down, no credit; the admin view shows it', td);
ok((await ADM(P + '/takedown', { reason: 'again', credit: 'none' }))._status === 400, 'a second takedown is refused');
const t1 = await tilesOf();
ok(!t1.some(x => x.id === sid) && t1.length === t0.length && t1[i0] && t1[i0].t === 'house' && t1[i0].held === true && !t1[i0].owner, 'board: the spot is gone, a house tile holds its place, same number of tiles', t1.map(x => x.id || (x.held ? 'held' : x.t)));
ok(JSON.stringify(t1).indexOf(upE.img) < 0, 'its image shows nowhere on the board');
ok((await v.req('/go/' + sid)).headers.get('location') === '/', '/go/<spot> goes home while it is down');
const gv = client('Mozilla/5.0 gate after takedown'); const gg = await gv.json('/api/gate', undefined, { 'X-Forwarded-For': '198.51.100.240' });
ok(gg.steps && !gg.steps.some(st => st.ref === String(sid) || st.img === upE.img), 'the gate never shows it (a house site takes its step)', gg.steps && gg.steps.map(st => st.ref || st.type));
const bt = await v.json('/api/board'); await sleep(4800); await v.json('/api/board/seen', { token: bt.token });
ok((await ADM('/api/admin/spots?q=%23' + sid)).spots[0].views === views0, 'no views count while it is down');
const mineD = (await m.json('/api/my')).spots.find(x => x.id === sid);
ok(mineD.down && mineD.down.reason === 'Misleading offer on the landing page' && mineD.showing.from === 'down', 'the owner sees "Taken down" with the reason', mineD.down);
const ed = await m.json('/api/my/spot/' + sid, { link: 'https://edit-7.com/' });
const upD = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(468, 60) })).json();
ok(ed._status === 400 && /taken down/.test(ed.error) && /taken down/.test(upD.error || ''), 'the owner cannot change a spot while it is down', { ed, upD });
if (!process.env.SKIP_UI) { // the pages while it is down: My Spots at phone width, and the admin page
const { chromium } = require(PW); const br = await chromium.launch(); const errs = [];
const cx = await br.newContext({ viewport: { width: 390, height: 844 } }); await cx.addCookies([{ name: 'bl.sid', value: m.jar['bl.sid'], url: BASE }]);
const pg = await cx.newPage(); pg.on('pageerror', x => errs.push(x.message));
await pg.goto(BASE + '/my', { waitUntil: 'networkidle' }); await pg.waitForSelector('.spot-down', { timeout: 8000 }).catch(() => {});
const txt = await pg.textContent('#spots'); const wide = await pg.evaluate(() => { const e = document.getElementById('spots'); return e.scrollWidth - e.clientWidth; }); // the spots card (the payments table further down is wider than a phone on its own)
ok(/Taken down/.test(txt) && txt.includes('Misleading offer on the landing page') && wide <= 1, 'My Spots (phone): "Taken down" with the reason, no sideways scroll', { wide });
ok(await pg.isVisible('#outAllBtn'), 'My Spots: Sign out everywhere button shows'); await pg.screenshot({ path: path.join(OUT, 'my-taken-down.png'), fullPage: true });
const pa = await cx.newPage(); pa.on('pageerror', x => errs.push(x.message)); await pa.goto(BASE + '/admin', { waitUntil: 'networkidle' });
await pa.fill('#tok', ADMIN); await pa.click('#tokBtn'); await pa.waitForSelector('#adm:not([hidden])', { timeout: 8000 }).catch(() => {});
await pa.fill('#spQ', '#' + sid); await pa.click('#spFind'); await pa.waitForSelector('.adm-spot', { timeout: 8000 }).catch(() => {});
const at = await pa.textContent('#spList'); const aw = await pa.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
ok(/TAKEN DOWN/.test(at) && /Restore this spot/.test(at) && /takedown/.test(await pa.textContent('#aActions')) && aw <= 1, 'admin page (phone): finds the spot, shows it taken down with Restore, ledger row', { aw });
await pa.screenshot({ path: path.join(OUT, 'admin-takedown.png'), fullPage: true });
ok(errs.length === 0, 'no page errors (taken-down views)', errs); await br.close();
}
const acts = await ADM('/api/admin/actions');
ok(acts.actions[0].action === 'takedown' && acts.actions[0].spotId === sid && acts.actions[0].reason === 'Misleading offer on the landing page' && acts.actions[0].credit === 'none' && acts.actions[0].by === 'smoke' && acts.actions[0].username === 'alpha', 'admin ledger: who, when, reason, credit decision', acts.actions[0]);
const rs = await ADM(P + '/restore', { reason: 'Owner fixed the page', by: 'smoke' });
ok(rs.ok && !rs.spot.down && rs.spot.downs.length === 1 && rs.spot.downs[0].restoreReason === 'Owner fixed the page' && rs.log.action === 'restore', 'restore: shows again, the takedown kept in its history', rs);
ok((await ADM(P + '/restore', {}))._status === 400, 'restoring a spot that is not down is refused');
const t2 = await tilesOf(); ok(t2.some(x => x.id === sid && x.img === upE.img), 'board shows the spot again after the restore');
ok((await v.req('/go/' + sid)).headers.get('location') === 'https://redir.edit-x.com/go', '/go/<spot> sends to its link again');
ok((await m.json('/api/my/spot/' + sid, { link: 'https://edit-8.com/' })).ok, 'the owner can edit again after the restore');
ok((await ADM('/api/admin/actions')).actions[0].action === 'restore', 'the restore is on the admin ledger');
const ap = await u.req('/admin'); ok(ap.status === 200 && ap.headers.get('x-frame-options') === 'DENY' && /Take a spot down/.test(await ap.text()), '/admin page served, never framed');
}
console.log('\n' + pass + ' passed, ' + fail + ' failed. Output in ' + OUT);
cleanup(); process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error(e); cleanup(); process.exit(1); });