13255c6fda
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
579 lines
51 KiB
JavaScript
579 lines
51 KiB
JavaScript
// ViralAdSource web app (viraladsource.com rebuild, Marty approved 2026-11-16). Plain Node http server, no framework (the InstantAdPay /
|
|
// Downline Banners / VBB / ViralAdBlitz pattern).
|
|
// "Every ad has a source. Watch yours travel." A network member (network sign-in through the hub, membership checked with the hub)
|
|
// posts one free text ad. Anyone reshares it with their own unique reshare link (/s/<code>); each reshare is a branch of the ad's
|
|
// family tree (tree.js). Rewards are for verified results only (config.js): L1 Boost resharer cut on chain (VASShop), L2 verified
|
|
// brand-new network member (signup.js, payouts OFF until Marty confirms), L3 verified views -> ad credits (wire.js).
|
|
// Pages: / (front), /s/<code> (an ad through a reshare link), /a/<id> (an ad at its source), /<username> (a member's ad), /my, /boost,
|
|
// /rewards, /join, /confirm, /ledger, /contract, /promote, /terms, /disclaimer, /privacy, /admin.
|
|
'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(C.dataDir, { recursive: true });
|
|
const docstore = require('./docstore'); docstore.install(C.dataDir);
|
|
const store = require('./store');
|
|
const wire = require('./wire');
|
|
const tree = require('./tree');
|
|
const signup = require('./signup');
|
|
const safety = require('./safety');
|
|
const networksso = require('./networksso');
|
|
const shop = require('./shop');
|
|
const promokit = require('./promokit');
|
|
const hubreport = require('./hubreport');
|
|
const hubpeople = require('./hubpeople');
|
|
const hubevents = require('./hubevents');
|
|
const hubline = require('./hubline');
|
|
const proof = require('./proof');
|
|
const netsites = require('./netsites');
|
|
const netdeals = require('./netdeals'); // Network Weekend ribbon feed (2026-11-17)
|
|
const weekend = require('./weekend'); // Network Weekend +3 board days per Boost (2026-11-17)
|
|
const lstrack = require('./lstrack');
|
|
const chatbot = require('./chatbot');
|
|
const adwriter = require('./hubadwriter'); // the network AI ad writer, asked through the hub (2026-11-17)
|
|
|
|
const PUB = path.join(__dirname, 'public');
|
|
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/;
|
|
const CODE_RE = /^[a-z0-9]{8}$/;
|
|
const PAGE_RE = /^\/([A-Za-z0-9_.-]{2,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);
|
|
wire.setSecret(SECRET);
|
|
// the staging-only test switch can never run on the real domain
|
|
const TEST_SWITCH = C.staging && !/(^|\.)viraladsource\.com$/i.test(C.site);
|
|
|
|
// ---- http helpers ----
|
|
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp',
|
|
'.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 https://linkspin.app https://polhunter.com; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
|
|
+ "img-src 'self' data: blob: https:; connect-src 'self' https://linkspin.app https://polhunter.com 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, code) {
|
|
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(code || 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' : ''); }
|
|
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']);
|
|
const visitorKey = req => hash('vk|' + ip(req) + '|' + (req.headers['user-agent'] || ''));
|
|
const ipKey = req => hash('ip|' + ip(req));
|
|
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 membership through the hub (InstantAdPay's lookup only while the hub is unreachable) ----
|
|
const netCache = new Map();
|
|
async function netMember(q) {
|
|
const h = q.u ? await hubpeople.byRef(q.u) : await hubpeople.byWallet(q.a);
|
|
if (h.ok) { const a = hubpeople.wallet(h.person); return a ? { address: a, username: h.person.username ? String(h.person.username) : null, hubId: h.person.id || null, via: 'hub' } : null; }
|
|
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), via: 'iap' }; } catch (e) { return null; }
|
|
netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear();
|
|
return m;
|
|
}
|
|
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 netVerified = m => !!m && m.netOk === true;
|
|
async function verifyNet(addr, email) {
|
|
const m = store.member(addr); if (!m || netVerified(m)) return;
|
|
const h = await hubpeople.byWallet(addr);
|
|
let known = h.ok && !!h.person, down = !h.ok;
|
|
if (!known && !down && email) { const e = await hubpeople.resolve({ email: String(email).trim().toLowerCase() }); if (e.ok) known = !!(e.person && !e.person.blocked); else down = true; }
|
|
if (!known && down) { const n = await netMember({ a: addr }).catch(() => null); known = (n && n.address === m.address) || m.via === 'iap' || m.via === 'linkspin' || m.via === 'hub'; }
|
|
if (known) { store.upsertMember(addr, { netOk: true, netAt: Date.now(), netBy: down ? 'fallback' : 'hub' }); await fillUsername(addr).catch(() => {}); }
|
|
}
|
|
// a confirmed L2 sign-up written to the hub (HUB_JOIN=1 only): POST /v1/join {email, ref, username}, sponsor = the resharer
|
|
async function hubJoin(email, ref, username) {
|
|
if (!hubpeople.on()) return { ok: false };
|
|
const raw = JSON.stringify({ email, ref: ref || undefined, username: username || undefined }); const ts = String(Date.now());
|
|
const sig = crypto.createHmac('sha256', String(process.env.HUB_SECRET).trim()).update(ts + '\n' + raw).digest('hex');
|
|
const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + '/v1/join', { method: 'POST', body: raw, signal: AbortSignal.timeout(8000),
|
|
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || 'viraladsource').trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
|
|
if (r.status !== 200) return { ok: false, status: r.status };
|
|
const j = await r.json(); return { ok: true, created: !!j.created, person: j.person || null };
|
|
}
|
|
const session = req => store.session(cookies(req)['vas.sid']);
|
|
|
|
networksso.init({ self: C.siteId, 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; }
|
|
store.upsertMember(v.wallet, patch);
|
|
await verifyNet(v.wallet, email).catch(() => {});
|
|
store.seenOn(v.wallet, visitorKey(req), ipKey(req));
|
|
return cookie('vas.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true);
|
|
},
|
|
landing: to => to, signinPath: to => to });
|
|
hubevents.init({ dataDir: C.dataDir, site: 'viraladsource', end: who => store.endSessions(x => who.match(x) || who.match(store.member(x.address)), who.before) });
|
|
|
|
// ---- old site links (the YourFreeWorld site): /?<old username> and /index.php?<old> -> that person's ad here (oldrefs.json, matched
|
|
// by email to the hub, loaded by POST /api/admin/oldrefs at the domain switch); /splashpg.php, /lcp.php ?r=<old> the same; any other *.php -> / ----
|
|
let oldRefs = { at: 0, map: {} };
|
|
function oldRefMap() {
|
|
if (Date.now() - oldRefs.at < 60000) return oldRefs.map;
|
|
let m = {}; try { m = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'oldrefs.json'), 'utf8')) || {}; } catch (e) {}
|
|
oldRefs = { at: Date.now(), map: m }; return m;
|
|
}
|
|
function oldLink(u) {
|
|
const p = u.pathname; const bare = u.search.slice(1).split('&')[0];
|
|
if (p === '/' || p === '/index.php') { if (!/^[A-Za-z0-9_.-]{2,40}$/.test(bare)) return p === '/' ? null : '/'; }
|
|
else if (!/\.php$/i.test(p)) return null;
|
|
const lp = p.toLowerCase();
|
|
const old = (lp === '/splashpg.php' || lp === '/lcp.php') ? String(u.searchParams.get('r') || '') : (lp === '/' || lp === '/index.php') ? bare : '';
|
|
const net = /^[A-Za-z0-9_.-]{2,40}$/.test(old) ? oldRefMap()[old.toLowerCase()] : null;
|
|
return net ? '/' + encodeURIComponent(net) : '/';
|
|
}
|
|
|
|
const PAGES = { '/': 'index.html', '/my': 'my.html', '/boost': 'boost.html', '/rewards': 'rewards.html', '/join': 'join.html', '/confirm': 'confirm.html', '/ledger': 'ledger.html',
|
|
'/contract': 'contract.html', '/admin': 'admin.html', '/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html' };
|
|
const RESERVED = new Set(['api', 'assets', 'art', 'go', 'r', 's', 'a', 'sso', 'health', 'promote', 'sitemap.xml', 'robots.txt', 'favicon.ico', 'index.php', 'my', 'boost', 'rewards', 'join', 'confirm', 'ledger', 'contract', 'admin', 'terms', 'disclaimer', 'privacy', 'how', 'tree']);
|
|
const challenges = new Map();
|
|
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 ''; } };
|
|
// the reshare tag a visitor carries: "<code>.<ms>" (last touch, VIA_DAYS)
|
|
function viaOf(req) { const v = String(cookies(req)['vas.via'] || ''); const m = /^([a-z0-9]{8})\.(\d{10,14})$/.exec(v); return m ? { code: m[1], at: Number(m[2]) } : null; }
|
|
const viaCookie = code => cookie('vas.via', code + '.' + Date.now(), C.viaDays * 86400, false);
|
|
|
|
function issueTicket(req, page, shown, src, via) {
|
|
if (isBot(req) || req.headers['sec-fetch-site'] === 'cross-site' || limited(req, 'ticket', 240, 3600000)) return null;
|
|
const s = session(req); const t = crypto.randomBytes(12).toString('hex');
|
|
tickets.set(t, { vk: visitorKey(req), iph: ipKey(req), at: Date.now(), page, shown, src: srcHost(src), via: via || null, viewer: s ? s.address : null });
|
|
if (tickets.size > 50000) { const cut = Date.now() - 1800000; for (const [k, v] of tickets) if (v.at < cut) tickets.delete(k); }
|
|
return t;
|
|
}
|
|
const todayStats = () => { const t = store.today(); return { views: t.views || 0, vclicks: t.vclicks || 0, reshares: t.reshares || 0, joins: t.confirms || 0, ads: store.liveAds().length }; };
|
|
// a join link to InstantAdPay or LinkSpin carries the way back here (2026-11-17, Marty: "it never had a return path back"): the
|
|
// provider remembers ?return=<this site>&to=/my and, after the sign-up or sign-in (and the wallet step), sends the member back
|
|
const withReturn = url => { try { const x = new URL(url); if (!/^(www\.)?(instantadpay\.com|linkspin\.app)$/.test(x.hostname) && x.origin !== new URL(C.iapBase).origin) return url; x.searchParams.set('return', C.siteId); x.searchParams.set('to', '/my'); return x.toString(); } catch (e) { return url; } };
|
|
const joinUrl = ref => withReturn(ref ? C.joinUrl.split('{ref}').join(encodeURIComponent(ref)) : C.joinUrl.replace(/\/join\/\{ref\}.*$/, '/').replace(/[?&]ref=\{ref\}/, '').split('{ref}').join(''));
|
|
const MACRO = /\{(clickid|placement)\}|%7B(clickid|placement)%7D/gi;
|
|
function clickLink(a, placement) {
|
|
const l = String(a.link || ''); if (!l.match(MACRO)) return l;
|
|
const v = { clickid: crypto.randomBytes(8).toString('hex'), placement: String(placement || 'site').replace(/[^a-z0-9-]/gi, '').slice(0, 20) || 'site' };
|
|
return l.replace(MACRO, (x, p1, p2) => v[(p1 || p2).toLowerCase()]);
|
|
}
|
|
function cleanText(s, max) { return String(s == null ? '' : s).replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(/[–—]/g, '-').replace(/\s+/g, ' ').trim().slice(0, max + 1); }
|
|
const uname = a => { const m = store.member(a); return m && m.username ? m.username : null; };
|
|
const shareUrl = s => 'https://' + C.site + '/s/' + s.id;
|
|
function myEarned(me) {
|
|
let wei = 0n; const items = [];
|
|
for (const x of wire.purchases()) for (const p of x.pays || []) if (p.to === me && p.kind > 0) { try { wei += BigInt(p.wei); } catch (e) {} items.push({ tx: String(x.key).split(':')[0], at: (x.blockAt ? x.blockAt * 1000 : x.at), kind: p.kind, depth: p.depth, wei: p.wei, failed: !!p.failed, buyerName: uname(x.buyer) }); }
|
|
return { wei: wei.toString(), items: items.sort((a, b) => (b.at || 0) - (a.at || 0)).slice(0, 50) };
|
|
}
|
|
|
|
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' && await networksso.page(req, res, u)) return;
|
|
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
|
|
if ((p === '/api/promo-kit' || p === '/promote') && promokit.handle(req, res, u, sendFile)) return;
|
|
if ((p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) && await chatbot.handle(req, res, p, u, { json, readBody, isAdmin })) return;
|
|
|
|
if (req.method === 'GET' || req.method === 'HEAD') {
|
|
if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files' });
|
|
{ const to = oldLink(u); if (to) { res.writeHead(301, { Location: to, 'Cache-Control': 'no-store' }); return res.end(); } }
|
|
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('vas.ref', ref, 30 * 86400, false);
|
|
if (p === '/my' || p === '/admin') ex['X-Frame-Options'] = 'DENY';
|
|
if (p === '/how' || p === '/tree') { res.writeHead(301, { Location: '/#how' }); return res.end(); }
|
|
return sendFile(res, path.join(PUB, PAGES[p]), ex);
|
|
}
|
|
if (p === '/how' || p === '/tree') { res.writeHead(301, { Location: '/#' + p.slice(1) }); return res.end(); }
|
|
// an ad through a reshare link: tag the visitor with the share (last touch), then the ad page
|
|
const sm = /^\/s\/([a-z0-9]{8})\/?$/.exec(p);
|
|
if (sm) {
|
|
const s = store.share(sm[1]); const a = s ? store.ad(s.adId) : null;
|
|
if (!s || !a || a.status === 'removed') { res.writeHead(302, { Location: '/' }); return res.end(); }
|
|
return sendFile(res, path.join(PUB, 'ad.html'), { 'Set-Cookie': viaCookie(s.id) });
|
|
}
|
|
const am = /^\/a\/(\d{1,9})\/?$/.exec(p);
|
|
if (am) { const a = store.ad(am[1]); if (!a || a.status === 'removed') { res.writeHead(302, { Location: '/' }); return res.end(); } const r = tree.rootOf(a); res.writeHead(302, { Location: '/s/' + r.id }); return res.end(); }
|
|
if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); }
|
|
if (p === '/sitemap.xml') {
|
|
const day = new Date().toISOString().slice(0, 10);
|
|
const urls = ['/', '/rewards', '/boost', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy'].map(x => '<url><loc>https://' + C.site + x + '</loc><lastmod>' + day + '</lastmod></url>').join('');
|
|
res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }));
|
|
return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>');
|
|
}
|
|
if (p === '/robots.txt') { res.writeHead(200, headers({ 'Content-Type': 'text/plain; charset=utf-8' })); return res.end(C.staging ? 'User-agent: *\nDisallow: /\n' : 'User-agent: *\nAllow: /\nDisallow: /my\nDisallow: /admin\nDisallow: /api/\nDisallow: /go/\nDisallow: /sso/\nDisallow: /s/\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);
|
|
}
|
|
// click relay: /go/<ad>?s=<share>&v=<verified token>&p=<placement> -> the ad's link (LinkSpin links carry the branch: s2 / s3)
|
|
const gm = /^\/go\/(\d{1,9})$/.exec(p);
|
|
if (gm) {
|
|
const a = store.ad(gm[1]); if (!a || a.status === 'removed') { res.writeHead(302, { Location: '/' }); return res.end(); }
|
|
const pl = String(u.searchParams.get('p') || '').slice(0, 20);
|
|
const sc = String(u.searchParams.get('s') || ''); let s = CODE_RE.test(sc) ? store.share(sc) : null; if (s && s.adId !== a.id) s = null;
|
|
if (!isBot(req) && !limited(req, 'click', 600, 3600000)) { const vk = visitorKey(req); const ss = session(req); wire.click(a, vk, wire.vtokenOk(vk, u.searchParams.get('v')), ss ? ss.address : null, s, pl); }
|
|
const dest = lstrack.dest(a) || clickLink(a, pl);
|
|
res.writeHead(302, { Location: lstrack.withBranch(dest, s, s ? uname(s.owner) : null), 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end();
|
|
}
|
|
// a member's ad: viraladsource.com/<network username> -> their ad at its source (with the ref cookie); no ad yet -> the front page
|
|
const pm = PAGE_RE.exec(p);
|
|
if (pm && !RESERVED.has(pm[1].toLowerCase()) && !/\.php$/i.test(pm[1])) {
|
|
const name = pm[1]; const m = store.memberByName(name); const a = m ? store.adOf(m.address) : null;
|
|
if (a && a.status === 'live') { const r = tree.rootOf(a); res.writeHead(302, { Location: '/s/' + r.id, 'Set-Cookie': cookie('vas.ref', name, 30 * 86400, false) }); return res.end(); }
|
|
const h = m ? { ok: true, person: m } : await hubpeople.byRef(name.toLowerCase()).catch(() => ({ ok: false }));
|
|
if (h.ok && h.person) { res.writeHead(302, { Location: '/?ref=' + encodeURIComponent(name) }); return res.end(); }
|
|
}
|
|
}
|
|
|
|
// -- public API
|
|
if (p === '/api/config' && req.method === 'GET') {
|
|
const live = await shop.liveRules().catch(() => null);
|
|
return json(res, 200, { site: C.site, siteName: C.siteName, staging: C.staging, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId,
|
|
boost: Object.assign({}, C.boost, { days: C.boost.days + weekend.bonusDays(), weekendDays: weekend.bonusDays() }), split: live ? { resharerBps: live.resharerBps, potBps: live.potBps, levelBps: live.levelBps, maxDepth: 20, live: true } : Object.assign({ proposal: true }, C.split),
|
|
reward: { cents: C.reward.cents, dailyCap: C.reward.dailyCap, payouts: C.reward.payouts, tiers: C.reward.tiers, proposal: true }, credits: C.credits, visitSeconds: C.visitSeconds, ad: C.ad,
|
|
sso: networksso.enabled() || networksso.hubOn(), shop: { live: shop.watching() && shop.signerOn(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, joinUrl: joinUrl(''),
|
|
aiWriter: await adwriter.status().then(w => (w.on ? { daily: w.daily } : null)) });
|
|
}
|
|
// everything a page shows, with its visit ticket. page=front|share|other, s=<share code> on share pages
|
|
if (p === '/api/wire' && req.method === 'GET') {
|
|
const kind = ['front', 'share'].includes(u.searchParams.get('page')) ? u.searchParams.get('page') : 'other';
|
|
const out = { today: todayStats(), week: wire.weekStats() }; const shown = []; let via = null;
|
|
const used = new Set();
|
|
if (kind === 'front') { out.board = wire.board(); out.board.forEach(x => { shown.push({ id: x.id, share: null, slot: 'board' }); used.add(x.id); }); }
|
|
if (kind === 'share') {
|
|
const s = store.share(String(u.searchParams.get('s') || '')); const a = s ? store.ad(s.adId) : null;
|
|
if (!s || !a || a.status !== 'live') return json(res, 404, { error: 'That ad is not running right now.' });
|
|
const anc = tree.ancestry(s); const me = session(req);
|
|
out.ad = wire.adCard(a, { href: '/go/' + a.id + '?s=' + s.id });
|
|
out.share = { code: s.id, step: s.step, resharer: s.step > 0 ? uname(s.owner) : null, owner: uname(a.owner), chain: anc.slice(0, 6).map(x => uname(x.owner)).filter(Boolean), branchCount: Math.max(0, store.sharesOf(a.id).length - 1) };
|
|
if (me) { const mine = store.shareOf(a.id, me.address); out.mine = mine ? { code: mine.id, url: shareUrl(mine), own: me.address === a.owner } : null; }
|
|
shown.push({ id: a.id, share: s.id, slot: 'share' }); used.add(a.id); via = s.id;
|
|
out.joinPath = '/join';
|
|
}
|
|
// "Featured with credits" places on every page
|
|
const cp = wire.creditPicks(C.credits.slots, used); out.featured = cp.map(a => wire.adCard(a, { credit: true }));
|
|
cp.forEach(a => shown.push({ id: a.id, share: null, slot: 'credit' }));
|
|
const hunt = u.searchParams.get('hunt') === '1' || srcHost(u.searchParams.get('src')) === 'polhunter.com';
|
|
out.ticket = hunt ? null : issueTicket(req, kind === 'share' ? 'share:' + via : kind, shown, u.searchParams.get('src'), via);
|
|
if (hunt) { out.hunt = true; store.bump('huntVisits'); }
|
|
out.seconds = C.visitSeconds;
|
|
return json(res, 200, out);
|
|
}
|
|
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, { verified: 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, { verified: false, why: 'early' });
|
|
tickets.delete(String(b.ticket));
|
|
if (age > 1800000) return json(res, 200, { verified: false, why: 'ticket' });
|
|
const r = wire.verify(t);
|
|
return json(res, 200, Object.assign(r, r.verified ? { vt: wire.vtoken(t.vk) } : {}));
|
|
}
|
|
if (p === '/api/ledger' && req.method === 'GET') return json(res, 200, proof.ledger(u.searchParams.get('n')), { 'Cache-Control': 'public, max-age=10' });
|
|
if (p === '/api/contract' && req.method === 'GET') { if (limited(req, 'contract', 600, 3600000)) return json(res, 429, { error: 'Too many requests' }); return json(res, 200, await proof.contract(), { 'Cache-Control': 'public, max-age=60' }); }
|
|
if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res);
|
|
if (p === '/api/network-deals' && req.method === 'GET') return netdeals.handle(req, res, 'viraladsource'); // Network Weekend ribbon
|
|
if (p === '/api/recent' && req.method === 'GET') {
|
|
const cut = Date.now() - 30 * 60000;
|
|
const ads = store.liveAds().filter(a => a.createdAt > cut).slice(-6).map(a => ({ kind: 'ad', key: 'a' + a.id, at: a.createdAt, name: uname(a.owner), headline: a.headline }));
|
|
const rs = store.state().shares.filter(s => s.step > 0 && s.createdAt > cut).slice(-6).map(s => ({ kind: 'reshare', key: 's' + s.id, at: s.createdAt, name: uname(s.owner), step: s.step }));
|
|
const boosts = proof.ledger(10).items.filter(x => x.at && x.at > cut).map(x => ({ kind: 'boost', key: 'b' + x.tx + x.orderId, at: x.at, name: x.buyerName, resharer: x.resharer ? x.resharer.name : null }));
|
|
return json(res, 200, { items: ads.concat(rs, boosts).sort((a, b) => b.at - a.at) }, { 'Cache-Control': 'public, max-age=10' });
|
|
}
|
|
if (p === '/api/quote' && req.method === 'GET') {
|
|
if (!shop.watching()) return json(res, 503, { error: 'Boosts are not open yet.' });
|
|
if (limited(req, 'quote', 600, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
|
|
const qty = Number(u.searchParams.get('qty') || 1);
|
|
if (!Number.isInteger(qty) || qty < 1 || qty > C.boost.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.boost.maxQty + ' Boosts.' });
|
|
try { return json(res, 200, Object.assign({ usd: C.boost.usd * qty, days: (C.boost.days + weekend.bonusDays()) * qty }, await shop.quote(C.boost.sku, qty))); } catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
|
|
}
|
|
if (p === '/api/gas' && req.method === 'GET') { try { return json(res, 200, shop.watching() ? await shop.fees() : {}); } catch (e) { return json(res, 200, {}); } }
|
|
if (/^\/api\/tx\/0x[0-9a-fA-F]{64}$/.test(p) && req.method === 'GET') {
|
|
if (!shop.watching() || limited(req, 'tx', 1200, 3600000)) return json(res, 200, { found: false });
|
|
try { return json(res, 200, await shop.receipt(p.slice(8))); } catch (e) { return json(res, 200, { found: false }); }
|
|
}
|
|
// L2: join the network free through a reshare link. GET /api/join/form -> a form token (when the form was shown);
|
|
// POST /api/join {email, username, form} -> confirm mail (staging: no mail); POST /api/confirm {t}
|
|
if (p === '/api/join/form' && req.method === 'GET') {
|
|
const via = viaOf(req); const s = via ? store.share(via.code) : null; const a = s ? store.ad(s.adId) : null;
|
|
const t = Date.now() + '.' + hash('form|' + Date.now() + '|' + visitorKey(req)).slice(0, 16);
|
|
return json(res, 200, { form: t, via: s ? { resharer: s.step > 0 ? uname(s.owner) : null, owner: a ? uname(a.owner) : null, headline: a ? a.headline : null } : null, mail: !!C.mail.url, staging: C.staging });
|
|
}
|
|
if (p === '/api/join' && req.method === 'POST') {
|
|
if (isBot(req) || limited(req, 'join', 8, 3600000)) return json(res, 429, { error: 'Too many sign-ups from this connection. Try again later.' });
|
|
const b = await readBody(req); const via = viaOf(req);
|
|
const fm = /^(\d{13})\.([0-9a-f]{16})$/.exec(String(b.form || ''));
|
|
const formOk = fm && hash('form|' + fm[1] + '|' + visitorKey(req)).slice(0, 16) === fm[2];
|
|
if (!formOk) return json(res, 400, { error: 'Reload the page and try again.' });
|
|
if (session(req)) return json(res, 400, { error: 'You are already signed in with a network account.' });
|
|
const r = await signup.join({ email: b.email, username: b.username, share: via ? via.code : null, vk: visitorKey(req), iph: ipKey(req), ua: req.headers['user-agent'], formMs: Date.now() - Number(fm[1]), clickAt: via ? via.at : null });
|
|
if (r.error) return json(res, 400, r);
|
|
return json(res, 200, { ok: true, mailed: r.mailed, staging: C.staging && !r.mailed });
|
|
}
|
|
if (p === '/api/confirm' && req.method === 'POST') {
|
|
if (limited(req, 'confirm', 30, 3600000)) return json(res, 429, { error: 'Too many tries.' });
|
|
const b = await readBody(req); const r = await signup.confirm(String(b.t || ''));
|
|
if (r.error) return json(res, 400, r);
|
|
return json(res, 200, { ok: true, status: r.signup.status, joinUrl: joinUrl(''), signIn: '/my' });
|
|
}
|
|
|
|
// 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\nViralAdSource 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);
|
|
store.upsertMember(a, store.member(a) ? {} : { via: 'wallet' });
|
|
await verifyNet(a).catch(() => {});
|
|
store.seenOn(a, visitorKey(req), ipKey(req));
|
|
return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('vas.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('vas.sid', '', 0, true), networksso.offCookie()] });
|
|
}
|
|
if (p === '/api/auth/logout-everywhere' && req.method === 'POST') {
|
|
const s = session(req); let hub = { ok: false };
|
|
if (s) { hub = await networksso.signOutEverywhere(s); store.endSessions(x => x.address === s.address, Date.now() + 1000); }
|
|
return json(res, 200, { ok: true, everywhere: !!hub.ok }, { 'Set-Cookie': [cookie('vas.sid', '', 0, true), networksso.offCookie()] });
|
|
}
|
|
if (p === '/api/hub/events' && req.method === 'POST') {
|
|
let raw = ''; try { raw = (await readRaw(req, 256 * 1024)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
|
|
const r = await hubevents.receive(req.headers, raw); return json(res, r.status, r.body);
|
|
}
|
|
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, netVerified: netVerified(m), test: !!(m && m.testMember) });
|
|
}
|
|
|
|
// -- 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)) store.upsertMember(me, { via: 'wallet' });
|
|
store.seenOn(me, visitorKey(req), ipKey(req)); // the L2 "not the resharer's own device or connection" check
|
|
if (p === '/api/my' && req.method === 'GET') {
|
|
await verifyNet(me).catch(() => {}); const m = store.member(me);
|
|
const a = store.adOf(me); const root = a && a.status !== 'removed' ? tree.rootOf(a) : null;
|
|
let ls = null;
|
|
if (a) { const stt = lstrack.state(a); ls = { on: lstrack.on(), track: a.track !== false, state: stt, link: stt === 'tracked' ? a.ls.link : null, clicks: null };
|
|
if (stt === 'tracked' && m.username) { const cs = await lstrack.clicks(m.username).catch(() => null); if (cs && cs[String(a.id)]) ls.clicks = cs[String(a.id)]; } }
|
|
const mine = store.sharesBy(me).filter(x => x.step > 0).sort((x, y) => y.createdAt - x.createdAt).slice(0, 100).map(x => { const ad = store.ad(x.adId); return { code: x.id, url: shareUrl(x), step: x.step, adId: x.adId, headline: ad ? ad.headline : null, live: !!(ad && ad.status === 'live'), owner: ad ? uname(ad.owner) : null, views: x.views || 0, clicks: x.vclicks || 0, signups: x.signups || 0, boosts: x.boosts || 0, under: x.children || 0 }; });
|
|
const cr = store.credits(me);
|
|
return json(res, 200, { address: me, username: m.username, netVerified: netVerified(m), test: !!m.testMember,
|
|
ad: a ? { id: a.id, headline: a.headline, line1: a.line1, line2: a.line2, link: a.link, status: a.status, views: a.views || 0, clicks: a.clicks || 0, vclicks: a.vclicks || 0, createdAt: a.createdAt, track: a.track !== false, spin: !!a.spin, boostedUntil: wire.boostedUntil(a.id) || null } : null,
|
|
source: root ? { code: root.id, url: shareUrl(root) } : null, tree: a ? tree.tree(a.id) : null, linkspin: ls, reshares: mine,
|
|
credits: { earned: cr.earned, spent: cr.spent, balance: store.creditBalance(me), views: cr.views, nextAt: C.credits.views - (cr.views % C.credits.views), per: C.credits.per, every: C.credits.views },
|
|
rewards: signup.mine(me), boosts: wire.purchases().filter(b => b.buyer === me).sort((x, y) => (y.at || 0) - (x.at || 0)).map(wire.boostView), earned: myEarned(me),
|
|
joinUrl: joinUrl(''), boost: Object.assign({}, C.boost, { days: C.boost.days + weekend.bonusDays(), weekendDays: weekend.bonusDays() }) });
|
|
}
|
|
if (p === '/api/my/spins' && req.method === 'GET') {
|
|
if (limited(req, 'spins', 120, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
|
|
const m = store.member(me); if (!netVerified(m)) return json(res, 403, { error: 'Sign in with your network account to use your spin links.' });
|
|
const r = await lstrack.spins(m.username); if (r.error) return json(res, 502, { error: r.error });
|
|
return json(res, 200, { account: r.account !== false, spins: r.spins || [] });
|
|
}
|
|
if (p === '/api/my/ad' && req.method === 'POST') {
|
|
if (limited(req, 'ad', 30, 3600000)) return json(res, 429, { error: 'Too many changes this hour.' });
|
|
const m = store.member(me); await verifyNet(me).catch(() => {});
|
|
if (!netVerified(m)) return json(res, 403, { error: 'Text ads are free for network members. Join InstantAdPay or LinkSpin free, then sign in here with that account.', join: joinUrl('') });
|
|
const b = await readBody(req);
|
|
const headline = cleanText(b.headline, C.ad.headline), line1 = cleanText(b.line1, C.ad.line), line2 = cleanText(b.line2, C.ad.line);
|
|
if (headline.length < 3 || headline.length > C.ad.headline) return json(res, 400, { error: 'Write a headline of 3 to ' + C.ad.headline + ' characters.' });
|
|
if (line1.length < 3 || line1.length > C.ad.line) return json(res, 400, { error: 'Write the first line in 3 to ' + C.ad.line + ' characters.' });
|
|
if (line2.length > C.ad.line) return json(res, 400, { error: 'Keep the second line to ' + C.ad.line + ' characters.' });
|
|
const lk = safety.checkLink(b.link, 'Your link'); if (lk.error) return json(res, 400, lk);
|
|
// a LinkSpin spin link is accepted ONLY when LinkSpin confirms it is this member's own (signed partner endpoint)
|
|
const sp = await lstrack.checkSpin(lk.url, m.username); if (sp.error) return json(res, 400, { error: sp.error });
|
|
const spin = sp.spin ? sp.code : null;
|
|
const cur = store.adOf(me);
|
|
if (C.linkProbe && (!cur || cur.link !== lk.url)) { const pr = await safety.probeLink(lk.url, { frames: false }); if (pr.error) return json(res, 400, pr); }
|
|
const track = b.track === undefined ? (cur ? cur.track !== false : true) : b.track !== false && b.track !== 'off' && b.track !== 0;
|
|
if (cur) { Object.assign(cur, { headline, line1, line2, link: lk.url, track, spin, status: cur.status === 'paused' ? 'paused' : 'live' }); store.saveAd(cur); if (lstrack.on()) lstrack.ensureAd(cur).catch(() => {}); return json(res, 200, { ok: true, ad: { id: cur.id }, created: false, source: shareUrl(tree.rootOf(cur)) }); }
|
|
const a = store.addAd({ owner: me, headline, line1, line2, link: lk.url, track, spin, status: 'live', views: 0, clicks: 0, vclicks: 0 }); store.bump('adsPosted');
|
|
const root = tree.rootOf(a); wire.attachPending(me, a.id);
|
|
if (lstrack.on()) lstrack.ensureAd(a).catch(() => {});
|
|
return json(res, 200, { ok: true, ad: { id: a.id }, created: true, source: shareUrl(root) });
|
|
}
|
|
// reshare an ad: my unique reshare link for it (under the share link I came through, when it is for the same ad)
|
|
if (p === '/api/my/reshare' && req.method === 'POST') {
|
|
if (limited(req, 'reshare', 120, 3600000)) return json(res, 429, { error: 'Too many reshares this hour.' });
|
|
const m = store.member(me); await verifyNet(me).catch(() => {});
|
|
if (!netVerified(m)) return json(res, 403, { error: 'Resharing is free for network members. Sign in with your network account first.' });
|
|
const b = await readBody(req); const a = store.ad(Number(b.adId));
|
|
const via = viaOf(req); const from = CODE_RE.test(String(b.from || '')) ? String(b.from) : via ? via.code : null;
|
|
const r = tree.reshare(a, me, from); if (r.error) return json(res, 400, r);
|
|
return json(res, 200, { ok: true, code: r.share.id, url: shareUrl(r.share), step: r.share.step, created: r.created, own: !!r.own });
|
|
}
|
|
if (p === '/api/my/order' && req.method === 'POST') {
|
|
if (!shop.watching() || !shop.signerOn()) return json(res, 503, { error: 'Boosts are not open yet.' });
|
|
if (limited(req, 'order', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
|
|
const b = await readBody(req); const qty = Number(b.qty || 1);
|
|
if (!Number.isInteger(qty) || qty < 1 || qty > C.boost.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.boost.maxQty + ' Boosts.' });
|
|
const a = store.adOf(me); if (!a || a.status !== 'live') return json(res, 400, { error: 'Post your text ad first. A Boost is for your ad.' });
|
|
const lo = await hubline.lineOf({ wallet: me }, shop.MAX_LINE);
|
|
if (!lo.ok) return json(res, 503, { error: 'Your sponsor line could not be checked with the network just now. Try again in a minute, so your team gets paid.' });
|
|
// eligibility (Marty 2026-11-17): a network member (hub, not blocked) with a linked wallet earns a level, Boost or not. Dropping the
|
|
// ineligible here IS the compression: each level passes up to the next eligible person; the contract pays places 1..5 and
|
|
// whatever levels are left when the line runs out go to the company
|
|
const line = lo.line.filter(x => x.wallet && !x.blocked && x.wallet !== me).map(x => x.wallet);
|
|
// the resharer whose branch sold it: the reshare link this buyer came through (last touch), never the buyer
|
|
const via = viaOf(req); const vs = via ? store.share(via.code) : null;
|
|
const resharer = vs && vs.step > 0 && vs.owner !== me ? vs.owner : null;
|
|
{ const S0 = store.state(); S0.orderVia = S0.orderVia || {}; if (resharer) S0.orderVia[me] = { code: vs.id, at: Date.now() }; else delete S0.orderVia[me]; store.save(); } // which branch sold it (proof.js books it on that reshare link)
|
|
try { return json(res, 200, Object.assign({ buyer: me, usd: C.boost.usd * qty, days: (C.boost.days + weekend.bonusDays()) * qty, qty, adId: a.id, resharerName: resharer ? uname(resharer) : null }, await shop.order(me, C.boost.sku, qty, a.id, line, resharer))); }
|
|
catch (e) { console.error('order failed:', String(e && e.message || e).slice(0, 200)); return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
|
|
}
|
|
if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); }
|
|
// the AI ad writer (2026-11-17): 3 suggested ads written only from the member's own page; nothing is posted (the hub writes them: hubadwriter.js)
|
|
if (p === '/api/my/adwriter' && req.method === 'POST') {
|
|
if (!(await adwriter.enabled())) return json(res, 503, { error: 'The ad writer is switched off right now. You can still write your ad yourself.' });
|
|
if (limited(req, 'adwriter', 12, 3600000)) return json(res, 429, { error: 'Too many ad writes from this connection this hour. Try again later, or write your ad yourself.' });
|
|
const m = store.member(me); await verifyNet(me).catch(() => {});
|
|
if (!netVerified(m)) return json(res, 403, { error: 'The ad writer is for network members. Sign in with your network account first.' });
|
|
const b = await readBody(req);
|
|
const r = await adwriter.write(me, String(b.url || '').trim().slice(0, 600), { headline: C.ad.headline, line: C.ad.line });
|
|
if (r.error) return json(res, r.status || 400, { error: r.error, code: r.code, left: r.left });
|
|
return json(res, 200, { ok: true, options: r.options, url: r.url, cached: r.cached, left: r.left });
|
|
}
|
|
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();
|
|
return json(res, 200, { day: store.ctDay(), week: store.ctWeek(), staging: C.staging, testSwitch: TEST_SWITCH, config: { boost: C.boost, split: C.split, reward: C.reward, credits: C.credits, hubJoin: C.hubJoin },
|
|
today: store.today(), totals: S.totals, members: store.members().length, ads: { live: store.liveAds().length, all: store.ads().length }, shares: S.shares.length,
|
|
rows: { visits: store.visits().length, clicks: store.clicks().length, signups: store.signups().length, rewards: store.rewards().length },
|
|
signup: signup.view(), shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), hubEvents: hubevents.view(), sso: { hub: networksso.hubOn(), pairwise: networksso.enabled() },
|
|
linkspin: lstrack.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length, adWriter: await adwriter.status() });
|
|
}
|
|
if (p === '/api/admin/signups' && req.method === 'GET') {
|
|
const st0 = String(u.searchParams.get('status') || '');
|
|
return json(res, 200, { signups: store.signups().filter(x => !st0 || x.status === st0).slice(-200).reverse().map(x => ({ id: x.id, status: x.status, email: x.email, username: x.username, share: x.share, resharer: x.resharer ? uname(x.resharer) || x.resharer : null,
|
|
createdAt: x.createdAt, confirmedAt: x.confirmedAt || null, checks: x.checks || null, fail: x.fail || [], hold: x.hold || [], rewards: x.rewards || [], confirmLink: TEST_SWITCH ? x.confirmLink || null : undefined })) });
|
|
}
|
|
if (p === '/api/admin/signup' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, await signup.decide(String(b.id || ''), String(b.action || ''))); }
|
|
if (p === '/api/admin/rewards' && req.method === 'GET') return json(res, 200, { payouts: C.reward.payouts, rewards: store.rewards().slice(-300).reverse().map(r => Object.assign({}, r, { voucher: r.voucher ? { nonce: r.voucher.nonce, deadline: r.voucher.deadline, unlockAt: r.voucher.unlockAt, signed: true } : null })) });
|
|
if (p === '/api/admin/rewards/pay' && req.method === 'POST') { if (!C.reward.payouts) return json(res, 409, { error: 'Payouts are off (REWARD_PAYOUTS). Marty confirms the amounts first.' }); return json(res, 200, { relayed: await signup.payDue() }); }
|
|
// staging only: mark a wallet as a test network member so the ad / reshare / tree flows can be tried without a real account
|
|
if (p === '/api/admin/test-member' && req.method === 'POST') {
|
|
if (!TEST_SWITCH) return json(res, 403, { error: 'The test switch exists on staging only.' });
|
|
const b = await readBody(req); if (!ADDR_RE.test(b.address || '') || (b.username && !NAME_RE.test(b.username))) return json(res, 400, { error: 'address (+ username)' });
|
|
const a = b.address.toLowerCase(); const other = b.username ? store.memberByName(b.username) : null;
|
|
if (other && other.address !== a) return json(res, 409, { error: 'username taken here' });
|
|
const m = store.upsertMember(a, { netOk: b.on !== false, netBy: 'test', testMember: b.on !== false, username: b.username || (store.member(a) || {}).username || null });
|
|
return json(res, 200, { ok: true, member: m });
|
|
}
|
|
if (p === '/api/admin/oldrefs' && req.method === 'POST') {
|
|
let b; try { b = JSON.parse((await readRaw(req, 4 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); }
|
|
if (!b || !b.oldrefs || typeof b.oldrefs !== 'object') return json(res, 400, { error: 'oldrefs object required' });
|
|
const o = {}; for (const [k, v] of Object.entries(b.oldrefs)) if (/^[a-z0-9_.-]{2,40}$/.test(k) && NAME_RE.test(String(v))) o[k] = String(v);
|
|
fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} };
|
|
return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length });
|
|
}
|
|
if (p === '/api/admin/ad' && req.method === 'POST') {
|
|
const b = await readBody(req); const a = store.ad(b.id); if (!a) return json(res, 404, { error: 'not found' });
|
|
if (!['live', 'paused', 'removed'].includes(b.status)) return json(res, 400, { error: 'status live | paused | removed' });
|
|
a.status = b.status; a.note = cleanText(b.note, 200); store.saveAd(a); return json(res, 200, { ok: true, ad: a });
|
|
}
|
|
if (p === '/api/admin/tree' && req.method === 'GET') return json(res, 200, tree.tree(Number(u.searchParams.get('ad'))));
|
|
if (p === '/api/admin/member-lookup' && req.method === 'GET') {
|
|
const q = String(u.searchParams.get('q') || '').trim(); let a = null;
|
|
if (ADDR_RE.test(q)) a = q.toLowerCase(); else if (/^#?\d{1,9}$/.test(q)) { const ad = store.ad(Number(q.replace('#', ''))); a = ad ? ad.owner : null; } else if (NAME_RE.test(q)) { const m = store.memberByName(q); a = m ? m.address : null; }
|
|
if (!a) return json(res, 404, { error: 'not found' });
|
|
const rec = Object.assign({}, store.member(a)); delete rec.vks; delete rec.iphs;
|
|
return json(res, 200, { address: a, record: rec, ad: store.adOf(a), reshares: store.sharesBy(a).length, credits: store.credits(a), rewards: signup.mine(a), earned: myEarned(a) });
|
|
}
|
|
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('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not found | ViralAdSource</title><body style="background:#EAF6F4;color:#0B2730;font-family:\'IBM Plex Sans\',system-ui,sans-serif;text-align:center;padding:40px 16px"><p style="font-size:22px;font-weight:700">This stream ran dry.</p><p><a style="color:#C4371B;font-weight:700" href="/">Back to the source</a></p></body>');
|
|
} catch (e) {
|
|
console.error('request', p, e.message);
|
|
if (!res.headersSent) json(res, 500, { error: 'Server error' });
|
|
}
|
|
});
|
|
|
|
(async () => {
|
|
await docstore.init({ splits: store.SPLITS });
|
|
process.on('SIGTERM', () => { store.flush(); docstore.drain(8000).finally(() => process.exit(0)); });
|
|
store.load();
|
|
wire.init();
|
|
store.prune(); wire.rebuild();
|
|
signup.init({ hub: hubpeople, hubJoin, shop, netVerified });
|
|
hubreport.init({ dataDir: C.dataDir, purchases: () => wire.purchases().map(x => ({ key: x.key, buyer: x.buyer, sponsor: null, usdCents: x.usdCents, block: x.block, at: x.at })) });
|
|
proof.init(C, { shop, wire, signup });
|
|
shop.setAttach(rec => { wire.attach(rec); store.bump('boosts', Number(rec.qty) || 1); });
|
|
shop.setHook(proof.onPurchase);
|
|
shop.setRewardHook(signup.onPaid);
|
|
shop.init(C);
|
|
setInterval(() => { if (store.prune()) wire.rebuild(); }, 3600000).unref();
|
|
if (C.reward.payouts) setInterval(() => signup.payDue().catch(() => {}), 60000).unref();
|
|
chatbot.init();
|
|
lstrack.init(C, store);
|
|
{ let busy = false; const tick = () => { if (busy) return; busy = true; lstrack.sweep(25).catch(() => {}).finally(() => { busy = false; }); };
|
|
setTimeout(tick, Number(process.env.LS_SWEEP_FIRST_MS || 20000)).unref(); setInterval(tick, Number(process.env.LS_SWEEP_MS || 120000)).unref(); }
|
|
server.listen(C.port, () => console.log('ViralAdSource on :' + C.port + (C.staging ? ' (staging)' : '') + ', rewards payouts ' + (C.reward.payouts ? 'ON' : 'OFF') + ', 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); });
|