From 9d0dde4b57c4a0258c4700d3eb67be04e6a9944c Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 13 Nov 2026 15:24:34 -0600 Subject: [PATCH] VBB v1 skeleton: off-chain loop engine, verified visitors, members, banners, leaderboards, admin; docstore + networksso from Downline Banners Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 5 + .gitignore | 5 + Dockerfile | 10 + config.js | 41 ++++ docstore.js | 191 +++++++++++++++++++ loop.js | 130 +++++++++++++ networksso.js | 212 +++++++++++++++++++++ package-lock.json | 240 ++++++++++++++++++++++++ package.json | 19 ++ public/admin.html | 41 ++++ public/art/mark.svg | 10 + public/art/tile-fallback.svg | 5 + public/assets/admin.js | 25 +++ public/assets/common.js | 61 ++++++ public/assets/leaders.js | 14 ++ public/assets/my.js | 75 ++++++++ public/assets/splash.js | 65 +++++++ public/assets/static.js | 10 + public/assets/vbb.css | 142 ++++++++++++++ public/assets/wallet.js | 199 ++++++++++++++++++++ public/how.html | 55 ++++++ public/index.html | 61 ++++++ public/leaders.html | 37 ++++ public/my.html | 80 ++++++++ public/packages.html | 42 +++++ safety.js | 135 ++++++++++++++ server.js | 353 +++++++++++++++++++++++++++++++++++ store.js | 111 +++++++++++ 28 files changed, 2374 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 config.js create mode 100644 docstore.js create mode 100644 loop.js create mode 100644 networksso.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/admin.html create mode 100644 public/art/mark.svg create mode 100644 public/art/tile-fallback.svg create mode 100644 public/assets/admin.js create mode 100644 public/assets/common.js create mode 100644 public/assets/leaders.js create mode 100644 public/assets/my.js create mode 100644 public/assets/splash.js create mode 100644 public/assets/static.js create mode 100644 public/assets/vbb.css create mode 100644 public/assets/wallet.js create mode 100644 public/how.html create mode 100644 public/index.html create mode 100644 public/leaders.html create mode 100644 public/my.html create mode 100644 public/packages.html create mode 100644 safety.js create mode 100644 server.js create mode 100644 store.js diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b4456b2 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +node_modules +data +qa/out +.git +.env diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9c03e52 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +data/ +*.log +qa/out/ +.env diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..2375d3f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,10 @@ +FROM node:22-alpine +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev --no-audit --no-fund +COPY . . +RUN mkdir -p /app/data +ENV NODE_ENV=production +ENV PORT=3000 +EXPOSE 3000 +CMD ["node","server.js"] diff --git a/config.js b/config.js new file mode 100644 index 0000000..42844c8 --- /dev/null +++ b/config.js @@ -0,0 +1,41 @@ +// 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. +const path = require('path'); + +let cfg = null; +function get() { + if (cfg) return cfg; + const e = process.env; + 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), + isProd: e.NODE_ENV === 'production', + site: e.SITE_HOST || 'viralbannerblitz.com', + siteName: 'Viral Banner Blitz', + dataDir: e.DATA_DIR || path.join(__dirname, 'data'), + chainId: Number(e.CHAIN_ID || 137), // only used in the wallet sign-in message + picker + chainName: e.CHAIN_NAME || 'Polygon', + publicRpc: e.PUBLIC_RPC || 'https://polygon-bor-rpc.publicnode.com', + walletConnectProjectId: (e.WALLETCONNECT_PROJECT_ID || '').trim(), + // the loop + loopSize: num(e.LOOP_SIZE, 50, 5, 500), // banners on the splash at once + perShift: num(e.VISITORS_PER_SHIFT, 10, 1, 1000), // verified unique visitors per one-place shift + viewsPerCycle: num(e.VIEWS_PER_CYCLE, 150, 0, 100000), // network ad views recorded per completed cycle (not credited in v1) + // verified visitors + visitSeconds: num(e.VISIT_SECONDS, 6, 2, 60), // the page must be visible this long before the visit counts + 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 + 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 + 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(/\/+$/, ''), + // network usernames: ?u= / ?a= -> {address, username}. '' turns the lookup off (local prototype). + networkLookupUrl: e.NETWORK_LOOKUP_URL !== undefined ? String(e.NETWORK_LOOKUP_URL).trim() + : String(e.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '') + '/api/network/member' + }; + return cfg; +} + +module.exports = { get, reset: () => { cfg = null; } }; diff --git a/docstore.js b/docstore.js new file mode 100644 index 0000000..32e14bd --- /dev/null +++ b/docstore.js @@ -0,0 +1,191 @@ +// Database-backed data documents (Marty 2026-11-13, standing rule: "everything database-driven ... files only for early +// prototyping"). Every *.json / *.jsonl data document under DATA_DIR that a module reads or writes with the fs *Sync calls lives +// in MySQL instead of on the volume: table `docs` (name = path relative to DATA_DIR, body LONGTEXT, updated_at). The modules keep +// their code; install() routes their fs calls on those paths to an in-memory copy that init() loads from MySQL at boot, and every +// change is written through to MySQL (coalesced per document, newest body wins, in order, retried until it lands). +// +// One writer at a time: init() claims the `docs_writer` row; an older app copy still running during a deploy finds the row taken +// and stops writing (logged), so it can never put stale data over the new copy's (the 2026-11-13 rotator.json loss). +// First boot: a document missing from MySQL is imported from its file, and the file is renamed .imported- (kept, not +// read again). Files the volume keeps on purpose: KEEP (rebuildable caches, uploads, images, the geo database, queues read by +// listing a folder). The SAME file ships in InstantAdPay, LinkSpin, Downline Banners and VBB. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const KEEP_FILES = new Set(['chain-index.json']); // a rebuildable cache of the blockchain +const KEEP_DIRS = ['uploads', 'geo', 'refuel-pending', 'backups', 'marks', 'kits', 'kitimg']; // binary files, or folders read by listing +const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, renameSync: fs.renameSync, + unlinkSync: fs.unlinkSync, statSync: fs.statSync, appendFileSync: fs.appendFileSync }; + +let ROOT = null, pool = null, ME = crypto.randomBytes(8).toString('hex'), ready = false, writer = true; +const cache = new Map(); // name -> { body: string, at: ms } +const pending = new Map(); // name -> body string | null (delete) +let flushing = false, timer = null; +const stats = { writes: 0, deletes: 0, refused: 0, errors: 0, imported: 0, lastError: null }; + +function nameOf(p) { + if (!ROOT || typeof p !== 'string' || !/\.jsonl?$/i.test(p)) return null; + const abs = path.resolve(p); if (!abs.startsWith(ROOT + path.sep)) return null; + const rel = abs.slice(ROOT.length + 1).split(path.sep).join('/'); + if (KEEP_FILES.has(rel) || KEEP_DIRS.some(d => rel === d || rel.startsWith(d + '/'))) return null; + return rel; +} +const enoent = p => { const e = new Error("ENOENT: no such file or directory, open '" + p + "'"); e.code = 'ENOENT'; e.errno = -2; e.path = p; return e; }; +const enc = o => (typeof o === 'string' ? o : o && o.encoding) || null; + +function put(name, body) { cache.set(name, { body, at: Date.now() }); pending.set(name, body); kick(); } +function drop(name) { cache.delete(name); pending.set(name, null); kick(); } +function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}); }, 300); } + +async function flush() { + if (!pool || flushing || !pending.size) return; + flushing = true; + try { + for (const [name, body] of [...pending]) { + if (pending.get(name) !== body) continue; // replaced while we were busy: the newer body goes next round + if (!writer) { pending.delete(name); stats.refused++; continue; } + const c = await pool.getConnection(); + try { + await c.beginTransaction(); + const [[w]] = await c.query('SELECT owner FROM docs_writer WHERE id = 1 FOR UPDATE'); + if (!w || w.owner !== ME) { await c.rollback(); writer = false; pending.delete(name); stats.refused++; console.error('docstore: another app copy took over writing; this copy stops writing'); continue; } + if (body === null) { await c.query('DELETE FROM docs WHERE name = ?', [name]); stats.deletes++; } + else { await c.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = VALUES(updated_at)', [name, body, Date.now()]); stats.writes++; } + await c.commit(); + if (pending.get(name) === body) pending.delete(name); + } catch (e) { try { await c.rollback(); } catch (x) {} stats.errors++; stats.lastError = String(e.message).slice(0, 200); console.error('docstore write', name, e.message); } + finally { c.release(); } + } + } finally { flushing = false; if (pending.size) setTimeout(() => flush().catch(() => {}), 1000); } +} + +// Route the fs *Sync calls on data documents. Installed before any module runs; until init() the documents read from disk. +function install(dataDir) { + if (ROOT) return; ROOT = path.resolve(dataDir); + fs.readFileSync = function (p, o) { + if (!ready && process.env.DOCSTORE_URL && nameOf(p)) console.error('docstore: read before init', p, new Error().stack.split('\n')[2]); + const n = ready ? nameOf(p) : null; if (!n) return O.readFileSync.apply(fs, arguments); + const d = cache.get(n); if (!d) throw enoent(p); + return enc(o) ? d.body : Buffer.from(d.body, 'utf8'); + }; + fs.existsSync = function (p) { const n = ready ? nameOf(p) : null; return n ? cache.has(n) : O.existsSync.apply(fs, arguments); }; + fs.writeFileSync = function (p, data, o) { + const n = ready ? nameOf(p) : null; if (!n) return O.writeFileSync.apply(fs, arguments); + const flag = o && typeof o === 'object' ? o.flag : null; + const s = Buffer.isBuffer(data) ? data.toString('utf8') : String(data); + put(n, flag && flag[0] === 'a' ? ((cache.get(n) || {}).body || '') + s : s); + }; + fs.appendFileSync = function (p, data) { + const n = ready ? nameOf(p) : null; if (!n) return O.appendFileSync.apply(fs, arguments); + put(n, ((cache.get(n) || {}).body || '') + (Buffer.isBuffer(data) ? data.toString('utf8') : String(data))); + }; + fs.renameSync = function (a, b) { + const nb = ready ? nameOf(b) : null; const na = ready ? nameOf(a) : null; + if (!nb && !na) return O.renameSync.apply(fs, arguments); + let body; + if (na) { const d = cache.get(na); if (!d) throw enoent(a); body = d.body; drop(na); } + else { body = O.readFileSync.call(fs, a, 'utf8'); try { O.unlinkSync.call(fs, a); } catch (e) {} } + if (nb) put(nb, body); else O.writeFileSync.call(fs, b, body); + }; + fs.unlinkSync = function (p) { const n = ready ? nameOf(p) : null; if (!n) return O.unlinkSync.apply(fs, arguments); if (!cache.has(n)) throw enoent(p); drop(n); }; + fs.statSync = function (p, o) { + const n = ready ? nameOf(p) : null; if (!n) return O.statSync.apply(fs, arguments); + const d = cache.get(n); if (!d) { if (o && o.throwIfNoEntry === false) return undefined; throw enoent(p); } + const size = Buffer.byteLength(d.body, 'utf8'); const t = new Date(d.at); + return { size, mtimeMs: d.at, mtime: t, ctime: t, birthtime: t, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false }; + }; +} + +// Connect, claim writing, load every document, import files MySQL does not have yet. Throws if MySQL is unreachable: the app +// must not run on an empty copy. +async function init(opts) { + const url = String(process.env.DOCSTORE_URL || '').trim(); + if (!url) { console.log('docstore: no DOCSTORE_URL, documents stay files (prototype mode)'); return false; } + const mysql = require('mysql2/promise'); + pool = mysql.createPool({ uri: url, connectionLimit: 6, charset: 'utf8mb4' }); + await pool.query('CREATE TABLE IF NOT EXISTS docs (name VARCHAR(190) PRIMARY KEY, body LONGTEXT NOT NULL, updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'); + await pool.query('CREATE TABLE IF NOT EXISTS docs_writer (id TINYINT PRIMARY KEY, owner VARCHAR(40) NOT NULL, at BIGINT NOT NULL) ENGINE=InnoDB'); + await pool.query('INSERT INTO docs_writer (id, owner, at) VALUES (1, ?, ?) ON DUPLICATE KEY UPDATE owner = VALUES(owner), at = VALUES(at)', [ME, Date.now()]); + const [rows] = await pool.query('SELECT name, body, updated_at FROM docs'); + for (const r of rows) cache.set(r.name, { body: r.body, at: Number(r.updated_at) }); + for (const sp of (opts && opts.splits) || []) await openSplit(sp); + // first boot for any document: import its file, then set the file aside + const stamp = new Date().toISOString().slice(0, 10); + const walk = dir => { let out = []; let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) {} for (const e of ents) { const p = path.join(dir, e.name); if (e.isDirectory()) out = out.concat(walk(p)); else out.push(p); } return out; }; + for (const p of walk(ROOT)) { + const n = nameOf(p); if (!n || cache.has(n)) continue; + const body = O.readFileSync.call(fs, p, 'utf8'); + if (/\.json$/i.test(n) && body.trim()) { try { JSON.parse(body); } catch (e) { throw new Error('docstore: ' + n + ' is not valid JSON; fix or move it before switching to MySQL'); } } + await pool.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [n, body, Date.now()]); + const [[got]] = await pool.query('SELECT body FROM docs WHERE name = ?', [n]); + cache.set(n, { body: got.body, at: Date.now() }); stats.imported++; + O.renameSync.call(fs, p, p + '.imported-' + stamp); + } + for (const sp of (opts && opts.splits) || []) await migrateSplit(sp); + ready = true; + console.log('docstore: MySQL documents ready,', cache.size, 'documents,', stats.imported, 'imported from files this boot'); + const shut = () => { flush().catch(() => {}).finally(() => {}); }; + process.once('beforeExit', shut); + return true; +} +// ---- row tables: an ever-growing array (spin-link clicks) is one row per item, never a rewrite of the whole document ---- +// spec { doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }. rows(table) gives the loaded items (oldest +// first); the module inserts / deletes rows itself and saves its document WITHOUT the field. +const ROWS = new Map(); const rowQ = []; let rowBusy = false; +async function openSplit(sp) { + await pool.query('CREATE TABLE IF NOT EXISTS `' + sp.table + '` (id VARCHAR(64) PRIMARY KEY, ts BIGINT NOT NULL, body MEDIUMTEXT NOT NULL, KEY ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'); + const [r] = await pool.query('SELECT body FROM `' + sp.table + '` ORDER BY ts, id'); + ROWS.set(sp.table, r.map(x => JSON.parse(x.body))); +} +async function insertMany(table, items, key, ts) { + for (let i = 0; i < items.length; i += 500) { + const part = items.slice(i, i + 500); + await pool.query('INSERT INTO `' + table + '` (id, ts, body) VALUES ? ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [part.map(x => [String(x[key]), Number(x[ts]) || 0, JSON.stringify(x)])]); + } +} +// first boot: the array still inside the document moves to its table, then the document is saved without it +async function migrateSplit(sp) { + const d = cache.get(sp.doc); if (!d) return; + let obj; try { obj = JSON.parse(d.body); } catch (e) { return; } + const arr = Array.isArray(obj[sp.field]) ? obj[sp.field] : null; if (!arr || !arr.length) return; + await insertMany(sp.table, arr, sp.key, sp.ts); + const [[{ n }]] = await pool.query('SELECT COUNT(*) n FROM `' + sp.table + '`'); + if (n < arr.length) throw new Error('docstore: ' + sp.table + ' holds ' + n + ' rows after moving ' + arr.length + '; stopping before the document is changed'); + const seen = new Set((ROWS.get(sp.table) || []).map(x => String(x[sp.key]))); const merged = (ROWS.get(sp.table) || []).concat(arr.filter(x => !seen.has(String(x[sp.key])))); + merged.sort((a, b) => (Number(a[sp.ts]) || 0) - (Number(b[sp.ts]) || 0)); ROWS.set(sp.table, merged); + obj[sp.field] = []; const body = JSON.stringify(obj); + await pool.query('UPDATE docs SET body = ?, updated_at = ? WHERE name = ?', [body, Date.now(), sp.doc]); cache.set(sp.doc, { body, at: Date.now() }); + console.log('docstore:', arr.length, sp.field, 'moved from', sp.doc, 'to table', sp.table); +} +function rows(table) { return ROWS.get(table) || null; } +function rowOp(op) { if (!pool || !writer) return; rowQ.push(op); if (!rowBusy) runRows(); } +async function runRows() { + rowBusy = true; + try { + while (rowQ.length && writer) { + const op = rowQ[0]; + try { + if (op.del) await pool.query('DELETE FROM `' + op.table + '` WHERE id IN (?)', [op.ids]); + else await pool.query('INSERT INTO `' + op.table + '` (id, ts, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [op.id, op.ts, op.body]); + rowQ.shift(); + } catch (e) { stats.errors++; stats.lastError = String(e.message).slice(0, 200); await new Promise(r => setTimeout(r, 1000)); } + } + } finally { rowBusy = false; } +} +const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) }); +const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); }; +function isOn() { return ready && !!pool; } +// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true. +async function claim(key) { + if (!pool) return true; + await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB'); + const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]); + return r.affectedRows === 1; +} + +// SIGTERM during a deploy: write what is pending, then exit +async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } } +function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); } +module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim }; diff --git a/loop.js b/loop.js new file mode 100644 index 0000000..80646de --- /dev/null +++ b/loop.js @@ -0,0 +1,130 @@ +// The cycle engine. The loop is a list of banner ids, front (index 0) = newest, back = the next to ride out. +// Every `perShift` verified unique visitors the loop shifts one place: the first waiting banner enters at the front and, +// once the loop is full, the banner at the back rides out. That banner has cycled, and its owner's reward (network ad views) +// is recorded in the ledger. While the loop has open places and nobody is waiting, a new banner goes straight in. +// No waiting banner when a shift is due: the bar holds at full and the next posted banner shifts the loop at once. +'use strict'; +const cfgMod = require('./config'); +const store = require('./store'); + +const C = () => cfgMod.get(); +let onCycle = null; +function init(o) { onCycle = (o && o.onCycle) || null; normalize(); } + +// a smaller LOOP_SIZE after a restart: the extra banners at the back ride out (cycle) now, in order +function normalize() { + const S = store.state(); + while (S.loop.length > C().loopSize) cycleOut(S.loop.pop()); + while (S.loop.length < C().loopSize && S.queue.length) enter(S.queue.shift()); +} +function enter(id) { + const S = store.state(); const b = store.banner(id); if (!b) return; + S.loop.unshift(b.id); b.state = 'loop'; b.enteredAt = Date.now(); store.saveBanner(b); +} +function cycleOut(id) { + const b = store.banner(id); if (!b) return null; + b.state = 'cycled'; b.cycledAt = Date.now(); store.saveBanner(b); + const S = store.state(); S.totals.cycles++; S.totals.views += C().viewsPerCycle; store.bump('cycles'); + const m = store.member(b.owner); + const e = store.addLedger({ bannerId: b.id, owner: b.owner, username: (m && m.username) || null, views: C().viewsPerCycle, day: store.ctDay(), status: 'recorded' }); + if (onCycle) try { onCycle(b, e); } catch (x) {} + return e; +} +// one place forward. -> { shifted, cycled: ledger entry | null } +function shift() { + const S = store.state(); + if (!S.queue.length) return { shifted: false, cycled: null }; + enter(S.queue.shift()); + let cycled = null; + while (S.loop.length > C().loopSize) cycled = cycleOut(S.loop.pop()); + S.totals.shifts++; store.bump('shifts'); store.save(); + return { shifted: true, cycled }; +} + +// a new banner (already checked and paid for with a credit) +function post(owner, img, link, via) { + const S = store.state(); + const b = store.addBanner({ owner: String(owner).toLowerCase(), img, link, via: via || 'credit', state: 'queued', clicks: 0 }); + S.totals.posts++; store.bump('posts'); + if (!S.queue.length && S.loop.length < C().loopSize) enter(b.id); + else { S.queue.push(b.id); if (S.progress >= C().perShift) { S.progress = 0; shift(); } } + store.save(); + return b; +} + +// a verified unique visitor arrived. Counting rules (24 hours, IP cap, bots) are checked by the caller via canCount(). +function addProgress() { + const S = store.state(); let res = { shifted: false, cycled: null }; + S.progress = Math.min(C().perShift, S.progress + 1); + if (S.progress >= C().perShift && S.queue.length) { S.progress = 0; res = shift(); } + store.save(); + return res; +} + +// ---- verified visitors: once per visitor key per 24 h, at most perIpDay keys per IP per 24 h ---- +const lastByVk = new Map(), byIp = new Map(); +function rebuildIndex() { + lastByVk.clear(); byIp.clear(); const cut = Date.now() - C().visitWindowHours * 3600000; + for (const v of store.visits()) if (v.at >= cut) { lastByVk.set(v.vk, v.at); (byIp.get(v.iph) || byIp.set(v.iph, []).get(v.iph)).push(v.at); } +} +function canCount(vk, iph) { + const win = C().visitWindowHours * 3600000, now = Date.now(); + const last = lastByVk.get(vk); if (last && now - last < win) return { ok: false, why: 'already' }; + const list = (byIp.get(iph) || []).filter(t => now - t < win); byIp.set(iph, list); + if (list.length >= C().perIpDay) return { ok: false, why: 'ip' }; + return { ok: true }; +} +// -> { counted, why?, shifted, cycled } +function verifiedVisit(o) { + const chk = canCount(o.vk, o.iph); if (!chk.ok) return { counted: false, why: chk.why }; + const now = Date.now(); + lastByVk.set(o.vk, now); (byIp.get(o.iph) || byIp.set(o.iph, []).get(o.iph)).push(now); + if (lastByVk.size > 200000) rebuildIndex(); + store.addVisit({ at: now, vk: o.vk, iph: o.iph, ref: o.ref || null, src: o.src || '', wk: store.ctWeek(now), day: store.ctDay(now) }); + store.state().totals.visits++; store.bump('visits'); + const r = addProgress(); + return Object.assign({ counted: true }, r); +} + +// ---- weekly leaderboards (Central time, Monday to Sunday) ---- +let lbCache = null; +function leaders(week, n) { + const wk = week || store.ctWeek(); n = n || 10; + if (lbCache && lbCache.wk === wk && Date.now() - lbCache.at < 15000 && lbCache.n === store.visits().length) return lbCache.out; + const per = new Map(); + for (const v of store.visits()) { + if (v.wk !== wk || !v.ref) continue; + const p = per.get(v.ref) || per.set(v.ref, { address: v.ref, visitors: 0, sources: new Set() }).get(v.ref); + p.visitors++; if (v.src) p.sources.add(v.src); + } + const rows = [...per.values()].map(p => { const m = store.member(p.address); return { address: p.address, username: (m && m.username) || null, visitors: p.visitors, sources: p.sources.size }; }); + const out = { week: wk, + visitors: rows.slice().sort((a, b) => b.visitors - a.visitors || b.sources - a.sources).slice(0, n), + sources: rows.filter(r => r.sources > 0).sort((a, b) => b.sources - a.sources || b.visitors - a.visitors).slice(0, n) }; + lbCache = { wk, at: Date.now(), n: store.visits().length, out }; + return out; +} +function memberWeek(addr) { + const a = String(addr).toLowerCase(), wk = store.ctWeek(); let visitors = 0; const src = new Set(); + for (const v of store.visits()) if (v.wk === wk && v.ref === a) { visitors++; if (v.src) src.add(v.src); } + return { week: wk, visitors, sources: src.size, sourceHosts: [...src].slice(0, 50) }; +} + +// ---- views for pages ---- +function tile(b) { const m = store.member(b.owner); return { id: b.id, img: b.img, href: '/go/' + b.id, owner: (m && m.username) ? '@' + m.username : null }; } +function view(queueShow) { + const S = store.state(); + return { loopSize: C().loopSize, perShift: C().perShift, progress: S.progress, waiting: S.queue.length, + loop: S.loop.map(id => store.banner(id)).filter(Boolean).map(tile), + queue: S.queue.slice(0, queueShow || 24).map(id => store.banner(id)).filter(Boolean).map(tile), + held: S.progress >= C().perShift && !S.queue.length, today: store.today(), totals: S.totals }; +} +// where a member's banner stands +function placeOf(b) { + const S = store.state(); + if (b.state === 'queued') { const i = S.queue.indexOf(b.id); return { state: 'queued', position: i + 1, of: S.queue.length }; } + if (b.state === 'loop') { const i = S.loop.indexOf(b.id); return { state: 'loop', place: i + 1, of: C().loopSize, shiftsToRideOut: Math.max(1, C().loopSize - i) }; } + return { state: b.state }; +} + +module.exports = { init, post, shift, verifiedVisit, canCount, rebuildIndex, leaders, memberWeek, view, placeOf, normalize }; diff --git a/networksso.js b/networksso.js new file mode 100644 index 0000000..28026f0 --- /dev/null +++ b/networksso.js @@ -0,0 +1,212 @@ +// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each +// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes. +// +// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider). +// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st), +// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P. +// 2. P GET /sso/check?st=&to=/path P looks at its OWN member session (never the admin portal). Signed in: +// P mints a token bound to R, the state and the email, and sends the browser +// to R /sso/in?t=. Not signed in: R /sso/in?none=1&to=/path. +// 3. R GET /sso/in?t= R checks signature, audience, expiry (60 s), the state against its cookie +// (so nobody can push their own token into someone else's browser), and spends +// the nonce (a second use is refused). The email must already be a member +// here; then R makes an ordinary session and redirects to the relative path. +// Outbound links: P GET /go/?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the +// secret not set), it is a plain redirect to the other site, so it is always safe to link through. +// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie +// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link), +// bots and non-page fetches never bounce. +// Token: "v1..", JSON = { iss, aud, email, +// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it. +// +// Wallet sites (Downline Banners, 2026-11-13, Marty: "sign in once and be logged into all these sites"). Downline Banners has no email +// accounts; its members are wallets. IAP and LinkSpin list it under `wallets: { bannerline: base }` and vouch one way: /go/bannerline +// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet +// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from +// either, and makes a session for that wallet. /sso/start?via= picks which site to ask; old copies ignore the new parameters. +'use strict'; +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim(); +const enabled = () => SECRET().length >= 32; +const TTL = 60 * 1000; // token life +const SKEW = 30 * 1000; // clock skew allowed between the two servers +const STATE_AGE = 300; // seconds: the state cookie +const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes +const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site +const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet +const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz' }; // vbb added 2026-11-13 (VBB app); copy this line to the other repos when IAP + LinkSpin list vbb under wallets +const WALLET_RE = /^0x[0-9a-f]{40}$/; + +let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath, + // wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } } + +const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); +const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64'); +const mac = s => crypto.createHmac('sha256', SECRET()).update('nsso.v1.' + s).digest(); +const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2'); +const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || ''); + +// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters. +function safePath(to, dflt) { + const d = dflt == null ? '/' : dflt; + const s = String(to == null ? '' : to); + if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d; + try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; } +} + +function mint(o) { + const now = o.now || Date.now(); + const t = { iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') }; + if (o.wallet) t.wallet = String(o.wallet).toLowerCase(); + if (o.name) t.name = String(o.name).slice(0, 40); + const body = b64u(JSON.stringify(t)); + return 'v1.' + body + '.' + b64u(mac(body)); +} + +// -> { ok, email, to, n, exp } or { error: reason } +function verify(tok, o) { + if (!enabled()) return { error: 'off' }; + const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || '')); + if (!m) return { error: 'malformed' }; + const want = mac(m[1]), got = unb64u(m[2]); + if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' }; + let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; } + const now = (o && o.now) || Date.now(); + if (!p || p.aud !== o.aud || ![].concat(o.iss).includes(p.iss)) return { error: 'audience' }; + if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' }; + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' }; + if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' }; + const st = String((o && o.st) || ''); + if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' }; + if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' }; + const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null; + return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) }; +} + +// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it), +// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window). +const used = new Map(); let fileLoaded = false, tableReady = null; +const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null; +function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); } +function loadFile() { + if (fileLoaded) return; fileLoaded = true; + try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {} +} +function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } } +async function spend(n, exp) { + const now = Date.now(); loadFile(); prune(now); + if (used.has(n)) return false; + used.set(n, Number(exp) + SKEW); saveFile(); + const db = C && C.db; + if (db && db.enabled && db.enabled()) { + try { + if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; }); + await tableReady; + await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]); + if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {}); + } catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed + } + return true; +} + +// crawlers, link previews and headless browsers never bounce +const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i; +const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); }; +// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser) +const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; }; + +function cookies(req) { + const out = {}; + for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } + return out; +} +const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : ''); +const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; }; +const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; }; + +function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); } + +// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in) +const offCookie = () => ck('nsso.off', '1', OFF_AGE, true); + +// -> true when the request was one of ours and has been answered +async function handle(req, res, u) { + if (!C || req.method !== 'GET') return false; + const p = u.pathname; + const peerName = NAMES[C.peer] || C.peer; + const goTo = p.startsWith('/go/') ? p.slice(4) : ''; + const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null); + if (goTo && (goTo === C.peer || walletBase(goTo))) { + const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)(); + const to = safePath(u.searchParams.get('to'), '/'); + const plain = base + to; + if (!enabled() || isBot(req)) return go(res, plain); + let s = null; try { s = await C.member(req); } catch (e) {} + if (!s || !s.email) return go(res, plain); + if (goTo !== C.peer) { let w = null; try { w = await C.wallet(s); } catch (e) {} if (!w || !w.address) return go(res, plain); } // no wallet to vouch for: a plain link + return go(res, base + '/sso/start?mode=go' + (goTo === C.peer ? '' : '&via=' + C.self) + '&to=' + encodeURIComponent(to)); + } + if (p === '/sso/start') { + const to = safePath(u.searchParams.get('to'), C.defaultPath); + const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check'; + const via = String(u.searchParams.get('via') || ''); + const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider + if (!enabled() || isBot(req) || notPage(req)) return go(res, to); + let s = null; try { s = await C.member(req); } catch (e) {} + if (s && (s.email || s.address)) return go(res, to); // already signed in here + const c = cookies(req); + if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to); + const st = crypto.randomBytes(16).toString('hex'); + const set = [ck('nsso.st', st, STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)]; + if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true)); + return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to), set); + } + if (p === '/sso/check') { + const st = String(u.searchParams.get('st') || ''); + const to = safePath(u.searchParams.get('to'), '/'); + const r = String(u.searchParams.get('r') || ''); + const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet + const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud; + const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to); + if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none); + let s = null; try { s = await C.member(req); } catch (e) {} + if (!s || !s.email) { log('check: not signed in here', null, 'for ' + forName); return go(res, none); } + let w = null; + if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } } + log('token issued', s.email, 'for ' + forName); + return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to })); + } + if (p === '/sso/in') { + const c = cookies(req); + const set = [ck('nsso.st', '', 0, true)]; + if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); } + const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] }); + if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); } + if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); } + let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; } + if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in + log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email); + set.push(ck('nsso.hint', v.email, HINT_AGE, true)); + return go(res, C.signinPath(v.to), set); + } + let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); } + if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); } + set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true)); + log('signed in from ' + (NAMES[v.iss] || peerName), v.email); + return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13) + } + if (p === '/api/sso/status') { + const c = cookies(req); const set = []; + let s = null; try { s = await C.member(req); } catch (e) {} + const signedIn = !!(s && (s.email || s.address)); + const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] }; + if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); } + return sendJson(res, out, set); + } + return false; +} + +module.exports = { init, handle, enabled, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES }; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..a5c709f --- /dev/null +++ b/package-lock.json @@ -0,0 +1,240 @@ +{ + "name": "vbb", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "vbb", + "version": "0.1.0", + "dependencies": { + "ethers": "^6.13.0", + "mysql2": "^3.11.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", + "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", + "license": "MIT" + }, + "node_modules/@noble/curves": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.2.0.tgz", + "integrity": "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.2" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz", + "integrity": "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@types/node": { + "version": "22.7.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz", + "integrity": "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/aes-js": { + "version": "4.0.0-beta.5", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.5.tgz", + "integrity": "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q==", + "license": "MIT" + }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ethers": { + "version": "6.17.0", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.17.0.tgz", + "integrity": "sha512-BpyrpIPJ3ydEVow8zGaz1DuPS7YU8DcWxuBnY9a0UA/lvAPwrMr+EPXsfrul628SRaekPNeIM4UFh/91GWZang==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/ethers-io/" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "1.11.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.2", + "@types/node": "22.7.5", + "aes-js": "4.0.0-beta.5", + "tslib": "2.7.0", + "ws": "8.21.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "license": "MIT" + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/lru.min": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.5.tgz", + "integrity": "sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, + "node_modules/mysql2": { + "version": "3.24.6", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz", + "integrity": "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==", + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.2", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.3", + "long": "^5.3.2", + "lru.min": "^1.1.4", + "named-placeholders": "^1.1.6", + "sql-escaper": "^1.5.1" + }, + "engines": { + "node": ">= 8.0" + }, + "peerDependencies": { + "@types/node": ">= 8" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "license": "MIT", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/sql-escaper": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.5.2.tgz", + "integrity": "sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=2.0.0", + "node": ">=12.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" + } + }, + "node_modules/tslib": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", + "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", + "license": "0BSD" + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..2b6f59e --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "vbb", + "version": "0.1.0", + "private": true, + "description": "Viral Banner Blitz (viralbannerblitz.com rebuild): a community banner loop of 125x125 banners that shifts with verified visitors. v1 off-chain.", + "main": "server.js", + "scripts": { + "start": "node server.js", + "dev": "node --watch server.js", + "qa": "node qa/smoke.mjs" + }, + "engines": { + "node": ">=20" + }, + "dependencies": { + "ethers": "^6.13.0", + "mysql2": "^3.11.0" + } +} diff --git a/public/admin.html b/public/admin.html new file mode 100644 index 0000000..f1a8805 --- /dev/null +++ b/public/admin.html @@ -0,0 +1,41 @@ + + + + +Admin | Viral Banner Blitz + + + + + + + + + + + + + + + + + + + + + + +
+

