diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c931a79 --- /dev/null +++ b/.env.example @@ -0,0 +1,23 @@ +# Viral Banner Blitz app env (Coolify later). Never commit real values. v1 is off-chain: no contract, no payments. +DOCSTORE_URL= # mysql://user:pass@host:3306/vbb REQUIRED for any real launch (files are local prototype only) +SITE_HOST=viralbannerblitz.com +SESSION_SECRET= # random hex; default = generated into DATA_DIR/.secret +ADMIN_TOKEN= # x-admin-token for /api/admin/status and /api/admin/ledger (8+ characters) +NETWORK_SSO_SECRET= # same value as InstantAdPay + LinkSpin (network sign-in); they must also list vbb under wallets +WALLETCONNECT_PROJECT_ID= # Reown id (IAP project); add the VBB domain to its allowlist first +LOOP_SIZE=50 # banners in the loop +VISITORS_PER_SHIFT=10 # verified unique visitors per shift +VIEWS_PER_CYCLE=150 # network ad views recorded per completed cycle +VISIT_SECONDS=6 # page visible this long before a visit counts +VISITS_PER_IP_DAY=3 # browsers counted per connection per 24 h +FREE_CREDITS_PER_DAY=1 +FREE_CREDIT_CAP=7 # free credits bank up to this many +MAX_QUEUED_PER_MEMBER=3 +CREDIT_PACKS=10:3,40:10 # credits:usd, shown as coming soon +LOOK_USD=2 # banner look, shown as coming soon +SPONSOR_PCT=30 # planned on-chain split (company gets the rest); not used in v1 +PRIZES_VISITORS=15,7,3 # weekly prizes in USD (paid in POL), displayed only +PRIZES_SOURCES=15,7,3 +LINK_PROBE=1 # 0 skips the target-link frame check (local tests only) +CF_PROXIED=0 # 1 only if Cloudflare proxies the domain (then cf-connecting-ip is trusted) +NETWORK_LOOKUP_URL= # default InstantAdPay /api/network/member; empty = off diff --git a/config.js b/config.js index 42844c8..4d4c088 100644 --- a/config.js +++ b/config.js @@ -1,11 +1,12 @@ // All runtime config comes from env (Coolify sets these). Read once. -// VBB v1 is off-chain: no contract, no prices, no money. Rewards are recorded, not credited yet. +// VBB v1 is off-chain: no contract, no payments. Planned prices are shown as "coming soon"; rewards are recorded, not credited yet. const path = require('path'); let cfg = null; function get() { if (cfg) return cfg; const e = process.env; + const list = (v, d) => String(v == null || v === '' ? d : v).split(',').map(x => x.trim()).filter(Boolean); const num = (v, d, min, max) => { const n = Number(v); return Number.isFinite(n) && v !== '' && v != null ? Math.min(max, Math.max(min, Math.round(n))) : d; }; cfg = { port: Number(e.PORT || 3000), @@ -26,8 +27,15 @@ function get() { visitWindowHours: 24, // one count per visitor key per 24 h perIpDay: num(e.VISITS_PER_IP_DAY, 3, 1, 100), // distinct user agents counted per IP per 24 h (shared connections, UA rotation) // members + freeCreditsPerDay: num(e.FREE_CREDITS_PER_DAY, 1, 0, 10), // Marty 2026-11-13: 1 free post credit a day on sign-in freeCreditCap: num(e.FREE_CREDIT_CAP, 7, 1, 365), // daily free credits bank up to this many maxQueuedPerMember: num(e.MAX_QUEUED_PER_MEMBER, 3, 1, 100), // banners one member may have waiting at once + // ---- Marty's approved numbers (2026-11-13). v1 takes no payments: packages show as "coming soon" with these planned prices, + // prizes are displayed only (no payout code yet), the split is kept here for the contract step. + packs: list(e.CREDIT_PACKS, '10:3,40:10').map(x => { const [credits, usd] = x.split(':').map(Number); return { credits, usd }; }).filter(x => x.credits > 0 && x.usd > 0), + lookUsd: Number(e.LOOK_USD || 2), // banner look (border + hover teaser), per banner, one-time + split: { sponsorPct: num(e.SPONSOR_PCT, 30, 0, 100), companyPct: 100 - num(e.SPONSOR_PCT, 30, 0, 100) }, // on-chain later, no line + prizes: { visitors: list(e.PRIZES_VISITORS, '15,7,3').map(Number).filter(x => x >= 0), sources: list(e.PRIZES_SOURCES, '15,7,3').map(Number).filter(x => x >= 0) }, // USD per place, paid in POL linkProbe: e.LINK_PROBE !== '0', // check the target link answers and allows frames (off in the local smoke test) iapBase: String(e.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''), lsBase: String(e.LS_URL || 'https://linkspin.app').replace(/\/+$/, ''), diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e05a9d7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,20 @@ +services: + vbb: + build: . + restart: unless-stopped + environment: + NODE_ENV: production + PORT: 3000 + DATA_DIR: /app/data + SITE_HOST: ${SITE_HOST:-viralbannerblitz.com} + DOCSTORE_URL: ${DOCSTORE_URL:-} + SESSION_SECRET: ${SESSION_SECRET:-} + ADMIN_TOKEN: ${ADMIN_TOKEN:-} + NETWORK_SSO_SECRET: ${NETWORK_SSO_SECRET:-} + WALLETCONNECT_PROJECT_ID: ${WALLETCONNECT_PROJECT_ID:-} + volumes: + - vbb-data:/app/data # uploads only once DOCSTORE_URL is set + expose: + - "3000" +volumes: + vbb-data: diff --git a/public/admin.html b/public/admin.html index f1a8805..0b23b1d 100644 --- a/public/admin.html +++ b/public/admin.html @@ -22,7 +22,7 @@ - +
diff --git a/public/art/icon-192.png b/public/art/icon-192.png new file mode 100644 index 0000000..5fdb069 Binary files /dev/null and b/public/art/icon-192.png differ diff --git a/public/art/og-share.png b/public/art/og-share.png new file mode 100644 index 0000000..c0d4c69 Binary files /dev/null and b/public/art/og-share.png differ diff --git a/public/assets/leaders.js b/public/assets/leaders.js index b4d0978..fb77fea 100644 --- a/public/assets/leaders.js +++ b/public/assets/leaders.js @@ -2,6 +2,14 @@ (async function () { VBB.renderNav('/leaders'); VBB.renderFooter(); const $ = VBB.$, esc = VBB.esc; + // weekly prizes from config (Marty 2026-11-13): displayed only, no payout code yet + const c = await VBB.getConfig().catch(() => ({})); + const pz = c.prizes || {}; const place = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th']; + const plist = (title, arr) => '

' + title + '

'; + if ((pz.visitors || []).length || (pz.sources || []).length) { + $('pz').innerHTML = ((pz.visitors || []).length ? plist('Most visitors sent', pz.visitors) : '') + ((pz.sources || []).length ? plist('Most traffic sources', pz.sources) : ''); + $('prizes').hidden = false; + } const d = await VBB.getJSON('/api/leaders'); if (d.error) return VBB.status(d.error, 'err'); const wk = new Date(d.week + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'long', day: 'numeric', timeZone: 'UTC' }); diff --git a/public/assets/static.js b/public/assets/static.js index 9c1ece7..a2d32f4 100644 --- a/public/assets/static.js +++ b/public/assets/static.js @@ -7,4 +7,9 @@ if (c.perShift) set('perShift', c.perShift); if (c.viewsPerCycle != null) set('views', VBB.n(c.viewsPerCycle)); if (c.visitSeconds) set('secs', c.visitSeconds); + // planned package prices from config (Marty 2026-11-13); still coming soon, nothing is sold here + const money = v => '$' + (Number.isInteger(v) ? v : Number(v).toFixed(2)); + const pp = document.getElementById('pkPacks'); + if (pp && c.packs && c.packs.length) pp.innerHTML = c.packs.map(p => '
  • ' + VBB.n(p.credits) + ' post credits for ' + money(p.usd) + '
  • ').join(''); + const lk = document.getElementById('pkLook'); if (lk && c.lookUsd) lk.textContent = money(c.lookUsd) + ' per banner'; })(); diff --git a/public/assets/vbb.css b/public/assets/vbb.css index f7e8e9a..eec9724 100644 --- a/public/assets/vbb.css +++ b/public/assets/vbb.css @@ -128,9 +128,16 @@ tr:nth-child(2) .rank{background:var(--amber);color:var(--hot-ink)} .mine .item .s a{word-break:break-all} .pill{display:inline-block;font:700 11px/1 var(--mono);letter-spacing:.06em;text-transform:uppercase;padding:4px 8px;border-radius:999px;margin-bottom:5px} .pill.queued{background:var(--sky-soft);color:var(--sky)} .pill.loop{background:var(--amber-soft);color:var(--amber)} .pill.cycled{background:var(--ok-soft);color:var(--ok)} -.share{display:flex;gap:8px;flex-wrap:wrap}.share input{flex:1;min-width:200px} +.share{display:flex;gap:8px;flex-wrap:wrap}.share input{flex:1;min-width:200px;background:#0a0f2a;border:1px solid var(--line2);border-radius:10px;padding:11px 12px;color:var(--ink);font:14px var(--mono)} .soon{border:1.5px dashed var(--line2);border-radius:var(--r);padding:26px 20px;text-align:center} .soon .tag{display:inline-block;font:700 12px var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--hot);background:var(--hot-soft);padding:5px 10px;border-radius:999px;margin-bottom:10px} +/* packages + prizes */ +.pk{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:14px;margin-top:6px} +.pk .card{margin:0} +.pk-price{font:900 24px/1.15 var(--disp);color:var(--amber);margin:4px 0} +.pk-list{list-style:none;padding:0;margin:6px 0}.pk-list li{font:700 16px/1.5 var(--body)} +.tag-soon{display:inline-block;font:700 11px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--hot);background:var(--hot-soft);padding:4px 9px;border-radius:999px;margin-top:6px} +.pz{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px} /* footer + toasts */ footer.foot{margin-top:48px;padding:28px 0 40px;border-top:1px solid var(--line);color:var(--muted);font-size:13.5px;text-align:center} footer.foot a{color:var(--muted)} footer.foot p{margin:6px 0} diff --git a/public/how.html b/public/how.html index 9b38d7d..3721154 100644 --- a/public/how.html +++ b/public/how.html @@ -22,7 +22,7 @@ - +
    diff --git a/public/index.html b/public/index.html index c056125..babf2ab 100644 --- a/public/index.html +++ b/public/index.html @@ -23,7 +23,7 @@ - +
    diff --git a/public/leaders.html b/public/leaders.html index 91f7b5d..7610400 100644 --- a/public/leaders.html +++ b/public/leaders.html @@ -22,16 +22,17 @@ - +
    This week

    Weekly leaderboards

    Monday to Sunday, Central time. Only verified visitors count: a real browser, on the page a few seconds, once a day per visitor.

    +

    Most visitors sent

    Most traffic sources

    Different websites your visitors came from (the referring site), so spreading your link widely counts.

    - + diff --git a/public/my.html b/public/my.html index 2a864da..9651df2 100644 --- a/public/my.html +++ b/public/my.html @@ -22,7 +22,7 @@ - +
    diff --git a/public/packages.html b/public/packages.html index 9cc3c53..e41219d 100644 --- a/public/packages.html +++ b/public/packages.html @@ -22,7 +22,7 @@ - +
    @@ -30,13 +30,17 @@
    Coming soon

    One-time purchases. Never a subscription.

    -

    Every package will be a single purchase you make once. Nothing renews, nothing bills you again.

    -

    Until packages open, every member gets one free post credit each day they sign in.

    - +

    Every package will be a single purchase you make once. Nothing renews, nothing bills you again. Here is what is planned.

    +
    +

    Post credit packs

    • 10 post credits for $3
    • 40 post credits for $10

    Each credit posts one banner into the loop.

    Coming soon
    +

    Banner look

    $2 per banner

    A border and a hover teaser that make your banner stand out in the loop.

    Coming soon
    +

    Tokens

    Network visits

    Each token is a visit to your site from the network, at the InstantAdPay visit rate.

    Coming soon
    +
    +

    Until packages open, every member gets one free post credit each day they sign in.

    Use my free credit
    - + diff --git a/qa/smoke.mjs b/qa/smoke.mjs new file mode 100644 index 0000000..c94cf01 --- /dev/null +++ b/qa/smoke.mjs @@ -0,0 +1,286 @@ +// 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, and page renders. +// Nothing leaves this machine: the network lookup is off, 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'); +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: '', + NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid' }); +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() { + const w = ethers.Wallet.createRandom(); const c = client(); + const ch = await c.json('/api/auth/challenge', { address: w.address }); + const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) }); + c.address = w.address.toLowerCase(); c.ok = v.ok === true && !!c.jar['vbb.sid']; + return c; +} +async function upload(c, buf) { const r = await c.req('/api/my/upload', { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: buf }); return Object.assign({ _status: r.status }, await r.json()); } +async function postBanner(c, seed, link) { const u = await upload(c, png(125, 125, seed)); return c.json('/api/my/banners', { img: u.img, link: link || 'https://example-member.com/offer?id=' + seed }); } +// one verified visit: ticket, wait, seen +async function visit(c, o = {}) { + const s = await c.json('/api/visit/start', { ref: o.ref || '', src: o.src || '' }); + if (!s.ticket) return { counted: false, why: 'no-ticket', start: s }; + await sleep(o.wait != null ? o.wait : 2100); + return Object.assign({ start: s }, await c.json('/api/visit/seen', { ticket: s.ticket, visibleMs: o.visibleMs != null ? o.visibleMs : 2100 })); +} + +async function main() { + const appBusy = await fetch(BASE).then(() => true, () => false); + if (appBusy) throw new Error('port ' + PORT + ' is already in use; set SMOKE_APP_PORT'); + console.log('data dir', DATA); + + console.log('1. copy rules (no em dashes, no MetaMask recommendation, no income promises)'); + const pub = path.join(APP, 'public'); + const files = fs.readdirSync(pub).filter(f => f.endsWith('.html')).map(f => path.join(pub, f)).concat(fs.readdirSync(path.join(pub, 'assets')).filter(f => /\.(js|css)$/.test(f) && f !== 'wallet.js').map(f => path.join(pub, 'assets', f))); + const texts = files.map(f => [path.basename(f), fs.readFileSync(f, 'utf8')]); + ok(texts.every(([, t]) => !/[\u2014\u2013]/.test(t)), 'no em or en dashes in any page or script', texts.filter(([, t]) => /[\u2014\u2013]/.test(t)).map(x => x[0])); + const html = texts.filter(([n]) => n.endsWith('.html')).map(x => x[1]).join('\n'); + ok(!/metamask/i.test(html), 'pages never name MetaMask'); + ok(/SafePal or any other crypto wallet/.test(html), 'wallet copy says "SafePal or any other crypto wallet"'); + ok(!/passive income|guaranteed (income|returns|profit)|earn (cash|money)|make money/i.test(html), 'no income promises in page copy'); + ok(/never a subscription/i.test(html), 'packages page says never a subscription'); + + console.log('2. boot (prototype mode, temp data dir)'); + await boot(); + const cfg = await (await fetch(BASE + '/api/config')).json(); + ok(cfg.loopSize === 5 && cfg.perShift === 3 && cfg.viewsPerCycle === 150 && cfg.visitSeconds === 2, 'config from env', cfg); + ok(fs.readFileSync(path.join(OUT, 'server.log'), 'utf8').includes('files (prototype mode)'), 'server says prototype mode (no DOCSTORE_URL)'); + ok(JSON.stringify(cfg.packs) === '[{"credits":10,"usd":3},{"credits":40,"usd":10}]' && cfg.lookUsd === 2 && cfg.freeCreditsPerDay === 1, 'approved defaults: packs 10 for $3 + 40 for $10, look $2, 1 free credit a day', cfg); + ok(JSON.stringify(cfg.prizes) === '{"visitors":[15,7,3],"sources":[15,7,3]}', 'approved weekly prizes: $15/$7/$3 per leaderboard', cfg.prizes); + + console.log('3. splash'); + const anon = client(); + let r = await anon.req('/'); + const home = await r.text(); + ok(r.status === 200 && /Viral Banner Blitz/.test(home) && /id="loop"/.test(home) && /id="bar"/.test(home), 'GET / serves the splash (loop grid + shift bar)'); + ok(!r.headers.get('x-frame-options'), 'splash stays frameable (traffic exchanges)'); + ok(/og:image" content="https:\/\/viralbannerblitz\.com\/art\/og-share\.png/.test(home) && /application\/ld\+json/.test(home), 'splash has Open Graph + JSON-LD'); + let sp = await anon.json('/api/splash'); + ok(sp.loopSize === 5 && sp.perShift === 3 && sp.progress === 0 && sp.loop.length === 0 && sp.waiting === 0, 'empty loop at start', sp); + for (const pth of ['/leaders', '/how', '/packages', '/robots.txt', '/sitemap.xml', '/art/mark.svg', '/assets/vbb.css', '/assets/splash.js']) { r = await anon.req(pth); ok(r.status === 200, 'GET ' + pth + ' 200', r.status); } + r = await anon.req('/my'); ok(r.status === 200 && r.headers.get('x-frame-options') === 'DENY', '/my served, never framed'); + r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in'); + + console.log('4. members: wallet sign-in and network sign-in'); + const A = await walletMember(); + ok(A.ok, 'wallet signature sign-in sets a session'); + let my = await A.json('/api/my'); + ok(my.credits === 1 && my.freeToday === true, 'first sign-in of the day: one free post credit', my); + my = await A.json('/api/my'); ok(my.credits === 1 && my.grantedNow === false, 'no second free credit the same day'); + const bad = client(); const w0 = ethers.Wallet.createRandom(), w1 = ethers.Wallet.createRandom(); + const ch0 = await bad.json('/api/auth/challenge', { address: w0.address }); + const v0 = await bad.json('/api/auth/verify', { address: w0.address, signature: await w1.signMessage(ch0.message) }); + ok(v0._status === 400 && !bad.jar['vbb.sid'], 'signature from another wallet is refused'); + // network sign-in from InstantAdPay: /sso/start -> (IAP mints a token) -> /sso/in + const L = client(); const lw = ethers.Wallet.createRandom().address.toLowerCase(); + r = await L.req('/sso/start?mode=go&via=iap&to=%2Fmy'); + const loc = r.headers.get('location') || ''; + ok(r.status === 302 && loc.startsWith('https://iap.invalid/sso/check?st=') && loc.includes('&r=vbb'), 'network sign-in hops to InstantAdPay', loc); + const st = new URL(loc).searchParams.get('st'); + const nsso = require(path.join(APP, 'networksso.js')); + process.env.NETWORK_SSO_SECRET = SSO_SECRET; + const tok = nsso.mint({ iss: 'iap', aud: 'vbb', email: 'leader@example.org', wallet: lw, name: 'smokeleader', st, to: '/my' }); + r = await L.req('/sso/in?t=' + encodeURIComponent(tok)); + ok(r.status === 302 && r.headers.get('location') === '/my' && !!L.jar['vbb.sid'], 'network token signs the member in', { s: r.status, l: r.headers.get('location') }); + r = await L.req('/sso/in?t=' + encodeURIComponent(tok)); ok(!r.headers.get('set-cookie') || !/vbb\.sid=[0-9a-f]{64}/.test(String(r.headers.get('set-cookie'))), 'a network token works only once'); + const me = await L.json('/api/me'); ok(me.signedIn && me.username === 'smokeleader' && me.address === lw, 'network member keeps the network username', me); + my = await L.json('/api/my'); ok(my.credits === 1 && my.share === 'https://viralbannerblitz.com/?ref=smokeleader', 'referral link is ?ref=', my.share); + + console.log('5. posting banners (checks + credits)'); + let u = await upload(A, png(468, 60)); ok(u._status === 400 && /125x125/.test(u.error), 'a 468x60 upload is refused', u); + u = await upload(A, Buffer.concat([png(125, 125), Buffer.alloc(101 * 1024)])); ok(u._status === 400 && /100 KB/.test(u.error), 'an upload over 100 KB is refused', u); + u = await upload(A, Buffer.from('GIF89a not really')); ok(u._status === 400, 'a broken image is refused'); + u = await upload(A, png(250, 250)); ok(u._status === 200 && /^\/u\/[a-z0-9-]+\.png$/.test(u.img), '250x250 (retina) upload accepted', u); + let p = await A.json('/api/my/banners', { img: u.img, link: 'http://plain-http.com/' }); ok(p._status === 400 && /https/.test(p.error), 'http link refused', p); + p = await A.json('/api/my/banners', { img: u.img, link: 'https://bit.ly/abc' }); ok(p._status === 400 && /shortener/.test(p.error), 'shortener link refused', p); + p = await A.json('/api/my/banners', { img: u.img, link: 'https://192.168.1.10/' }); ok(p._status === 400, 'IP-address link refused', p); + p = await A.json('/api/my/banners', { img: 'http://example-member.com/x.png', link: 'https://example-member.com/' }); ok(p._status === 400 && /https/.test(p.error), 'http image address refused', p); + p = await A.json('/api/my/banners', { img: '/u/00000000-aaaaaaaaaaaa.png', link: 'https://example-member.com/' }); ok(p._status === 400, 'someone else\'s (or a missing) upload is refused', p); + const B1 = await postBanner(A, 1, 'https://example-member.com/offer?id=1'); + ok(B1.ok && B1.banner.state === 'loop' && B1.credits === 0, 'first banner enters the open loop at once and uses the credit', B1); + p = await postBanner(A, 9); ok(p._status === 400 && /no post credits/i.test(p.error), 'no credits left: post refused', p); + // four more members fill the loop (5 places), a sixth waits + const M = [A]; const banners = [B1.banner.id]; + for (let i = 2; i <= 6; i++) { const m = await walletMember(); await m.json('/api/my'); const b = await postBanner(m, i); M.push(m); banners.push(b.banner && b.banner.id); } + sp = await anon.json('/api/splash'); + ok(sp.loop.length === 5 && sp.waiting === 1 && sp.queue[0].id === banners[5], 'loop full (5), sixth banner waits at #1', { loop: sp.loop.map(x => x.id), q: sp.queue.map(x => x.id) }); + ok(sp.loop[0].id === banners[4] && sp.loop[4].id === banners[0], 'newest at the front, first banner at the back (next out)', sp.loop.map(x => x.id)); + my = await M[5].json('/api/my'); ok(my.banners[0].state === 'queued' && my.banners[0].position === 1, 'My Banners shows queued + position', my.banners[0]); + my = await A.json('/api/my'); ok(my.banners[0].state === 'loop' && my.banners[0].place === 5 && my.banners[0].shiftsToRideOut === 1, 'My Banners shows place in the loop', my.banners[0]); + + console.log('6. verified unique visitors -> shifts -> a cycle'); + const botC = client({ ua: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' }); + let s = await botC.json('/api/visit/start', { ref: 'smokeleader' }); ok(!s.ticket, 'bots get no visit ticket'); + const early = client(); let vv = await visit(early, { wait: 300 }); ok(!vv.counted && vv.why === 'early', 'a visit sent before the timer does not count', vv); + const v1c = client(); vv = await visit(v1c, { ref: 'smokeleader', src: 'https://www.exchange-one.com/surf' }); ok(vv.counted && vv.progress === 1, 'verified visitor 1 counts (1/3)', vv); + vv = await visit(v1c, { ref: 'smokeleader' }); ok(!vv.counted && (vv.why === 'already' || vv.start.already), 'the same visitor does not count twice in 24 h', vv); + const [v2c, v3c] = [client(), client()]; + const [x2, x3] = await Promise.all([visit(v2c, { ref: 'smokeleader', src: 'https://exchange-two.net/' }), visit(v3c, { ref: 'smokeleader', src: 'https://exchange-one.com/other' })]); + ok(x2.counted && x3.counted, 'visitors 2 and 3 count', [x2, x3]); + ok([x2, x3].some(x => x.shifted && x.cycled === banners[0]), 'the third visitor shifts the loop and banner #' + banners[0] + ' cycles', [x2, x3]); + sp = await anon.json('/api/splash'); + ok(sp.progress === 0 && sp.waiting === 0 && sp.loop.length === 5 && sp.loop[0].id === banners[5] && !sp.loop.some(t => t.id === banners[0]), 'after the shift: sixth banner at the front, first banner gone, bar reset', { p: sp.progress, loop: sp.loop.map(x => x.id) }); + ok(sp.today.shifts === 1 && sp.today.cycles === 1 && sp.today.visits === 3, 'today counters: 1 shift, 1 cycle, 3 visitors', sp.today); + my = await A.json('/api/my'); + ok(my.banners[0].state === 'cycled' && my.rewards.length === 1 && my.rewards[0].views === 150 && my.rewards[0].status === 'recorded' && my.rewardViews === 150, 'owner sees the cycle: 150 network views recorded', my.rewards); + // per-IP cap: VISITS_PER_IP_DAY=2 distinct browsers on one connection + const shared = '198.51.100.7'; + const sv = []; + for (let i = 0; i < 3; i++) sv.push(client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/' + i })); + const svr = await Promise.all(sv.map(c => visit(c))); + ok(svr.filter(x => x.counted).length === 2 && svr.some(x => x.why === 'ip' || (x.start && x.start.already)), 'only 2 browsers per connection count per day', svr.map(x => [x.counted, x.why])); + // forged X-Forwarded-For prefixes are ignored (rightmost entry = the proxy's) + const forge = client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/forger' }); + const fs1 = await forge.req('/api/visit/start', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Forwarded-For': '1.2.3.4, ' + shared }, body: '{}' }); + ok((await fs1.json()).already === true, 'a forged X-Forwarded-For entry does not make a new visitor'); + sp = await anon.json('/api/splash'); + ok(sp.progress === 2 && !sp.held, 'bar at 2/3 after the shared-connection visits', sp.progress); + // bar full with nobody waiting: it holds; the next post shifts at once + vv = await visit(client()); sp = await anon.json('/api/splash'); + ok(vv.counted && !vv.shifted && sp.progress === 3 && sp.held === true, 'bar full with an empty queue holds (nothing to push in)', { vv, p: sp.progress, held: sp.held }); + const G = await walletMember(); await G.json('/api/my'); + const gb = await postBanner(G, 7); + sp = await anon.json('/api/splash'); + ok(gb.ok && gb.banner.state === 'loop' && sp.progress === 0 && sp.loop[0].id === gb.banner.id && !sp.loop.some(t => t.id === banners[1]), 'a post while the bar is full shifts at once; banner #' + banners[1] + ' cycles', { gb, loop: sp.loop.map(x => x.id) }); + + console.log('7. weekly leaderboard'); + const lb = await anon.json('/api/leaders'); + ok(/^\d{4}-\d{2}-\d{2}$/.test(lb.week), 'week key (Central time Monday)', lb.week); + ok(lb.visitors[0] && lb.visitors[0].name === '@smokeleader' && lb.visitors[0].visitors === 3 && lb.visitors[0].sources === 2, 'top visitors: @smokeleader, 3 visitors, 2 sources', lb.visitors); + ok(lb.sources[0] && lb.sources[0].name === '@smokeleader' && lb.sources[0].sources === 2, 'top sources: @smokeleader with 2 distinct referring sites', lb.sources); + ok(lb.visitors.length === 1, 'visitors with no ref credit nobody', lb.visitors); + my = await L.json('/api/my'); ok(my.week.visitors === 3 && my.week.sources === 2, 'member sees their week (3 visitors, 2 sources)', my.week); + + console.log('8. click relay'); + r = await anon.req('/go/' + banners[2]); ok(r.status === 302 && r.headers.get('location') === 'https://example-member.com/offer?id=3', '/go/ 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'); + + // ---- 12. page renders (Playwright, if installed) ---- + if (!process.env.SKIP_UI && fs.existsSync(PW)) { + console.log('12. 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: \$15 in POL/.test(await pg.textContent('#pz')), name + ': leaderboard page shows the weekly prizes'); + await pg.goto(BASE + '/packages', { waitUntil: 'domcontentloaded' }); await pg.waitForTimeout(400); + const pk = await pg.textContent('#pk'); + ok(/10 post credits for \$3/.test(pk) && /40 post credits for \$10/.test(pk) && /\$2 per banner/.test(pk) && /Coming soon/i.test(pk), name + ': packages page shows the planned prices as coming soon', pk.slice(0, 200)); + ok(!(await pg.$('#pk button, #pk form')), name + ': no purchase controls on the packages page'); + await pg.screenshot({ path: path.join(OUT, 'packages-' + name + '.png'), fullPage: true }); + // My Banners, signed in as the network member (cookie copied from the HTTP client) + await ctx.addCookies([{ name: 'vbb.sid', value: L.jar['vbb.sid'], url: BASE }]); + await pg.goto(BASE + '/my', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 }); + ok((await pg.inputValue('#share')).endsWith('?ref=smokeleader'), name + ': My Banners shows the share link'); + await pg.screenshot({ path: path.join(OUT, 'my-' + name + '.png'), fullPage: true }); + await ctx.close(); + } + ok(errs.length === 0, 'no page errors', errs); + await browser.close(); + } else console.log('12. page renders skipped (SKIP_UI or no Playwright at ' + PW + ')'); + + await stop(); + console.log('\n' + pass + ' passed, ' + fail + ' failed'); + fs.writeFileSync(path.join(OUT, 'smoke.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n'); + process.exit(fail ? 1 : 0); +} +main().catch(e => { console.error('smoke crashed:', e.stack || e.message); fail++; process.exit(1); }); diff --git a/server.js b/server.js index 44a3134..42d8363 100644 --- a/server.js +++ b/server.js @@ -120,7 +120,8 @@ function signedIn(addr, patch) { function grantDaily(m) { const day = store.ctDay(); if (m.freeDay === day) return false; m.freeDay = day; let granted = false; - if (m.credits < C.freeCreditCap) { m.credits++; granted = true; } + const add = Math.min(C.freeCreditsPerDay, Math.max(0, C.freeCreditCap - m.credits)); + if (add > 0) { m.credits += add; granted = true; } store.save(); return granted; } function myData(addr) { @@ -202,7 +203,7 @@ const server = http.createServer(async (req, res) => { if (p === '/api/config' && req.method === 'GET') { return json(res, 200, { site: C.site, siteName: C.siteName, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId, loopSize: C.loopSize, perShift: C.perShift, viewsPerCycle: C.viewsPerCycle, visitSeconds: C.visitSeconds, freeCreditCap: C.freeCreditCap, maxQueued: C.maxQueuedPerMember, - sso: networksso.enabled() }); + freeCreditsPerDay: C.freeCreditsPerDay, packs: C.packs, lookUsd: C.lookUsd, prizes: C.prizes, sso: networksso.enabled() }); } if (p === '/api/splash' && req.method === 'GET') return json(res, 200, loop.view(24), { 'Cache-Control': 'no-store' }); if (p === '/api/leaders' && req.method === 'GET') { @@ -312,7 +313,7 @@ const server = http.createServer(async (req, res) => { if (p === '/api/admin/status' && req.method === 'GET') { const S = store.state(); const L = store.ledger(); const t = store.today(); const byStatus = {}; for (const e of L) byStatus[e.status] = (byStatus[e.status] || 0) + e.views; - return json(res, 200, { day: store.ctDay(), week: store.ctWeek(), config: { loopSize: C.loopSize, perShift: C.perShift, viewsPerCycle: C.viewsPerCycle, visitSeconds: C.visitSeconds, perIpDay: C.perIpDay, freeCreditCap: C.freeCreditCap, maxQueued: C.maxQueuedPerMember }, + return json(res, 200, { day: store.ctDay(), week: store.ctWeek(), config: { split: C.split, packs: C.packs, lookUsd: C.lookUsd, prizes: C.prizes, freeCreditsPerDay: C.freeCreditsPerDay, loopSize: C.loopSize, perShift: C.perShift, viewsPerCycle: C.viewsPerCycle, visitSeconds: C.visitSeconds, perIpDay: C.perIpDay, freeCreditCap: C.freeCreditCap, maxQueued: C.maxQueuedPerMember }, loop: { filled: S.loop.length, size: C.loopSize, ids: S.loop, nextOut: S.loop.length ? S.loop[S.loop.length - 1] : null }, queue: { length: S.queue.length, next: S.queue.slice(0, 20) }, progress: S.progress, held: S.progress >= C.perShift && !S.queue.length, today: { visits: t.visits || 0, shifts: t.shifts || 0, cycles: t.cycles || 0, posts: t.posts || 0, clicks: t.clicks || 0 },