Admin

Loop status and the cycle reward ledger. Rewards are recorded only; nothing is credited yet.

+
+ + +
+ + + + diff --git a/public/art/mark.svg b/public/art/mark.svg new file mode 100644 index 0000000..9875f6d --- /dev/null +++ b/public/art/mark.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/public/art/tile-fallback.svg b/public/art/tile-fallback.svg new file mode 100644 index 0000000..b7b59dc --- /dev/null +++ b/public/art/tile-fallback.svg @@ -0,0 +1,5 @@ + + + Image did + not load + diff --git a/public/assets/admin.js b/public/assets/admin.js new file mode 100644 index 0000000..593ebbc --- /dev/null +++ b/public/assets/admin.js @@ -0,0 +1,25 @@ +// Admin: status + the cycle reward ledger, read with the ADMIN_TOKEN (kept in this tab only). +(function () { + VBB.renderNav(''); + const $ = VBB.$, esc = VBB.esc; + let tok = ''; try { tok = sessionStorage.getItem('vbb.admin') || ''; } catch (e) {} + const get = u => VBB.getJSON(u, { headers: { 'x-admin-token': tok } }); + async function open() { + const s = await get('/api/admin/status'); + if (s.error) { VBB.status('That token was not accepted.', 'err'); return; } + try { sessionStorage.setItem('vbb.admin', tok); } catch (e) {} + $('tokCard').hidden = true; $('adm').hidden = false; VBB.status(''); + $('aStats').innerHTML = [['Loop filled', s.loop.filled + ' / ' + s.loop.size], ['Waiting', s.queue.length], ['Next shift', s.progress + ' / ' + s.config.perShift + (s.held ? ' (held)' : '')], + ['Shifts today', s.today.shifts], ['Cycles today', s.today.cycles], ['Visitors today', s.today.visits], ['Cycles total', s.totals.cycles], ['Views recorded', VBB.n(s.ledger.views)], ['Views credited', VBB.n(s.ledger.credited)], ['Members', s.members]] + .map(x => '
' + esc(x[1]) + '' + esc(x[0]) + '
').join(''); + $('aRaw').textContent = JSON.stringify(s, null, 2); + const l = await get('/api/admin/ledger?n=300'); + const who = r => r.username ? '@' + r.username : VBB.short(r.address || r.owner); + $('aMembers').innerHTML = l.members && l.members.length ? '' + l.members.map(m => '').join('') + '
MemberCyclesViews
' + esc(who(m)) + '' + m.cycles + '' + VBB.n(m.views) + '
' : '

No cycles yet.

'; + $('aLedger').innerHTML = l.entries && l.entries.length ? '' + + l.entries.map(e => '').join('') + '
When (CT)EntryBannerMemberViewsStatus
' + esc(new Date(e.at).toLocaleString('en-US', { timeZone: 'America/Chicago' })) + '' + esc(e.id) + '#' + e.bannerId + '' + esc(who(e)) + '' + VBB.n(e.views) + '' + esc(e.status) + '
' : '

The ledger is empty.

'; + } + $('tokBtn').onclick = () => { tok = $('tok').value.trim(); open(); }; + $('tok').addEventListener('keydown', e => { if (e.key === 'Enter') $('tokBtn').click(); }); + if (tok) open(); +})(); diff --git a/public/assets/common.js b/public/assets/common.js new file mode 100644 index 0000000..ca9ffb9 --- /dev/null +++ b/public/assets/common.js @@ -0,0 +1,61 @@ +// Shared page helpers (VBB namespace, modelled on Downline Banners' common.js): nav, footer, toasts, fetch helpers. +window.VBB = (function () { + let cfgP = null; + const $ = id => document.getElementById(id); + const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + const getConfig = () => cfgP || (cfgP = fetch('/api/config').then(r => r.json())); + const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : ''; + const framed = (() => { try { return window.top !== window.self; } catch (e) { return true; } })(); + function status(msg, cls) { const el = $('status'); if (!el) return; el.hidden = !msg; el.className = 'note ' + (cls || ''); el.textContent = msg || ''; } + async function getJSON(url, opts) { const r = await fetch(url, opts); let j = {}; try { j = await r.json(); } catch (e) {} if (!r.ok && !j.error) j.error = 'Request failed (' + r.status + ')'; return j; } + const post = (url, body) => getJSON(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) }); + const n = x => Number(x || 0).toLocaleString('en-US'); + + function renderNav(active) { + const nav = document.createElement('nav'); nav.className = 'top'; + const links = [['/', 'The loop'], ['/leaders', 'Leaderboards'], ['/how', 'How it works'], ['/packages', 'Packages'], ['/my', 'My Banners']]; + nav.innerHTML = ''; + document.body.prepend(nav); + // inside a traffic-exchange frame, the member page opens in a new tab + if (framed) document.querySelectorAll('nav a[href="/my"]').forEach(a => { a.target = '_blank'; a.rel = 'noopener'; }); + } + function renderFooter() { + const f = document.createElement('footer'); f.className = 'foot'; + f.innerHTML = '

Viral Banner Blitz, part of the Crypto Team Build Network

' + + '

A banner that cycles earns advertising across the network, not cash. Nothing here is an income opportunity.

' + + '

The loop · Leaderboards · How it works · Packages · My Banners

'; + document.body.appendChild(f); + toasts(); + } + // live cycle toasts: real cycles from the ledger only, bottom-left, one at a time, never older than 30 minutes + let toastsOn = false; + function toasts() { + if (toastsOn) return; toastsOn = true; + const seen = new Set(); let first = true; + const box = document.createElement('div'); box.className = 'toasts'; box.setAttribute('aria-live', 'polite'); document.body.appendChild(box); + const show = c => { + const el = document.createElement('a'); el.className = 'toast'; el.href = '/how'; + el.innerHTML = '' + (c.name ? esc(c.name) + '\'s banner' : 'A banner') + ' just cycled
' + n(c.views) + ' network ad views earned for its owner'; + box.appendChild(el); requestAnimationFrame(() => el.classList.add('in')); + setTimeout(() => { el.classList.remove('in'); setTimeout(() => el.remove(), 400); }, 7000); + }; + const tick = async () => { + let d; try { d = await getJSON('/api/recent'); } catch (e) { return; } if (!d || !d.cycles) return; + const fresh = d.cycles.filter(c => !seen.has(c.id)); d.cycles.forEach(c => seen.add(c.id)); + const list = first ? fresh.slice(0, 1) : fresh.reverse(); first = false; + list.slice(0, 3).forEach((c, i) => setTimeout(() => show(c), 1500 + i * 8000)); + }; + tick(); setInterval(tick, 25000); + } + function tile(t, extra) { + const a = document.createElement('a'); a.className = 'tile' + (extra && extra.cls ? ' ' + extra.cls : ''); + a.href = t.href; a.target = '_blank'; a.rel = 'noopener'; + a.innerHTML = '' + esc(t.owner ? 'Banner by ' + t.owner : 'Member banner #' + t.id) + '' + + (extra && extra.pos ? '' + esc(extra.pos) + '' : '') + (t.owner ? '' + esc(t.owner) + '' : ''); + const img = a.querySelector('img'); img.src = t.img; img.onerror = () => { img.onerror = null; img.src = '/art/tile-fallback.svg'; }; + return a; + } + return { $, esc, getConfig, short, framed, status, getJSON, post, n, renderNav, renderFooter, tile }; +})(); diff --git a/public/assets/leaders.js b/public/assets/leaders.js new file mode 100644 index 0000000..b4d0978 --- /dev/null +++ b/public/assets/leaders.js @@ -0,0 +1,14 @@ +// Weekly leaderboards: top 10 by verified visitors sent, top 10 by distinct traffic sources (Central time week). +(async function () { + VBB.renderNav('/leaders'); VBB.renderFooter(); + const $ = VBB.$, esc = VBB.esc; + 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' }); + $('weekLbl').textContent = 'Week of Monday ' + wk + ', Central time. Resets every Monday at 12:00 AM. Only verified visitors count: a real browser, on the page a few seconds, once a day per visitor.'; + const table = (rows, main) => rows.length ? '' + + rows.map((r, i) => '').join('') + '
#Member' + (main === 'visitors' ? 'Visitors' : 'Sources') + '' + (main === 'visitors' ? 'Sources' : 'Visitors') + '
' + (i + 1) + '' + esc(r.name) + '' + VBB.n(r[main]) + '' + VBB.n(main === 'visitors' ? r.sources : r.visitors) + '
' + : '

Nobody yet this week. Share your link from My Banners and take the top spot.

'; + $('lbVisitors').innerHTML = table(d.visitors, 'visitors'); + $('lbSources').innerHTML = table(d.sources, 'sources'); +})(); diff --git a/public/assets/my.js b/public/assets/my.js new file mode 100644 index 0000000..2a1c3b4 --- /dev/null +++ b/public/assets/my.js @@ -0,0 +1,75 @@ +// My Banners: sign in (network or wallet), credits, post a banner, banner states, share link, cycle rewards. +(async function () { + VBB.renderNav('/my'); VBB.renderFooter(); + const $ = VBB.$, esc = VBB.esc; + const c = await VBB.getConfig().catch(() => ({})); + const me = await VBB.getJSON('/api/me'); + if (!me.signedIn) { + // signed in on InstantAdPay already? one quick hop there and back signs you in here too + try { const ss = await VBB.getJSON('/api/sso/status'); if (ss && ss.check) { location.replace('/sso/start?mode=check&via=iap&to=' + encodeURIComponent('/my')); return; } } catch (e) {} + $('signin').hidden = false; + if (!c.sso) { $('ssoIap').hidden = true; $('ssoLs').hidden = true; } + $('signBtn').onclick = async () => { + try { VBB.status('Check your wallet for the sign-in message.'); await VBBWallet.signIn(); location.reload(); } + catch (e) { VBB.status(String(e && e.message || e).slice(0, 300), 'err'); } + }; + return; + } + $('outBtn').onclick = async () => { await VBB.post('/api/auth/logout'); location.reload(); }; + + let uploaded = ''; + function preview(src) { const p = $('preview'); p.innerHTML = src ? 'Preview' : '125 x 125
preview'; if (src) p.querySelector('img').src = src; } + $('img').addEventListener('input', () => { uploaded = ''; $('fileNote').textContent = ''; const v = $('img').value.trim(); preview(/^https:\/\//.test(v) ? v : ''); }); + $('file').addEventListener('change', async e => { + const f = e.target.files[0]; if (!f) return; + if (f.size > 100 * 1024) { VBB.status('That file is ' + Math.ceil(f.size / 1024) + ' KB. The limit is 100 KB.', 'err'); return; } + $('fileNote').textContent = 'Uploading...'; + const r = await VBB.getJSON('/api/my/upload', { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: f }); + e.target.value = ''; + if (r.error) { $('fileNote').textContent = ''; VBB.status(r.error, 'err'); return; } + uploaded = r.img; $('img').value = ''; $('fileNote').textContent = 'Uploaded: ' + f.name; preview(r.img); VBB.status(''); + }); + $('postBtn').onclick = async () => { + const img = uploaded || $('img').value.trim(); + if (!img) return VBB.status('Add an image address or upload a file.', 'err'); + $('postBtn').disabled = true; VBB.status('Checking your image and link...'); + const r = await VBB.post('/api/my/banners', { img, link: $('link').value.trim() }); + $('postBtn').disabled = false; + if (r.error) return VBB.status(r.error, 'err'); + uploaded = ''; $('img').value = ''; $('link').value = ''; $('fileNote').textContent = ''; preview(''); + VBB.status(r.banner.state === 'loop' ? 'Posted. Your banner went straight into the loop.' : 'Posted. Your banner is number ' + r.banner.position + ' in line.', 'ok'); + load(); + }; + $('copyBtn').onclick = () => { $('share').select(); try { navigator.clipboard.writeText($('share').value); } catch (e) { document.execCommand('copy'); } VBB.status('Link copied.', 'ok'); }; + + const where = b => b.state === 'queued' ? 'Waiting
Number ' + b.position + ' of ' + b.of + ' in line' + : b.state === 'loop' ? 'In the loop
Place ' + b.place + ' of ' + b.of + ', rides out in about ' + b.shiftsToRideOut + ' shift' + (b.shiftsToRideOut === 1 ? '' : 's') + : 'Cycled
' + (b.cycledAt ? new Date(b.cycledAt).toLocaleString() : ''); + async function load() { + const d = await VBB.getJSON('/api/my'); + if (d.error) return VBB.status(d.error, 'err'); + $('dash').hidden = false; + $('me').textContent = d.username ? '@' + d.username + ' (' + VBB.short(d.address) + ')' : d.address; + const live = d.banners.filter(b => b.state !== 'cycled').length, cyc = d.banners.filter(b => b.state === 'cycled').length; + $('stats').innerHTML = [['Post credits', d.credits], ['Banners waiting or in the loop', live], ['Banners cycled', cyc], ['Network ad views earned', VBB.n(d.rewardViews)]] + .map(x => '
' + esc(x[1]) + '' + esc(x[0]) + '
').join(''); + $('creditNote').textContent = (d.grantedNow ? 'Your free credit for today was just added. ' : d.freeToday ? 'Today\'s free credit is in. ' : '') + + 'One free credit arrives each day you sign in (they bank up to ' + d.freeCreditCap + '). You can have up to ' + d.maxQueued + ' banners waiting at once.'; + $('postBtn').disabled = d.credits < 1; + if (d.credits < 1) VBB.status('You have used your credits. Come back tomorrow for a free one.'); + $('mine').innerHTML = d.banners.length ? '' : '

No banners yet. Post your first one above.

'; + for (const b of d.banners) { + const el = document.createElement('div'); el.className = 'item'; + el.innerHTML = 'Banner #' + b.id + '
' + where(b) + '

' + VBB.n(b.clicks) + ' clicks
'; + el.querySelector('img').src = b.img; const a = el.querySelector('a'); a.href = b.link; a.textContent = b.link.replace(/^https:\/\//, '').slice(0, 60); + $('mine').appendChild(el); + } + $('share').value = d.share; + $('weekStats').innerHTML = [['Verified visitors you sent this week', d.week.visitors], ['Traffic sources this week', d.week.sources]] + .map(x => '
' + esc(x[1]) + '' + esc(x[0]) + '
').join(''); + $('rewards').innerHTML = d.rewards.length ? '' + + d.rewards.map(e => '').join('') + '
WhenBannerNetwork ad viewsStatus
' + esc(new Date(e.at).toLocaleString()) + '#' + e.bannerId + '' + VBB.n(e.views) + '' + (e.status === 'recorded' ? 'Recorded' : esc(e.status)) + '
' + : '

No cycles yet. Your first reward appears when one of your banners rides out of the loop.

'; + } + load(); setInterval(load, 30000); +})(); diff --git a/public/assets/splash.js b/public/assets/splash.js new file mode 100644 index 0000000..7f34fd6 --- /dev/null +++ b/public/assets/splash.js @@ -0,0 +1,65 @@ +// The splash: the loop grid, the next-shift bar, the waiting queue, and this visitor's verified visit. +(async function () { + VBB.renderNav('/'); VBB.renderFooter(); + const $ = VBB.$, esc = VBB.esc; + const c = await VBB.getConfig().catch(() => ({})); + document.querySelectorAll('[data-k=perShift]').forEach(el => { el.textContent = c.perShift || 10; }); + document.querySelectorAll('[data-k=views]').forEach(el => { el.textContent = VBB.n(c.viewsPerCycle || 150); }); + + let lastLoop = null, known = new Set(), firstPaint = true; + function render(d) { + const pct = Math.min(100, Math.round(d.progress / d.perShift * 100)); + $('prog').innerHTML = d.progress + ' / ' + d.perShift + ''; + $('bar').style.width = pct + '%'; $('barWrap').setAttribute('aria-valuemax', d.perShift); $('barWrap').setAttribute('aria-valuenow', d.progress); + $('progLbl').textContent = d.held ? 'bar full: the next banner posted shifts the loop' : 'verified visitors toward the next shift'; + const t = d.today || {}; + $('today').textContent = VBB.n(t.shifts) + ' shifts and ' + VBB.n(t.cycles) + ' cycles today'; + // the loop + const ids = d.loop.map(x => x.id).join(','); + if (ids !== lastLoop) { + lastLoop = ids; const g = $('loop'); g.innerHTML = ''; + const full = d.loop.length >= d.loopSize; + d.loop.forEach((t, i) => { + const last = full && i === d.loop.length - 1; + const el = VBB.tile(t, { pos: last ? 'NEXT OUT' : String(i + 1), cls: (last ? 'next' : '') + (!firstPaint && !known.has(t.id) ? ' fresh' : '') }); + g.appendChild(el); known.add(t.id); + }); + for (let i = d.loop.length; i < d.loopSize; i++) { + const a = document.createElement('a'); a.className = 'tile open'; a.href = '/my'; + a.innerHTML = '+Open place
post yours'; g.appendChild(a); + } + firstPaint = false; + } + $('loopInfo').textContent = d.loop.length + ' of ' + d.loopSize + ' places filled'; + // the queue + const q = $('queue'); q.innerHTML = ''; + d.queue.forEach((t, i) => q.appendChild(VBB.tile(t, { pos: '#' + (i + 1) }))); + $('queueEmpty').hidden = d.waiting > 0; + $('queueInfo').textContent = d.waiting ? VBB.n(d.waiting) + ' waiting' + (d.waiting > d.queue.length ? ', first ' + d.queue.length + ' shown' : '') : ''; + } + async function load() { const d = await VBB.getJSON('/api/splash'); if (!d.error) render(d); } + await load(); setInterval(load, 8000); + + // ---- this visit: a ticket now, redeemed once the page has been visible for visitSeconds ---- + const note = $('visitNote'); + const qs = new URLSearchParams(location.search); + const src = document.referrer || ''; // inside a traffic-exchange frame this is the exchange: the traffic source + const start = await VBB.post('/api/visit/start', { ref: qs.get('ref') || '', src }).catch(() => ({})); + if (!start || !start.ticket) { note.textContent = 'Share the loop: every verified visitor moves it forward.'; return; } + if (start.already) { note.textContent = 'Your visit already counted today. Thanks for pushing the loop.'; note.className = 'visit-note ok'; return; } + const need = (start.seconds || 6) * 1000; + let visible = 0, since = document.visibilityState === 'visible' ? Date.now() : 0, sent = false; + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') since = Date.now(); + else if (since) { visible += Date.now() - since; since = 0; } + }); + const timer = setInterval(async () => { + const v = visible + (since ? Date.now() - since : 0); + const left = Math.max(0, Math.ceil((need - v) / 1000)); + if (left > 0) { note.textContent = 'Your visit counts toward the next shift in ' + left + ' second' + (left === 1 ? '' : 's') + '.'; return; } + if (sent) return; sent = true; clearInterval(timer); + const r = await VBB.post('/api/visit/seen', { ticket: start.ticket, visibleMs: v }).catch(() => ({})); + if (r.counted) { note.className = 'visit-note ok'; note.textContent = r.shifted ? 'Counted, and your visit shifted the loop!' : 'Counted. You pushed the loop one step closer to the next shift.'; load(); } + else note.textContent = r.why === 'already' ? 'Your visit already counted today. Thanks for pushing the loop.' : 'Thanks for visiting the loop.'; + }, 500); +})(); diff --git a/public/assets/static.js b/public/assets/static.js new file mode 100644 index 0000000..9c1ece7 --- /dev/null +++ b/public/assets/static.js @@ -0,0 +1,10 @@ +// How it works + Packages: nav, footer, and the live config numbers. +(async function () { + const page = location.pathname.replace(/\/$/, '') || '/'; + VBB.renderNav(page); VBB.renderFooter(); + const c = await VBB.getConfig().catch(() => ({})); + const set = (k, v) => document.querySelectorAll('[data-k=' + k + ']').forEach(el => { el.textContent = v; }); + if (c.perShift) set('perShift', c.perShift); + if (c.viewsPerCycle != null) set('views', VBB.n(c.viewsPerCycle)); + if (c.visitSeconds) set('secs', c.visitSeconds); +})(); diff --git a/public/assets/vbb.css b/public/assets/vbb.css new file mode 100644 index 0000000..f7e8e9a --- /dev/null +++ b/public/assets/vbb.css @@ -0,0 +1,142 @@ +/* Viral Banner Blitz. Own look (2026-11-13): midnight navy, signal orange and amber, Archivo + Figtree. + Not the InstantAdPay mint, not the Downline Banners ultraviolet + lime. Neutral class names (no "ad"/"banner" words: + ad blockers hide elements with those). */ +:root{ + --bg:#0b1030;--bg2:#10173f;--panel:#141c4a;--panel2:#1a2358;--ink:#f6f2e8;--muted:#a9b0d4;--faint:#7a83b3; + --line:rgba(255,255,255,.09);--line2:rgba(255,255,255,.16); + --hot:#ff5b2e;--hot-ink:#1a0800;--hot-soft:rgba(255,91,46,.14);--amber:#ffb000;--amber-soft:rgba(255,176,0,.13); + --sky:#5cc8ff;--sky-soft:rgba(92,200,255,.13);--ok:#3ddc97;--ok-soft:rgba(61,220,151,.13);--bad:#ff6b6b;--bad-soft:rgba(255,107,107,.13); + --disp:"Archivo","Arial Black",system-ui,sans-serif;--body:"Figtree","Segoe UI",system-ui,sans-serif;--mono:"JetBrains Mono",ui-monospace,Consolas,monospace; + --r:18px;--tile:125px;color-scheme:dark} +*{box-sizing:border-box} +html{-webkit-text-size-adjust:100%} +body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 var(--body);min-height:100vh; + background-image:radial-gradient(60% 40% at 15% -5%,rgba(255,91,46,.16),transparent 70%),radial-gradient(50% 35% at 95% 0%,rgba(92,200,255,.10),transparent 70%), + radial-gradient(rgba(255,255,255,.035) 1px,transparent 1px);background-size:auto,auto,22px 22px;background-attachment:fixed,fixed,scroll} +a{color:var(--amber)} a:hover{color:#ffd166} +.wrap{max-width:1180px;margin:0 auto;padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px))} +h1,h2,h3{font-family:var(--disp);line-height:1.08;margin:0 0 10px;letter-spacing:-.01em;text-wrap:balance} +h1{font-size:clamp(30px,5.2vw,58px);font-weight:900} +h2{font-size:clamp(20px,2.6vw,26px);font-weight:800} +h3{font-size:17px;font-weight:700} +p{margin:8px 0} +.muted{color:var(--muted)} .small{font-size:13.5px} .mono{font-family:var(--mono)} .center{text-align:center} +/* nav */ +nav.top{position:sticky;top:0;z-index:30;background:rgba(11,16,48,.86);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-bottom:1px solid var(--line)} +nav.top .wrap{display:flex;align-items:center;gap:14px;min-height:62px;flex-wrap:wrap;padding-top:6px;padding-bottom:6px} +.brand{display:flex;align-items:center;gap:10px;text-decoration:none;color:var(--ink);min-width:0;margin-right:auto} +.brand img{flex:none} +.brand .wm{font:900 19px/1 var(--disp);letter-spacing:-.02em;white-space:nowrap} +.brand .wm b{color:var(--hot)} +.brand .by{display:block;font:500 11px/1.2 var(--body);color:var(--faint);letter-spacing:.02em;margin-top:3px} +nav.top .links{display:flex;gap:4px;flex-wrap:wrap} +nav.top .links a{color:var(--muted);text-decoration:none;font-weight:600;font-size:14px;padding:7px 11px;border-radius:999px} +nav.top .links a:hover{color:var(--ink);background:var(--line)} +nav.top .links a.on{color:var(--hot-ink);background:var(--amber)} +@media (max-width:720px){nav.top .links{width:100%;overflow-x:auto;flex-wrap:nowrap;scrollbar-width:none;margin:0 -4px 2px}nav.top .links::-webkit-scrollbar{display:none}nav.top .links a{flex:none}} +/* hero */ +.hero{padding:34px 0 8px} +.hero .eyebrow{display:inline-flex;align-items:center;gap:8px;font:600 12px/1 var(--mono);letter-spacing:.14em;text-transform:uppercase;color:var(--amber);margin-bottom:14px} +.hero .eyebrow i{width:8px;height:8px;border-radius:50%;background:var(--hot);box-shadow:0 0 0 4px var(--hot-soft);animation:pulse 1.8s ease-in-out infinite} +.hero h1 em{font-style:normal;color:var(--hot)} +.hero .lead{color:var(--muted);font-size:clamp(16px,1.8vw,18.5px);max-width:720px} +@keyframes pulse{50%{box-shadow:0 0 0 8px rgba(255,91,46,0)}} +/* buttons */ +.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;font:800 15px/1 var(--disp);letter-spacing:.01em;padding:13px 20px;border-radius:12px;border:0;cursor:pointer; + background:var(--hot);color:#fff;text-decoration:none;box-shadow:0 10px 30px -12px rgba(255,91,46,.8);transition:transform .12s ease,filter .12s ease} +.btn:hover{color:#fff;filter:brightness(1.08);transform:translateY(-1px)} +.btn:disabled{opacity:.5;cursor:not-allowed;transform:none} +.btn.sec{background:var(--panel2);color:var(--ink);box-shadow:none;border:1px solid var(--line2)} +.btn.amber{background:var(--amber);color:var(--hot-ink);box-shadow:0 10px 30px -14px rgba(255,176,0,.8)} +.btn.quiet{background:transparent;color:var(--muted);box-shadow:none;border:1px solid var(--line)} +.btn.small{padding:9px 13px;font-size:13px;border-radius:10px} +.row{display:flex;gap:10px;flex-wrap:wrap;align-items:center} +/* panels */ +.card{background:linear-gradient(180deg,var(--panel),var(--bg2));border:1px solid var(--line2);border-radius:var(--r);padding:20px;margin:16px 0;box-shadow:0 24px 60px -40px rgba(0,0,0,.9)} +.card>h2:first-child,.card>h3:first-child{margin-top:0} +.note{border-radius:12px;padding:10px 14px;margin:12px 0;background:var(--sky-soft);border:1px solid rgba(92,200,255,.3);font-size:14.5px} +.note.err{background:var(--bad-soft);border-color:var(--bad)} .note.ok{background:var(--ok-soft);border-color:var(--ok)} +.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:12px 0} +.stat{background:var(--bg2);border:1px solid var(--line);border-radius:14px;padding:12px 14px} +.stat b{display:block;font:800 24px/1.15 var(--disp);font-variant-numeric:tabular-nums} +.stat span{color:var(--muted);font-size:13px} +/* the shift meter */ +.meter{background:var(--bg2);border:1px solid var(--line2);border-radius:var(--r);padding:16px 18px;margin:18px 0 6px} +.meter-top{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;margin-bottom:10px} +.meter-top .big{font:900 34px/1 var(--disp);font-variant-numeric:tabular-nums;color:var(--amber)} +.meter-top .big small{font-size:18px;color:var(--muted);font-weight:700} +.meter-top .lbl{font-weight:600} +.meter-top .side{margin-left:auto;color:var(--muted);font-size:13.5px} +.bar{position:relative;height:16px;border-radius:999px;background:rgba(255,255,255,.07);overflow:hidden} +.bar i{position:absolute;inset:0 auto 0 0;width:0;border-radius:999px;background:linear-gradient(90deg,var(--hot),var(--amber));transition:width .6s cubic-bezier(.2,.8,.2,1)} +.bar i::after{content:"";position:absolute;inset:0;background:repeating-linear-gradient(115deg,rgba(255,255,255,.18) 0 10px,transparent 10px 20px);animation:slide 1.2s linear infinite} +@keyframes slide{to{background-position:40px 0}} +.ticks{display:flex;justify-content:space-between;margin-top:6px;font:500 11px var(--mono);color:var(--faint)} +.visit-note{font-size:13.5px;color:var(--muted);margin-top:10px;min-height:20px} +.visit-note.ok{color:var(--ok)} +/* the loop grid: 125x125 tiles */ +.loop-head{display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap;margin:26px 0 10px} +.loop-head h2{margin:0} +.loop-head .side{margin-left:auto;color:var(--muted);font-size:13.5px} +.grid{display:grid;grid-template-columns:repeat(auto-fill,var(--tile));gap:10px;justify-content:center} +.tile{position:relative;display:block;width:var(--tile);aspect-ratio:1;border-radius:12px;overflow:hidden;background:var(--panel);border:1px solid var(--line2);line-height:0;text-decoration:none} +.tile img{width:100%;height:100%;object-fit:cover;display:block} +.tile .pos{position:absolute;left:5px;top:5px;font:700 10.5px/1 var(--mono);background:rgba(11,16,48,.82);color:var(--ink);padding:3px 5px;border-radius:6px} +.tile .who{position:absolute;left:0;right:0;bottom:0;font:600 10.5px/1.2 var(--body);background:linear-gradient(0deg,rgba(11,16,48,.92),transparent);color:var(--ink);padding:14px 6px 5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;opacity:0;transition:opacity .15s} +.tile:hover .who,.tile:focus-visible .who{opacity:1} +.tile.next{border:2px solid var(--hot);box-shadow:0 0 0 4px var(--hot-soft)} +.tile.next .pos{background:var(--hot);color:#fff} +.tile.fresh{animation:enter .7s cubic-bezier(.2,.8,.2,1)} +@keyframes enter{from{transform:scale(.6);opacity:0}} +.tile.open{display:flex;align-items:center;justify-content:center;flex-direction:column;gap:4px;border:1.5px dashed var(--line2);background:transparent;color:var(--faint);font:600 12px/1.25 var(--body);text-align:center;padding:8px} +.tile.open:hover{border-color:var(--amber);color:var(--amber)} +.tile.open b{font:900 22px/1 var(--disp)} +.queue{display:flex;gap:8px;overflow-x:auto;padding:4px 0 10px;scrollbar-width:thin} +.queue .tile{--tile:72px;flex:none;border-radius:9px} +.queue .tile .pos{font-size:9.5px} +.legend{display:flex;gap:16px;flex-wrap:wrap;color:var(--muted);font-size:13px;margin:10px 0 0} +.legend span{display:inline-flex;align-items:center;gap:6px} +.legend i{width:12px;height:12px;border-radius:3px;border:2px solid var(--hot)} +.legend i.n{border:1px solid var(--line2);background:var(--panel)} +@media (max-width:600px){:root{--tile:calc((100vw - 32px - 30px) / 4)}.grid{grid-template-columns:repeat(4,var(--tile));gap:10px}.meter-top .big{font-size:28px}} +/* steps */ +.how{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin:12px 0;padding:0;list-style:none;counter-reset:s} +.how li{counter-increment:s;background:var(--bg2);border:1px solid var(--line);border-radius:14px;padding:14px 14px 14px 52px;position:relative} +.how li::before{content:counter(s);position:absolute;left:14px;top:14px;width:26px;height:26px;border-radius:8px;background:var(--amber);color:var(--hot-ink);font:900 14px/26px var(--disp);text-align:center} +.how li b{display:block;margin-bottom:2px} +/* tables + forms */ +table.t{width:100%;border-collapse:collapse;font-size:14.5px} +table.t th,table.t td{text-align:left;padding:9px 8px;border-bottom:1px solid var(--line);vertical-align:middle} +table.t th{color:var(--muted);font:600 11.5px var(--mono);letter-spacing:.08em;text-transform:uppercase} +table.t td.n{text-align:right;font-family:var(--mono);font-variant-numeric:tabular-nums} +table.t tr.me td{background:var(--amber-soft)} +.scroll{overflow-x:auto} +.rank{display:inline-grid;place-items:center;width:26px;height:26px;border-radius:8px;background:var(--panel2);font:800 13px var(--disp)} +tr:nth-child(2) .rank{background:var(--amber);color:var(--hot-ink)} +.field{display:flex;flex-direction:column;gap:5px;margin:10px 0} +.field label{font-size:13.5px;color:var(--muted);font-weight:600} +.field input{background:#0a0f2a;border:1px solid var(--line2);border-radius:10px;padding:11px 12px;color:var(--ink);font:14px var(--mono);width:100%} +.field input:focus{outline:2px solid var(--amber);outline-offset:1px} +.post-grid{display:grid;grid-template-columns:auto 1fr;gap:18px;align-items:start} +@media (max-width:600px){.post-grid{grid-template-columns:1fr}} +.preview{width:125px;height:125px;border-radius:12px;border:1.5px dashed var(--line2);display:grid;place-items:center;color:var(--faint);font-size:12px;text-align:center;overflow:hidden;background:var(--bg2)} +.preview img{width:125px;height:125px;object-fit:cover;display:block} +.mine{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:12px} +.mine .item{display:flex;gap:12px;background:var(--bg2);border:1px solid var(--line);border-radius:14px;padding:10px;align-items:center} +.mine .item img{width:72px;height:72px;border-radius:9px;object-fit:cover;flex:none} +.mine .item .s{font-size:13.5px;min-width:0} +.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} +.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} +/* 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} +.toasts{position:fixed;left:max(16px,env(safe-area-inset-left,0px));bottom:max(16px,env(safe-area-inset-bottom,0px));z-index:50;display:flex;flex-direction:column;gap:8px;pointer-events:none} +.toast{pointer-events:auto;display:block;max-width:300px;background:var(--panel2);border:1px solid rgba(255,176,0,.4);border-radius:14px;padding:10px 14px;color:var(--ink);font-size:13.5px;line-height:1.35; + box-shadow:0 14px 34px -14px rgba(0,0,0,.9);opacity:0;transform:translateY(10px);transition:opacity .35s ease,transform .35s ease;text-decoration:none} +.toast.in{opacity:1;transform:none} .toast span{color:var(--muted);font-size:12.5px} +[hidden]{display:none!important} +@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}} diff --git a/public/assets/wallet.js b/public/assets/wallet.js new file mode 100644 index 0000000..7bb8fbe --- /dev/null +++ b/public/assets/wallet.js @@ -0,0 +1,199 @@ +// Viral Banner Blitz wallet sign-in: Downline Banners' wallet.js (same AppKit build, chain guard, dead-session recovery) +// with the buy functions removed. VBB v1 only signs a free sign-in message; it never sends a transaction. +window.VBBWallet = (function () { + const pad = v => BigInt(v).toString(16).padStart(64, '0'); + const padAddr = a => { if (!a) return pad(0); if (!/^0x[0-9a-fA-F]{40}$/.test(a)) throw new Error('Bad address: ' + a); return a.slice(2).toLowerCase().padStart(64, '0'); }; + // Normalize a chainId to a decimal number. eth_chainId is meant to return a + // hex string, but some wallets return a number or a decimal string — compare + // numerically so a wallet's shape never crashes the flow. + const chainNum = v => { + if (v == null) return NaN; + if (typeof v === 'number') return v; + const s = String(v).trim(); + return /^0x/i.test(s) ? parseInt(s, 16) : parseInt(s, 10); + }; + const APPKIT_URL = 'https://cdn.jsdelivr.net/npm/@reown/appkit-cdn@1.8.23/dist/appkit.js'; + + let modal = null, akPromise = null, provider = null; + + async function initAppKit(c) { + if (modal) return modal; + if (akPromise) return akPromise; + akPromise = (async () => { + const mod = await import(APPKIT_URL); + const { createAppKit, WagmiAdapter, networks } = mod; + const netMap = { 80002: networks.polygonAmoy, 137: networks.polygon, 31337: networks.hardhat || networks.localhost }; + const base = netMap[Number(c.chainId)] || networks.polygonAmoy; + // Override the chain's RPC with our clean public endpoint. AppKit's built-in + // networks advertise the WalletConnect RPC proxy + // (rpc.walletconnect.org/v1/?chainId=…&projectId=…) as the chain RPC, and + // wallets reject that query-string URL as "Invalid URL" when adding/switching + // the network — the cause of Trust's "Invalid URL", MetaMask's switch loop, + // and the failed mobile buy (the chain switch never completed). + const rpc = String(c.rpc || '').trim(); + const net = rpc ? Object.assign({}, base, { rpcUrls: { default: { http: [rpc] }, public: { http: [rpc] } } }) : base; + // Accept the wallet's usual networks too, so AppKit doesn't trap the user in + // its own "Switch Network" modal — that modal loops on a testnet the wallet + // can't auto-add. We switch to `net` ourselves (wallet_addEthereumChain adds + // + switches in one step) and sendTx hard-guards the chain before signing. + const allNets = [net]; + for (const k of ['polygon', 'mainnet']) { + try { const n = networks[k]; if (n && n.id !== net.id) allNets.push(n); } catch (e) {} + } + const projectId = String(c.walletConnectProjectId || '').trim(); + const wagmiAdapter = new WagmiAdapter({ networks: allNets, projectId }); + modal = createAppKit({ + adapters: [wagmiAdapter], networks: allNets, projectId, defaultNetwork: net, + metadata: { name: 'Viral Banner Blitz', description: 'A community banner loop that moves with every verified visitor.', + url: location.origin, icons: [location.origin + '/logo-icon.png'] }, + features: { analytics: false, email: false, socials: [] }, + // Picker order: wallets without Trust's balance-proportion block go first. + // Trust Wallet is NOT excluded; it just drops out of the featured row into + // "All wallets" (Marty, 2026-09-09: move Trust to the bottom, not off). + featuredWalletIds: [ + '0b415a746fb9ee99cce155c2ceca0c6f6061b1dbca2d722b3ba16381d0562150', // SafePal (recommended, listed first) + 'c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96', // MetaMask + 'a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393', // Phantom + 'fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa' // Coinbase Wallet + ] + }); + return modal; + })(); + return akPromise; + } + + function currentAddress() { try { return (modal && modal.getAddress && modal.getAddress()) || null; } catch (e) { return null; } } + + function waitForConnection(timeoutMs) { + if (currentAddress()) return Promise.resolve(currentAddress()); + return new Promise((resolve, reject) => { + let done = false, unsub = null; + const finish = (addr, err) => { if (done) return; done = true; try { unsub && unsub(); } catch (e) {} err ? reject(err) : resolve(addr); }; + try { unsub = modal.subscribeAccount(acc => { if (acc && acc.isConnected && acc.address) finish(acc.address); }); } catch (e) {} + const t0 = Date.now(); + (function poll() { + if (done) return; + const a = currentAddress(); + if (a) return finish(a); + if (Date.now() - t0 > (timeoutMs || 180000)) return finish(null, new Error('Wallet connection timed out. Tap Connect and try again.')); + setTimeout(poll, 400); + })(); + }); + } + + async function resolveProvider() { + for (let i = 0; i < 20; i++) { + try { const p = modal.getWalletProvider ? await Promise.resolve(modal.getWalletProvider()) : null; if (p && p.request) return p; } catch (e) {} + await new Promise(r => setTimeout(r, 300)); + } + throw new Error('Could not reach your wallet. Try connecting again.'); + } + + function eth() { if (!provider) throw new Error('Connect your wallet first.'); return provider; } + const isInjected = () => !!(provider && window.ethereum && (provider === window.ethereum || provider.isMetaMask)); + // the account the wallet will actually sign with: for an injected wallet (MetaMask + // extension) that is its active account, which can differ from AppKit's cached one + async function activeAddress(fallback) { + if (isInjected()) { try { const a = await provider.request({ method: 'eth_accounts' }); if (a && a[0]) return a[0]; } catch (e) {} } + return fallback || currentAddress(); + } + // Force the wallet's own account picker. Injected wallets stay connected to the + // site, so a plain disconnect/reconnect never shows one: asking for permissions + // again makes MetaMask open its account-selection prompt, and whatever the user + // ticks becomes the active account. WalletConnect wallets fall back to a fresh + // session (the picker + the wallet app's own account choice). + async function pickAccount() { + const c = await VBB.getConfig(); + await initAppKit(c); + const inj = window.ethereum; + if (inj && inj.request) { + try { + await inj.request({ method: 'wallet_requestPermissions', params: [{ eth_accounts: {} }] }); + const accs = await inj.request({ method: 'eth_accounts' }); + if (accs && accs[0]) { provider = inj; await ensureChain(c).catch(() => {}); return accs[0]; } + } catch (e) { + if (e && (e.code === 4001 || /reject|denied/i.test(String(e.message || '')))) throw new Error('You closed the account picker. Pick the account you want and try again.'); + } + } + return freshConnect(c); + } + + // A WalletConnect session can die underneath AppKit's cached "connected" + // state: the wallet app rejects or kills it (Trust does this after its own + // security stop), the phone sleeps, the relay drops. AppKit still reports an + // address, so the next request fails with a "disconnected" style error. + // Detect that, wipe the stale session, and re-open the picker for a fresh one. + const DEAD_RE = /disconnect|not connected|no matching key|session (topic|expired|deleted|not found)|call connect|please call connect|missing or invalid|relay/i; + const isDead = e => DEAD_RE.test(String((e && e.message) || e || '')); + async function freshConnect(c) { + try { VBB.status('Your wallet session dropped. Reconnect in the picker…'); } catch (e) {} + await disconnect(); + try { await modal.open(); } catch (e) {} + const addr = await waitForConnection(180000); + try { if (modal && modal.close) await modal.close(); } catch (e) {} + provider = await resolveProvider(); + await ensureChain(c).catch(() => {}); + return addr; + } + + async function connect() { + const c = await VBB.getConfig(); + await initAppKit(c); + let addr = currentAddress(); + if (!addr) { + // give AppKit a moment to rehydrate an existing session before popping the + // picker — otherwise an already-connected wallet still gets the modal + for (let i = 0; i < 8 && !addr; i++) { await new Promise(r => setTimeout(r, 150)); addr = currentAddress(); } + } + if (!addr) { try { await modal.open(); } catch (e) {} addr = await waitForConnection(180000); } + try { if (modal && modal.close) await modal.close(); } catch (e) {} // dismiss the picker once we're connected + provider = await resolveProvider(); + // probe the session: a dead WalletConnect session answers with a disconnect error + try { await provider.request({ method: 'eth_chainId' }); } + catch (e) { if (isDead(e)) return freshConnect(c); } + await ensureChain(c).catch(() => {}); // AppKit already connects on the right network; switch is best-effort + return addr; + } + + async function ensureChain(c) { + const want = '0x' + Number(c.chainId).toString(16); + let cur; try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) { return; } + if (chainNum(cur) === Number(c.chainId)) return; + try { + await eth().request({ method: 'wallet_switchEthereumChain', params: [{ chainId: want }] }); + } catch (e) { + // any failure (not just 4902): try to add the chain — wallet_addEthereumChain + // adds AND switches in one step, which is what unblocks wallets that can't + // otherwise reach a chain they don't already have (e.g. a testnet). + const addParams = { chainId: want, chainName: c.chainName, nativeCurrency: { name: 'POL', symbol: 'POL', decimals: 18 }, rpcUrls: [c.rpc] }; + if (c.explorer && /^https?:\/\//i.test(c.explorer)) addParams.blockExplorerUrls = [c.explorer]; + try { await eth().request({ method: 'wallet_addEthereumChain', params: [addParams] }); } catch (e2) {} + } + } + + // SIWE: challenge -> personal_sign -> verify (server sets the session cookie) + async function signIn(opts) { + const addr = (opts && opts.pick) ? await pickAccount() : await activeAddress(await connect()); + const ch = await (await fetch('/api/auth/challenge', { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address: addr }) })).json(); + if (ch.error) throw new Error(ch.error); + // hex-encode the message (Trust and others require hex for personal_sign) + const hexMsg = '0x' + Array.from(new TextEncoder().encode(ch.message)).map(b => b.toString(16).padStart(2, '0')).join(''); + const sig = await eth().request({ method: 'personal_sign', params: [hexMsg, addr] }); + const r = await (await fetch('/api/auth/verify', { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address: addr, signature: sig, asPosition: !!(opts && opts.asPosition) }) })).json(); + if (r.error) throw new Error(r.error); + return r; + } + + async function disconnect() { + // AppKit's disconnect can hang on the WalletConnect relay (esp. mobile) — + // never block on it, so the UI can't get stuck "disconnecting". + try { if (modal && modal.disconnect) await Promise.race([modal.disconnect(), new Promise(r => setTimeout(r, 1200))]); } catch (e) {} + provider = null; + try { Object.keys(localStorage).forEach(k => { if (/wc@2|walletconnect|w3m|wcm|reown|wagmi|appkit/i.test(k)) localStorage.removeItem(k); }); } catch (e) {} + } + + function walletName() { try { const w = modal && modal.getWalletInfo && modal.getWalletInfo(); return (w && w.name) || ''; } catch (e) { return ''; } } + return { connect, signIn, disconnect, address: currentAddress, activeAddress, pickAccount, walletName }; +})(); diff --git a/public/how.html b/public/how.html new file mode 100644 index 0000000..9b38d7d --- /dev/null +++ b/public/how.html @@ -0,0 +1,55 @@ + + + + +How It Works | Viral Banner Blitz + + + + + + + + + + + + + + + + + + + + + + +
+

How the loop works

One public page, one shared loop. The whole community moves it with real visitors.

+
    +
  1. Sign in, get a creditSign in through InstantAdPay, LinkSpin or a wallet. Every day you sign in you get one free post credit.
  2. +
  3. Post a bannerA 125x125 image and a link. It waits in line, then enters the loop at the front.
  4. +
  5. Visitors move the loopEvery 10 verified visitors shift every banner one place forward.
  6. +
  7. Ride out, earn advertisingThe banner at the end rides out. It has cycled, and you earn 150 network ad views.
  8. +
+
+

What counts as a verified visitor

+

A real browser that keeps the loop page open and visible for about 6 seconds. Each visitor counts once every 24 hours. Bots, crawlers and repeat visits do not count, and only a few visitors per internet connection count each day.

+
+
+

What a cycle earns

+

A cycle earns network ad views: advertising for your own offers across the Crypto Team Build Network (InstantAdPay, LinkSpin and the network banner boards). It is advertising, not cash, and nothing here promises income.

+

Right now each cycle is recorded on your My Banners page. Adding those views to your network advertising is the next step and is not switched on yet.

+
+
+

Weekly leaderboards

+

Share your link (it ends in ?ref= and your network username). The leaderboards count the verified visitors you send each week and how many different websites they came from.

+ +
+ +
+ + + + diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..c056125 --- /dev/null +++ b/public/index.html @@ -0,0 +1,61 @@ + + + + +Viral Banner Blitz | The banner loop the whole community pushes + + + + + + + + + + + + + + + + + + + + + + + +
+
+
Live loop
+

Every visitor pushes the loop. Ride it out, earn advertising.

+

This page is the loop: member banners in 125x125 tiles. Every 10 verified visitors shift it one place, and the banner at the end rides out. That banner has cycled, and its owner earns 150 network ad views.

+ +
+ +
+
0 / 10verified visitors toward the next shift
+
+
Stay on this page for a few seconds and your visit counts toward the next shift.
+
+ +

The loop

+
+
Rides out at the next shiftNewest enters top left
+ +

Waiting to enter

+
+ + +
+

Send visitors, move up the leaderboard

+

Share your link from My Banners. Every verified visitor it brings moves the loop for everyone, and the weekly leaderboards count the visitors you send and how many different traffic sources they came from.

+ +
+ +
+ + + + diff --git a/public/leaders.html b/public/leaders.html new file mode 100644 index 0000000..91f7b5d --- /dev/null +++ b/public/leaders.html @@ -0,0 +1,37 @@ + + + + +Weekly Leaderboards | Viral Banner Blitz + + + + + + + + + + + + + + + + + + + + + + +
+
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 new file mode 100644 index 0000000..2a864da --- /dev/null +++ b/public/my.html @@ -0,0 +1,80 @@ + + + + +My Banners | Viral Banner Blitz + + + + + + + + + + + + + + + + + + + + + + +
+

My Banners

Post a banner, watch it move through the loop, and share your link.

+ + + + + +
+ + + + + diff --git a/public/packages.html b/public/packages.html new file mode 100644 index 0000000..9cc3c53 --- /dev/null +++ b/public/packages.html @@ -0,0 +1,42 @@ + + + + +Packages | Viral Banner Blitz + + + + + + + + + + + + + + + + + + + + + + +
+

Packages

Extra post credits and banner extras are on the way.

+
+
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.

+ +
+ +
+ + + + diff --git a/safety.js b/safety.js new file mode 100644 index 0000000..d995457 --- /dev/null +++ b/safety.js @@ -0,0 +1,135 @@ +// Link + image checks for posted banners (Downline Banners' safety.js, sized for VBB). +// Links: https only, a real public hostname, no shorteners, and (when probed) a page that answers and allows frames. +// Images: a real PNG/JPG/GIF at exactly 125x125 (or 250x250 retina) and at most 100 KB. An https image address is +// fetched once, checked the same way and stored as an upload, so the splash never hotlinks someone else's server. +const net = require('net'); +const dns = require('dns'); +const https = require('https'); + +const MAX_UPLOAD = 100 * 1024; +const BAD_HOST = /(^|\.)(localhost|local|internal|lan|home|corp|onion|test|invalid|example)$/i; +// shorteners and redirectors hide where a click goes; a member link must show its real destination +const REDIRECTORS = /(^|\.)(bit\.ly|tinyurl\.com|t\.co|goo\.gl|is\.gd|cutt\.ly|ow\.ly|rebrand\.ly|shorturl\.at|rb\.gy|s\.id|t\.ly|v\.gd|bl\.ink|tiny\.cc)$/i; + +function checkLink(raw, what) { + what = what || 'Link'; + const s = String(raw || '').trim(); + if (!s) return { error: what + ' is empty.' }; + if (s.length > 600) return { error: what + ' is too long (600 characters max).' }; + if (/[\s<>"'`\\]/.test(s)) return { error: what + ' has spaces or characters a web address cannot have.' }; + let u; try { u = new URL(s); } catch (e) { return { error: what + ' is not a valid web address.' }; } + if (u.protocol !== 'https:') return { error: what + ' must start with https://' }; + if (u.username || u.password) return { error: what + ' cannot contain a username or password.' }; + const h = u.hostname.toLowerCase().replace(/\.$/, ''); + if (net.isIP(h.replace(/^\[|\]$/g, ''))) return { error: what + ' must use a domain name, not an IP address.' }; + if (!h.includes('.') || BAD_HOST.test(h)) return { error: what + ' must point to a public website.' }; + if (!/^[a-z0-9.-]+$/.test(h) && !/^xn--/.test(h)) return { error: what + ' has an unusual domain name.' }; + if (REDIRECTORS.test(h)) return { error: 'Use the real destination, not a link shortener.' }; + if (u.port && !['443', ''].includes(u.port)) return { error: what + ' must use the normal https port.' }; + return { ok: true, url: u.toString() }; +} + +function imageInfo(buf) { + if (!buf || buf.length < 24) return null; + if (buf.slice(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) + return { type: 'png', ext: '.png', w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) }; + if (buf.slice(0, 6).toString('latin1') === 'GIF87a' || buf.slice(0, 6).toString('latin1') === 'GIF89a') + return { type: 'gif', ext: '.gif', w: buf.readUInt16LE(6), h: buf.readUInt16LE(8) }; + if (buf[0] === 0xff && buf[1] === 0xd8) { + let i = 2; + while (i + 9 < buf.length) { + if (buf[i] !== 0xff) { i++; continue; } + const m = buf[i + 1]; + if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { type: 'jpg', ext: '.jpg', h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) }; + if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { i += 2; continue; } + i += 2 + buf.readUInt16BE(i + 2); + } + return { type: 'jpg', ext: '.jpg', w: 0, h: 0 }; + } + return null; +} +function checkImage(buf) { + if (!buf || !buf.length) return { error: 'No file received.' }; + if (buf.length > MAX_UPLOAD) return { error: 'That file is ' + Math.ceil(buf.length / 1024) + ' KB. The limit is 100 KB.' }; + const info = imageInfo(buf); + if (!info) return { error: 'Use a PNG, JPG or GIF image.' }; + const ok = (info.w === 125 && info.h === 125) || (info.w === 250 && info.h === 250); + if (!ok) return { error: 'The image is ' + info.w + 'x' + info.h + '. It must be 125x125 (or 250x250).' }; + return { ok: true, info }; +} + +// ---- outbound requests only to public addresses (the DNS answer used for the connection is the one checked) ---- +function privateIp(ip) { + if (net.isIPv4(ip)) { + const [a, b] = ip.split('.').map(Number); + return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) + || (a === 192 && b === 168) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224; + } + const s = ip.toLowerCase(); + if (s.startsWith('::ffff:')) return privateIp(s.slice(7)); + return s === '::' || s === '::1' || s.startsWith('fc') || s.startsWith('fd') || s.startsWith('fe80') || s.startsWith('ff'); +} +function safeLookup(host, opts, cb) { + dns.lookup(host, Object.assign({}, opts, { all: false }), (err, addr, fam) => { + if (err) return cb(err); + if (privateIp(addr)) return cb(new Error('private address')); + cb(null, addr, fam); + }); +} +// GET with a size cap, a timeout and no redirects followed (a redirect is reported so the caller can decide) +function get(url, maxBytes, timeoutMs) { + return new Promise(resolve => { + let done = false; const fin = v => { if (!done) { done = true; resolve(v); } }; + let req; + try { + req = https.get(url, { lookup: safeLookup, timeout: timeoutMs || 5000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; VBBCheck/1.0; +https://viralbannerblitz.com)', Accept: '*/*' } }, res => { + const out = { status: res.statusCode, headers: res.headers, location: res.headers.location || null }; + if (!maxBytes) { res.destroy(); return fin(out); } + const ch = []; let n = 0; + res.on('data', c => { n += c.length; if (n > maxBytes) { res.destroy(); return fin(Object.assign(out, { tooBig: true })); } ch.push(c); }); + res.on('end', () => fin(Object.assign(out, { body: Buffer.concat(ch) }))); + res.on('error', () => fin(Object.assign(out, { error: 'read' }))); + }); + req.on('timeout', () => { req.destroy(); fin({ error: 'timeout' }); }); + req.on('error', e => fin({ error: /private address/.test(e.message) ? 'private' : 'unreachable' })); + } catch (e) { fin({ error: 'unreachable' }); } + }); +} + +// does this response allow being shown inside a frame on another site? +function frameVerdict(headers) { + const h = k => String(headers[k] || '').toLowerCase(); + if (h('x-frame-options')) return false; + const fa = /frame-ancestors([^;]*)/.exec(h('content-security-policy')); + return !(fa && !/\*|https:/.test(fa[1])); +} +// the target link must answer and allow frames (traffic exchanges and the splash preview show sites in a frame). Up to 3 redirects. +async function probeLink(url) { + let cur = url; + for (let hop = 0; hop < 4; hop++) { + const r = await get(cur, 0, 6000); + if (r.error === 'private') return { error: 'That link points to a private network address.' }; + if (r.error) return { error: 'We could not reach that link. Check it opens in your browser and try again.' }; + if (r.status >= 300 && r.status < 400 && r.location) { + let next; try { next = new URL(r.location, cur).toString(); } catch (e) { return { error: 'That link redirects somewhere invalid.' }; } + const c = checkLink(next, 'The page your link redirects to'); if (c.error) return c; + cur = c.url; continue; + } + if (r.status >= 400) return { error: 'That link answered with an error (' + r.status + '). Use a page that loads.' }; + if (!frameVerdict(r.headers)) return { error: 'That site does not allow being shown in a frame, so it cannot rotate here. Use a page that allows frames (most landing pages and LinkSpin links do).' }; + return { ok: true }; + } + return { error: 'That link redirects too many times.' }; +} +// an https image address: fetched once, checked like an upload. -> { ok, buf, info } or { error } +async function fetchImage(url) { + const r = await get(url, MAX_UPLOAD, 6000); + if (r.error === 'private') return { error: 'That image address points to a private network address.' }; + if (r.error) return { error: 'We could not download that image. Check the address or upload the file instead.' }; + if (r.tooBig) return { error: 'That image is over 100 KB.' }; + if (r.status !== 200) return { error: 'The image address answered ' + r.status + '. Use a direct link to the image file, or upload it.' }; + const c = checkImage(r.body); if (c.error) return c; + return { ok: true, buf: r.body, info: c.info }; +} + +module.exports = { checkLink, checkImage, imageInfo, frameVerdict, probeLink, fetchImage, privateIp, MAX_UPLOAD }; diff --git a/server.js b/server.js new file mode 100644 index 0000000..44a3134 --- /dev/null +++ b/server.js @@ -0,0 +1,353 @@ +// Viral Banner Blitz web app (viralbannerblitz.com rebuild, "VBB"). Plain Node http server, no framework (the InstantAdPay and +// Downline Banners pattern). v1 is off-chain: no contract, no prices, no money. +// Pages: / (splash: the loop, the next-shift bar, the queue), /my (My Banners), /leaders, /how, /packages, /admin. +// Engine: loop.js. Data: store.js on docstore.js (MySQL when DOCSTORE_URL is set). Checks: safety.js. Network sign-in: networksso.js. +'use strict'; +const http = require('http'); +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const { verifyMessage, getAddress } = require('ethers'); +const cfgMod = require('./config'); + +const C = cfgMod.get(); +fs.mkdirSync(path.join(C.dataDir, 'uploads'), { recursive: true }); +const docstore = require('./docstore'); docstore.install(C.dataDir); // before any module reads data +const store = require('./store'); +const loop = require('./loop'); +const safety = require('./safety'); +const networksso = require('./networksso'); + +const PUB = path.join(__dirname, 'public'); +const UPL = path.join(C.dataDir, 'uploads'); +const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; +const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/; +const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|preview|monitor|wget|curl|python|httpclient|scrapy|semrush|ahrefs|headless|lighthouse|pingdom|go-http|java\/|okhttp|axios|node-fetch|phantom|selenium|puppeteer|playwright/i; +const SECRET = (() => { + if (process.env.SESSION_SECRET) return process.env.SESSION_SECRET; + const f = path.join(C.dataDir, '.secret'); + try { return fs.readFileSync(f, 'utf8').trim(); } catch (e) {} + const s = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, s, { mode: 0o600 }); } catch (e) {} return s; +})(); +const hash = s => crypto.createHmac('sha256', SECRET).update(s).digest('hex').slice(0, 24); + +// ---- http helpers ---- +const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', + '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' }; +const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " + + "img-src 'self' data: blob: https:; connect-src 'self' https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org " + + "https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; " + + "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: 'self'"; +function headers(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); } +function json(res, code, obj, extra) { res.writeHead(code, headers(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); res.end(JSON.stringify(obj)); } +function sendFile(res, file, extra) { + fs.readFile(file, (err, data) => { + if (err) { res.writeHead(404, headers({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } + const ext = path.extname(file).toLowerCase(); + res.writeHead(200, headers(Object.assign({ 'Content-Type': MIME[ext] || 'application/octet-stream', 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' }, extra))); + res.end(data); + }); +} +function readRaw(req, max) { + return new Promise((resolve, reject) => { const ch = []; let n = 0; + req.on('data', c => { n += c.length; if (n > max * 8) { req.destroy(); return; } if (n <= max) ch.push(c); }); + req.on('end', () => n > max ? reject(new Error('too big')) : resolve(Buffer.concat(ch))); req.on('error', reject); }); +} +async function readBody(req) { const b = await readRaw(req, 32 * 1024); try { return b.length ? JSON.parse(b.toString('utf8')) : {}; } catch (e) { return {}; } } +function cookies(req) { const o = {}; for (const p of (req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { o[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } return o; } +function cookie(name, val, maxAgeSec, httpOnly) { return name + '=' + encodeURIComponent(val) + '; Path=/; SameSite=Lax; Max-Age=' + maxAgeSec + (httpOnly ? '; HttpOnly' : '') + (C.isProd ? '; Secure' : ''); } +// Client IP. Behind Coolify's proxy the RIGHTMOST X-Forwarded-For entry is the one the proxy added; earlier entries are whatever +// the client sent and can be forged, so they are never used. CF_PROXIED=1 (only when Cloudflare proxies the domain): cf-connecting-ip. +function ip(req) { + if (process.env.CF_PROXIED === '1' && req.headers['cf-connecting-ip']) return String(req.headers['cf-connecting-ip']).trim(); + const xff = String(req.headers['x-forwarded-for'] || '').split(',').map(s => s.trim()).filter(Boolean); + return (xff.length ? xff[xff.length - 1] : String(req.socket.remoteAddress || '')).replace(/^::ffff:/, ''); +} +const isBot = req => !req.headers['user-agent'] || BOT_UA.test(req.headers['user-agent']); +// visitor = IP + user agent (not a cookie: traffic-exchange frames drop cookies) +const visitorKey = req => hash('vk|' + ip(req) + '|' + (req.headers['user-agent'] || '')); +const ipKey = req => hash('ip|' + ip(req)); + +// per-IP fixed-window limiter +const buckets = new Map(); +function limited(req, name, max, windowMs) { + const k = name + ':' + ip(req); const now = Date.now(); let b = buckets.get(k); + if (!b || now - b.t > windowMs) { b = { t: now, n: 0 }; buckets.set(k, b); } + if (buckets.size > 100000) buckets.clear(); + return ++b.n > max; +} +const isAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const g = String(req.headers['x-admin-token'] || ''); + return t.length >= 8 && g.length === t.length && crypto.timingSafeEqual(Buffer.from(g), Buffer.from(t)); }; + +// ---- network usernames (InstantAdPay today, the network hub later: this is the one place to point at it) ---- +const netCache = new Map(); +async function netMember(q) { + if (!C.networkLookupUrl) return null; + const k = q.u ? 'u:' + q.u.toLowerCase() : 'a:' + q.a.toLowerCase(); + const hit = netCache.get(k); if (hit && Date.now() - hit.at < 3600000) return hit.m; + let m = null; + try { const ac = new AbortController(); setTimeout(() => ac.abort(), 4000).unref(); + const qs = q.u ? 'u=' + encodeURIComponent(q.u) : 'a=' + encodeURIComponent(q.a); + const j = await (await fetch(C.networkLookupUrl + '?' + qs, { signal: ac.signal })).json(); + if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username) }; } catch (e) { return null; } + netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear(); + return m; +} +// ?ref= -> a VBB member's address (only members who have signed in here can be credited) +async function resolveRef(raw) { + const r = String(raw || '').trim().slice(0, 60); if (!r) return null; + if (ADDR_RE.test(r)) return store.member(r) ? r.toLowerCase() : null; + if (!NAME_RE.test(r)) return null; + const local = store.memberByName(r); if (local) return local.address; + const m = await netMember({ u: r }).catch(() => null); + return m && store.member(m.address) ? m.address : null; +} +// a member's username: the one the network sign-in carried, else the network lookup by wallet (filled in once) +async function fillUsername(addr) { + const m = store.member(addr); if (!m || m.username) return; + const n = await netMember({ a: addr }).catch(() => null); + if (n && n.address === m.address && NAME_RE.test(n.username) && !store.memberByName(n.username)) store.upsertMember(addr, { username: n.username }); +} +const refCookie = req => { const v = cookies(req)['vbb.ref']; return v && (NAME_RE.test(v) || ADDR_RE.test(v)) ? v : null; }; + +// ---- members ---- +const session = req => store.session(cookies(req)['vbb.sid']); +function signedIn(addr, patch) { + const m = store.upsertMember(addr, patch); + grantDaily(m); return m; +} +// one free post credit a day (Central time), banked up to freeCreditCap +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; } + store.save(); return granted; +} +function myData(addr) { + const m = store.member(addr); + const banners = store.bannersOf(addr).slice().reverse().map(b => Object.assign({ id: b.id, img: b.img, link: b.link, createdAt: b.createdAt, cycledAt: b.cycledAt || null, clicks: b.clicks || 0 }, loop.placeOf(b))); + const rewards = store.ledger().filter(e => e.owner === m.address); + const shareName = m.username || m.address; + return { address: m.address, username: m.username, credits: m.credits, freeCreditCap: C.freeCreditCap, freeToday: m.freeDay === store.ctDay(), + maxQueued: C.maxQueuedPerMember, banners, rewards: rewards.slice(-50).reverse(), rewardViews: rewards.reduce((t, e) => t + e.views, 0), + week: loop.memberWeek(m.address), share: 'https://' + C.site + '/?ref=' + encodeURIComponent(shareName) }; +} + +// ---- visit tickets: issued on page load, redeemed after the page has been visible for visitSeconds ---- +const tickets = new Map(); +const srcHost = raw => { try { const u = new URL(String(raw || '')); if (!/^https?:$/.test(u.protocol)) return ''; const h = u.hostname.toLowerCase().replace(/^www\./, ''); return h === C.site || h.endsWith('.' + C.site) || !h.includes('.') ? '' : h.slice(0, 80); } catch (e) { return ''; } }; + +// Viral Banner Blitz only RECEIVES network sign-ins (like Downline Banners): InstantAdPay or LinkSpin vouch for the member's wallet +// and username. Those sites must list `vbb` under `wallets` before this works live. +networksso.init({ self: 'vbb', peer: 'iap', peerBase: () => C.iapBase, from: { iap: () => C.iapBase, linkspin: () => C.lsBase }, + isProd: C.isProd, dataDir: C.dataDir, defaultPath: '/my', + member: async req => { const s = session(req); return s ? { address: s.address } : null; }, + accept: async (email, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }), + signIn: async (email, req, v) => { + const patch = { via: v.iss }; + if (v.name && NAME_RE.test(v.name)) { const other = store.memberByName(v.name); if (!other || other.address === v.wallet) patch.username = v.name; } + signedIn(v.wallet, patch); + return cookie('vbb.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true); + }, + landing: to => to, signinPath: to => to }); + +const PAGES = { '/': 'index.html', '/my': 'my.html', '/leaders': 'leaders.html', '/how': 'how.html', '/packages': 'packages.html', '/admin': 'admin.html' }; +const challenges = new Map(); +const clickSeen = new Map(); + +const server = http.createServer(async (req, res) => { + const u = new URL(req.url, 'http://x'); const p = u.pathname; + { const host = String(req.headers.host || '').toLowerCase().split(':')[0]; + if (C.isProd && host !== C.site && host.endsWith('.' + C.site)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } } + try { + if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return; + + if (req.method === 'GET' || req.method === 'HEAD') { + if (PAGES[p]) { + const ex = {}; + const ref = u.searchParams.get('ref'); + if (ref && (NAME_RE.test(ref) || ADDR_RE.test(ref))) ex['Set-Cookie'] = cookie('vbb.ref', ref, 30 * 86400, false); + if (p === '/my' || p === '/admin') ex['X-Frame-Options'] = 'DENY'; // member + admin pages never framed; the splash stays frameable + return sendFile(res, path.join(PUB, PAGES[p]), ex); + } + if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/?ref=' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); } + if (p === '/sitemap.xml') { + const day = new Date().toISOString().slice(0, 10); + const urls = ['/', '/leaders', '/how', '/packages'].map(x => 'https://' + C.site + x + '' + day + '').join(''); + res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); + return res.end('' + urls + ''); + } + if (p === '/robots.txt') { res.writeHead(200, headers({ 'Content-Type': 'text/plain; charset=utf-8' })); return res.end('User-agent: *\nAllow: /\nDisallow: /my\nDisallow: /admin\nDisallow: /api/\nDisallow: /go/\nDisallow: /sso/\n\nSitemap: https://' + C.site + '/sitemap.xml\n'); } + if (p.startsWith('/assets/') || p.startsWith('/art/') || p === '/favicon.ico') { + const f = path.normalize(path.join(PUB, p === '/favicon.ico' ? '/art/icon-192.png' : p)); if (!f.startsWith(PUB + path.sep)) { res.writeHead(400); return res.end(); } + return sendFile(res, f); + } + if (p.startsWith('/u/')) { + const name = path.basename(p); if (!/^[a-z0-9-]+\.(png|jpg|gif)$/.test(name)) { res.writeHead(404); return res.end(); } + return sendFile(res, path.join(UPL, name), { 'Cache-Control': 'public, max-age=604800, immutable' }); + } + // click relay: /go/ counts one click per visitor per banner per hour, then sends the visitor to the banner's link + const gm = /^\/go\/(\d{1,9})$/.exec(p); + if (gm) { + const b = store.banner(gm[1]); if (!b) { res.writeHead(302, { Location: '/' }); return res.end(); } + if (!isBot(req)) { + const k = visitorKey(req) + ':' + b.id; const t = clickSeen.get(k); + if (!t || Date.now() - t > 3600000) { clickSeen.set(k, Date.now()); if (clickSeen.size > 100000) clickSeen.clear(); b.clicks = (b.clicks || 0) + 1; store.saveBanner(b); store.bump('clicks'); } + } + res.writeHead(302, { Location: b.link, 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end(); + } + } + + // -- public API + 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() }); + } + 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') { + const out = loop.leaders(null, 10); + const fmt = r => ({ name: r.username ? '@' + r.username : r.address.slice(0, 6) + '...' + r.address.slice(-4), visitors: r.visitors, sources: r.sources }); + return json(res, 200, { week: out.week, visitors: out.visitors.map(fmt), sources: out.sources.map(fmt) }, { 'Cache-Control': 'public, max-age=15' }); + } + if (p === '/api/recent' && req.method === 'GET') { + const list = store.ledger().slice(-8).reverse().filter(e => Date.now() - e.at < 30 * 60000) + .map(e => ({ id: e.id, at: e.at, bannerId: e.bannerId, name: e.username ? '@' + e.username : null, views: e.views })); + return json(res, 200, { cycles: list }, { 'Cache-Control': 'public, max-age=10' }); + } + + // verified visitors: start (page load) -> seen (after visitSeconds of the page being visible) + if (p === '/api/visit/start' && req.method === 'POST') { + const b = await readBody(req); + if (isBot(req) || req.headers['sec-fetch-site'] === 'cross-site') return json(res, 200, { ticket: null }); + if (limited(req, 'ticket', 120, 3600000)) return json(res, 200, { ticket: null }); + const refRaw = String(b.ref || '').trim() || refCookie(req); + const ref = refRaw ? await resolveRef(refRaw) : null; + const s = session(req); + const t = crypto.randomBytes(12).toString('hex'); + tickets.set(t, { vk: visitorKey(req), iph: ipKey(req), at: Date.now(), ref: ref && (!s || s.address !== ref) ? ref : null, src: srcHost(b.src) }); + if (tickets.size > 50000) { const cut = Date.now() - 1800000; for (const [k, v] of tickets) if (v.at < cut) tickets.delete(k); } + return json(res, 200, { ticket: t, seconds: C.visitSeconds, already: !loop.canCount(visitorKey(req), ipKey(req)).ok }); + } + if (p === '/api/visit/seen' && req.method === 'POST') { + const b = await readBody(req); const t = tickets.get(String(b.ticket || '')); + if (!t || isBot(req) || t.vk !== visitorKey(req)) return json(res, 200, { counted: false, why: 'ticket' }); + const age = Date.now() - t.at; + if (age < C.visitSeconds * 1000 - 300 || Number(b.visibleMs) < C.visitSeconds * 1000 - 300) return json(res, 200, { counted: false, why: 'early' }); + tickets.delete(String(b.ticket)); + if (age > 1800000) return json(res, 200, { counted: false, why: 'ticket' }); + const r = loop.verifiedVisit({ vk: t.vk, iph: t.iph, ref: t.ref, src: t.src }); + return json(res, 200, { counted: r.counted, why: r.why || null, shifted: !!r.shifted, cycled: r.cycled ? r.cycled.bannerId : null, progress: store.state().progress, perShift: C.perShift }); + } + + // wallet sign-in + if (p === '/api/auth/challenge' && req.method === 'POST') { + if (limited(req, 'auth', 30, 600000)) return json(res, 429, { error: 'Too many sign-in attempts. Wait a few minutes.' }); + const b = await readBody(req); if (!ADDR_RE.test(b.address || '')) return json(res, 400, { error: 'Bad address' }); + const a = b.address.toLowerCase(); const nonce = crypto.randomBytes(16).toString('hex'); + const message = C.site + ' wants you to sign in with your wallet:\n' + getAddress(a) + '\n\nViral Banner Blitz sign-in. This signature is free and cannot move funds or approve anything.\n\nChain ID: ' + C.chainId + '\nNonce: ' + nonce + '\nIssued At: ' + new Date().toISOString(); + challenges.set(a, { message, exp: Date.now() + 600000 }); + if (challenges.size > 20000) challenges.clear(); + return json(res, 200, { message }); + } + if (p === '/api/auth/verify' && req.method === 'POST') { + const b = await readBody(req); const a = String(b.address || '').toLowerCase(); const ch = challenges.get(a); + if (!ch || ch.exp < Date.now()) return json(res, 400, { error: 'Sign-in request expired. Tap sign in again.' }); + let rec; try { rec = verifyMessage(ch.message, String(b.signature || '')).toLowerCase(); } catch (e) { return json(res, 400, { error: 'Invalid signature.' }); } + if (rec !== a) return json(res, 400, { error: 'Your wallet signed with a different account (' + rec.slice(0, 6) + '...' + rec.slice(-4) + '). Switch accounts and try again.' }); + challenges.delete(a); + signedIn(a, store.member(a) ? {} : { via: 'wallet' }); + fillUsername(a).catch(() => {}); + return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('vbb.sid', store.mintSession(a), store.SESSION_TTL / 1000, true) }); + } + if (p === '/api/auth/logout' && req.method === 'POST') { + const s = session(req); if (s) store.dropSession(s.token); + return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('vbb.sid', '', 0, true), networksso.offCookie()] }); + } + if (p === '/api/me' && req.method === 'GET') { + const s = session(req); if (!s) return json(res, 200, { signedIn: false }); + const m = store.member(s.address); + return json(res, 200, { signedIn: true, address: s.address, username: m ? m.username : null }); + } + + // -- member API + if (p.startsWith('/api/my')) { + const s = session(req); if (!s) return json(res, 401, { error: 'Sign in first.' }); + const me = s.address; + if (!store.member(me)) signedIn(me, { via: 'wallet' }); + if (p === '/api/my' && req.method === 'GET') { const m = store.member(me); const granted = grantDaily(m); m.lastSeen = Date.now(); return json(res, 200, Object.assign(myData(me), { grantedNow: granted })); } + if (p === '/api/my/upload' && req.method === 'POST') { + if (limited(req, 'upload', 40, 3600000)) return json(res, 429, { error: 'Too many uploads this hour.' }); + let buf; try { buf = await readRaw(req, safety.MAX_UPLOAD + 1); } catch (e) { return json(res, 400, { error: 'The file is over 100 KB.' }); } + const r = safety.checkImage(buf); if (r.error) return json(res, 400, r); + return json(res, 200, { ok: true, img: saveUpload(me, buf, r.info.ext) }); + } + if (p === '/api/my/banners' && req.method === 'POST') { + if (limited(req, 'post', 30, 3600000)) return json(res, 429, { error: 'Too many posts this hour.' }); + const b = await readBody(req); const m = store.member(me); + if (m.credits < 1) return json(res, 400, { error: 'You have no post credits. A free credit arrives each day you sign in.' }); + const waiting = store.bannersOf(me).filter(x => x.state === 'queued').length; + if (waiting >= C.maxQueuedPerMember) return json(res, 400, { error: 'You already have ' + waiting + ' banners waiting. Post again when one enters the loop.' }); + const lk = safety.checkLink(b.link, 'Target link'); if (lk.error) return json(res, 400, lk); + let img = String(b.img || '').trim(); + if (/^\/u\/[a-z0-9-]+\.(png|jpg|gif)$/.test(img)) { + if (!img.slice(3).startsWith(me.slice(2, 10) + '-') || !fs.existsSync(path.join(UPL, img.slice(3)))) return json(res, 400, { error: 'Upload the image again.' }); + } else { + const ic = safety.checkLink(img, 'Image address'); if (ic.error) return json(res, 400, ic); + const f = await safety.fetchImage(ic.url); if (f.error) return json(res, 400, f); + img = saveUpload(me, f.buf, f.info.ext); + } + if (C.linkProbe) { const pr = await safety.probeLink(lk.url); if (pr.error) return json(res, 400, pr); } + if (store.member(me).credits < 1) return json(res, 400, { error: 'You have no post credits.' }); // spent meanwhile by another tab + m.credits -= 1; + const nb = loop.post(me, img, lk.url, 'credit'); + return json(res, 200, { ok: true, banner: Object.assign({ id: nb.id }, loop.placeOf(nb)), credits: m.credits }); + } + return json(res, 404, { error: 'Not found' }); + } + + // -- admin (x-admin-token: ADMIN_TOKEN) + if (p.startsWith('/api/admin/')) { + if (!isAdmin(req)) return json(res, 401, { error: 'no' }); + 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 }, + 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 }, + totals: S.totals, ledger: { entries: L.length, views: L.reduce((x, e) => x + e.views, 0), viewsByStatus: byStatus, credited: 0 }, + members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, docstore: docstore.view() }); + } + if (p === '/api/admin/ledger' && req.method === 'GET') { + const n = Math.min(2000, Math.max(1, Number(u.searchParams.get('n')) || 200)); const L = store.ledger(); + const per = {}; for (const e of L) { const k = e.owner; const r = per[k] || (per[k] = { address: k, username: e.username, cycles: 0, views: 0 }); r.cycles++; r.views += e.views; if (e.username) r.username = e.username; } + return json(res, 200, { entries: L.slice(-n).reverse(), members: Object.values(per).sort((a, b) => b.views - a.views), note: 'v1 records rewards only; nothing has been credited to InstantAdPay or LinkSpin.' }); + } + return json(res, 404, { error: 'Not found' }); + } + + if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' }); + res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' })); + return res.end('Not found

Not found. Back to the loop

'); + } catch (e) { + console.error('request', p, e.message); + if (!res.headersSent) json(res, 500, { error: 'Server error' }); + } +}); +function saveUpload(owner, buf, ext) { + const name = owner.slice(2, 10) + '-' + crypto.randomBytes(6).toString('hex') + ext; + fs.writeFileSync(path.join(UPL, name), buf); // uploads stay files on the volume (docstore keeps the uploads folder on disk) + return '/u/' + name; +} + +(async () => { + await docstore.init({ splits: store.SPLITS }); // before anything reads its data + process.on('SIGTERM', () => { store.flush(); docstore.drain(8000).finally(() => process.exit(0)); }); + store.load(); + loop.init({ onCycle: (b, e) => console.log('cycle', 'banner #' + b.id, e.views + ' network views recorded') }); + store.pruneVisits(); loop.rebuildIndex(); + setInterval(() => { if (store.pruneVisits()) loop.rebuildIndex(); }, 3600000).unref(); + server.listen(C.port, () => console.log('Viral Banner Blitz on :' + C.port + ' loop ' + C.loopSize + ', ' + C.perShift + ' visitors per shift, store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)'))); +})().catch(e => { console.error('start failed:', e.message); process.exit(1); }); +process.on('SIGINT', () => { store.flush(); process.exit(0); }); diff --git a/store.js b/store.js new file mode 100644 index 0000000..6fa1107 --- /dev/null +++ b/store.js @@ -0,0 +1,111 @@ +// VBB data. One document (vbb.json) holds the loop, the queue, members, sessions and daily counters; three growing +// collections are row tables when the app runs on MySQL (docstore splits): banners, the cycle reward ledger and the +// verified visits. Without DOCSTORE_URL (local prototype only) everything stays in the one file, written atomically +// (tmp + rename). Marty's rule (2026-11-13): MySQL is the standard; never launch on files. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const cfgMod = require('./config'); +const docstore = require('./docstore'); + +const DOC = 'vbb.json'; +const SPLITS = [ + { doc: DOC, field: 'banners', table: 'vbb_banners', key: 'id', ts: 'createdAt' }, + { doc: DOC, field: 'ledger', table: 'vbb_ledger', key: 'id', ts: 'at' }, + { doc: DOC, field: 'visits', table: 'vbb_visits', key: 'id', ts: 'at' } +]; +const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s])); + +let S = null, saveT = null, rowMode = false; +const byId = new Map(); // banner id -> banner +const FILE = () => path.join(cfgMod.get().dataDir, DOC); + +function load() { + try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; } + S = Object.assign({ v: 1, seq: { banner: 0, ledger: 0, visit: 0 }, loop: [], queue: [], progress: 0, + totals: { shifts: 0, cycles: 0, visits: 0, posts: 0, views: 0 }, daily: {}, members: {}, sessions: {}, banners: [], ledger: [], visits: [] }, S || {}); + rowMode = docstore.isOn(); + if (rowMode) for (const sp of SPLITS) S[sp.field] = (docstore.rows(sp.table) || []).slice(); + byId.clear(); for (const b of S.banners) byId.set(b.id, b); + const now = Date.now(); + for (const [k, s] of Object.entries(S.sessions)) if (s.expires < now) delete S.sessions[k]; +} +function save(now) { + if (saveT && !now) return; + const run = () => { + saveT = null; + try { + const out = rowMode ? Object.assign({}, S, Object.fromEntries(SPLITS.map(sp => [sp.field, []]))) : S; + const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 }); fs.renameSync(tmp, FILE()); + } catch (e) { console.error('store save failed', e.message); } + }; + if (now) { clearTimeout(saveT); run(); } else saveT = setTimeout(run, 800); +} +function flush() { save(true); } +const state = () => S; + +// a row in a growing collection changed: one row write on MySQL, the document on files +function putRow(field, item) { + if (rowMode) { const sp = TABLE[field]; docstore.rowPut(sp.table, item[sp.key], item[sp.ts], item); } + save(); +} +function dropRows(field, ids) { + if (!ids.length) return; + const set = new Set(ids); S[field] = S[field].filter(x => !set.has(x[TABLE[field].key])); + if (rowMode) docstore.rowDel(TABLE[field].table, ids); + save(); +} +function nextId(kind) { S.seq[kind] = (S.seq[kind] || 0) + 1; return S.seq[kind]; } + +// ---- Central time (Marty: everything on US Central) ---- +const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' }); +function ctDay(ts) { const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value])); return p.year + '-' + p.month + '-' + p.day; } +// week key = the Central-time date of that week's Monday +function ctWeek(ts) { + const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value])); + const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0; + const d = new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)); + return d.toISOString().slice(0, 10); +} +function bump(k, n) { const day = ctDay(); const d = S.daily[day] || (S.daily[day] = {}); d[k] = (d[k] || 0) + (n || 1); save(); } +function today() { return S.daily[ctDay()] || {}; } + +// ---- banners ---- +function banner(id) { return byId.get(Number(id)) || null; } +function addBanner(b) { b.id = nextId('banner'); b.createdAt = Date.now(); S.banners.push(b); byId.set(b.id, b); putRow('banners', b); return b; } +function saveBanner(b) { putRow('banners', b); } +function bannersOf(addr) { const a = String(addr).toLowerCase(); return S.banners.filter(b => b.owner === a); } + +// ---- ledger (cycle rewards: recorded only in v1, no crediting yet) ---- +function addLedger(e) { e.id = 'c' + nextId('ledger'); e.at = Date.now(); S.ledger.push(e); putRow('ledger', e); return e; } +function ledger() { return S.ledger; } + +// ---- verified visits ---- +function addVisit(v) { v.id = 'v' + nextId('visit'); v.at = v.at || Date.now(); S.visits.push(v); putRow('visits', v); return v; } +function visits() { return S.visits; } +// keep 15 days: the 24-hour check and this week's + last week's leaderboards +function pruneVisits() { const cut = Date.now() - 15 * 86400000; const old = S.visits.filter(v => v.at < cut).map(v => v.id); dropRows('visits', old); return old.length; } + +// ---- members ---- +function member(addr) { return S.members[String(addr || '').toLowerCase()] || null; } +function upsertMember(addr, patch) { + const a = String(addr).toLowerCase(); + const m = S.members[a] || (S.members[a] = { address: a, username: null, joinedAt: Date.now(), credits: 0, freeDay: null, via: null }); + Object.assign(m, patch || {}); m.lastSeen = Date.now(); save(); return m; +} +function memberByName(name) { + const n = String(name || '').toLowerCase(); if (!n) return null; + for (const m of Object.values(S.members)) if (m.username && m.username.toLowerCase() === n) return m; + return null; +} +function members() { return Object.values(S.members); } + +// ---- sessions ---- +const SESSION_TTL = 7 * 24 * 3600000; +function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: address.toLowerCase(), expires: Date.now() + SESSION_TTL }; save(); return token; } +function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; } +function dropSession(token) { delete S.sessions[token]; save(); } + +module.exports = { SPLITS, load, flush, save, state, ctDay, ctWeek, bump, today, banner, addBanner, saveBanner, bannersOf, addLedger, ledger, + addVisit, visits, pruneVisits, member, upsertMember, memberByName, members, mintSession, session, dropSession, SESSION_TTL };