Banner Spin engine (phase 1): /i/ image with no-store + fresh ETag, /c/ click matching (visitor key + placement host note, 15 min) with fallback, /s/ exact-match script embed, impression counters flushed every 5 s (read-add-write), banner clicks with lsid conversions + source postbacks, tiers ($25 own package; Starter 2x5, Builder 5x15, Leader 10x25), member + admin API, admin kill switch per Banner Spin / per banner / global, Banner Spins in admin Member content

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-18 10:58:44 -05:00
parent e0e0bde1f9
commit 406113bc03
6 changed files with 507 additions and 11 deletions
+98 -4
View File
@@ -43,6 +43,7 @@ const carry = require('./carry'); // sponsor carry-over: engine acti
const rotator = require('./rotator');
const health = require('./health'); // destination health checks + auto-pause (2026-10-10)
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29)
const bannerspin = require('./bannerspin'); // Banner Spin: one image URL + one click URL rotating up to 25 banners (2026-10-18)
const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12)
const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/<slug> (2026-09-29)
const domains = require('./domains'); // link-domain pool by channel + six-hourly safety checks; burned domains leave the pool (2026-10-10)
@@ -174,6 +175,20 @@ async function cachedMember(id) {
let v = null; try { v = await chain.member(id); } catch (e) {}
memberInfoCache.set(id, { t: Date.now(), v }); return v;
}
// Banner Spin access facts (2026-10-18): an own package of $25 or more on the main id or any linked position (the tank
// adoption rule), and qualifying buyers counted the way pay levels count them (main + positions, so Qualified Start counts).
// Cached a minute; bannerspin.js remembers what it has seen so the chain index window never takes a tier away.
const bsFacts = new Map();
async function bannerFacts(email) {
const e = String(email || '').toLowerCase(); const hit = bsFacts.get(e); if (hit && Date.now() - hit.ts < 60000) return hit.f;
const ids = []; try { const a = await accounts.byEmail(e); if (a && a.memberId) ids.push(a.memberId); for (const p of await accounts.positions(e)) if (p.memberId && !ids.includes(p.memberId)) ids.push(p.memberId); } catch (er) {}
const ownBuy = ids.some(id => tank.hasOwnBuy(id));
let buyers = 0; for (const id of ids) { try { buyers += (await chain.member(id)).buyerCount || 0; } catch (er) {} }
const idset = new Set(ids), counted = new Set(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'BuyerCounted' && idset.has(ev.sponsorId) && ev.newBuyerId) counted.add(ev.newBuyerId);
buyers = Math.max(buyers, counted.size);
try { const ms = await ads.milestonesOf(e); if (ms.includes('level3')) buyers = Math.max(buyers, 5); else if (ms.includes('level2')) buyers = Math.max(buyers, 2); } catch (er) {} // a badge once earned stays earned
const f = { ownBuy, buyers }; bsFacts.set(e, { ts: Date.now(), f }); return f;
}
async function myMemberIds(s) {
const main = await auth.refreshMemberId(s);
const ids = main ? [main] : [];
@@ -476,6 +491,8 @@ async function boot() {
setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000);
setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources });
bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts });
rotator.setExternalConvert((lsid, ev, facts) => bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks
sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } });
zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST });
pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } });
@@ -500,7 +517,7 @@ async function boot() {
audit.init({ dataDir: DATA_DIR, notify: text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: counter audit', text).catch(() => {}); } });
setTimeout(() => audit.dailyTick(), 5 * 60 * 1000); setInterval(() => audit.dailyTick(), 24 * 60 * 60 * 1000);
videomaker.init({ dataDir: DATA_DIR, spaces, accounts });
content.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, accounts, pages, rotator, sources, zones, ads, postbacks, audiences, messages, videomaker, reports, domains, adminEmail: ADMIN_EMAIL, houseOwner: ads.HOUSE_OWNER, siteHost: SITE_HOST, linkHost: () => domains.live()[0] || SITE_HOST, pagesHost });
content.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, accounts, pages, rotator, bannerspin, sources, zones, ads, postbacks, audiences, messages, videomaker, reports, domains, adminEmail: ADMIN_EMAIL, houseOwner: ads.HOUSE_OWNER, siteHost: SITE_HOST, linkHost: () => domains.live()[0] || SITE_HOST, pagesHost });
leaderboard.init({ chain, accounts, ads, dataDir: DATA_DIR, siteConfig, pushFeed, adminEmail: ADMIN_EMAIL,
notify: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); if (String(sc.leaderboardAnnounceGeneral || '1') !== '0') await telegramSend(sc.telegramEchoChatId, text, null); } });
setTimeout(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 90 * 1000);
@@ -917,7 +934,7 @@ function linkSitePage(host, page) {
disclosure: '<h1>Affiliate and advertising disclosure</h1><p>Links forwarded through ' + H + ' may be affiliate links or paid advertisements. The member who published a link may earn a commission or advertising credit if you buy something or sign up on the page you land on. This never changes the price you pay.</p><p>' + brand + ' itself is an advertising platform. Members buy ad packages and earn commissions when people they referred buy ad packages. No income is guaranteed to anyone; results depend on effort, and any earnings examples on member pages are illustrations, not promises.</p><p>The pages you are forwarded to belong to their publishers. We are not responsible for their claims, and we remove links that are reported and found to violate our <a href="/terms">terms</a>.</p>',
terms: '<h1>Terms of use</h1><p>By following a link on ' + H + ' you agree to these terms.</p><h2>The service</h2><p>' + H + ' forwards visitors to destinations chosen by ' + brand + ' members. We provide the forwarding only. We do not endorse, verify or control the destination pages, and we are not a party to any transaction you make there.</p><h2>Acceptable use</h2><p>Members may not forward visitors to content that is illegal, deceptive, malicious, adult, or that impersonates another business. Links that violate this are removed and the member\'s account is closed. Automated access to this domain is not permitted except by search engines.</p><h2>No warranty</h2><p>The service is provided as is. We do not guarantee that any link will be available, and we are not liable for the content, availability or conduct of destination sites.</p><h2>Contact</h2><p>Questions about these terms: <a href="https://linkspin.co">linkspin.co</a>.</p>',
privacy: '<h1>Privacy policy</h1><p>This policy covers ' + H + ' and the link forwarding service on it.</p><h2>What we collect</h2><p>When you follow a link we record the date, your country (derived from your network address and then discarded), the site that referred you, whether you are on a phone or a computer, and an anonymous visitor token that changes every day and cannot be traced back to you. We do not store your IP address, your name, your email address or any account information on this domain.</p><h2>Cookies</h2><p>This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.</p><h2>Why we collect it</h2><p>So members can see how many people followed their links and from where. Counts are shown to the member who published the link, in aggregate, and to nobody else.</p><h2>Retention</h2><p>Link statistics are kept for up to thirteen months and then deleted.</p><h2>Your rights</h2><p>Because we hold no personal data on this domain there is nothing to access or delete here. For anything involving a ' + brand + ' member account, contact us through <a href="https://linkspin.co">linkspin.co</a>.</p>',
abuse: '<h1>Report a link</h1><p>If a link on ' + H + ' forwarded you to a page that is deceptive, unsafe, adult, or impersonates a business, tell us. We review every report and pull the link first, then ask questions.</p><p>Send the full link you clicked (it starts with https://' + H + '/r/) and what you saw, to the support contact on <a href="https://linkspin.co">linkspin.co</a>. Reports are usually handled the same day.</p>',
abuse: '<h1>Report a link</h1><p>If a link on ' + H + ' forwarded you to a page that is deceptive, unsafe, adult, or impersonates a business, tell us. We review every report and pull the link first, then ask questions.</p><p>Send the full link you clicked (it starts with https://' + H + '/r/ or https://' + H + '/c/) and what you saw, or the address of a banner image you want reviewed, to the support contact on <a href="https://linkspin.co">linkspin.co</a>. Reports are usually handled the same day.</p>',
gone: '<h1>That link is not active</h1><p>The link you followed has been removed or has expired. Nothing was recorded. If you were expecting a specific page, ask the person who shared the link for a fresh one.</p>'
};
return '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + H + '</title><meta name="robots" content="noindex,follow"><style>body{margin:0;font:16px/1.6 system-ui,Segoe UI,Roboto,sans-serif;color:#1b1f1e;background:#fbfbf9}main{max-width:680px;margin:0 auto;padding:40px 22px 60px}nav{display:flex;gap:16px;flex-wrap:wrap;font-size:14px;margin-bottom:28px}nav a{color:#0f766e;text-decoration:none}h1{font-size:26px;margin:0 0 12px}h2{font-size:17px;margin:22px 0 6px}p{margin:0 0 12px}footer{margin-top:40px;font-size:13px;color:#6b7370;border-top:1px solid #e3e3dd;padding-top:12px}</style></head><body><main>' + nav + (bodies[page] || bodies.gone) + '<footer>&copy; ' + year + ' ' + brand + ' link service. <a href="/disclosure">Disclosure</a> &middot; <a href="/terms">Terms</a> &middot; <a href="/privacy">Privacy</a></footer></main></body></html>';
@@ -970,7 +987,7 @@ const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://x');
const p = u.pathname;
// zone endpoints run on other people's sites and show only ad creatives, so they pass the curtain
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-');
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18)
// support must reach everyone, invited or not (2026-10-16): someone locked out or not yet let in is exactly who needs it
if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
@@ -981,6 +998,30 @@ const server = http.createServer(async (req, res) => {
if (hit && hit.url) { res.writeHead(302, { Location: hit.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); }
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone'));
}
// -- Banner Spin (2026-10-18): /i/<code>.gif the image (a fresh pick on every load, never cached), /c/<code> the click,
// /s/<code>.js the script embed (banner + its own click link). Any host, any origin, like /r/.
{ const bm = /^\/(i|c|s)\/([a-z0-9]{5,12})(\.gif|\.js)?$/.exec(p);
if (bm && (req.method === 'GET' || req.method === 'HEAD') && ((bm[1] === 'i' && bm[3] === '.gif') || (bm[1] === 'c' && !bm[3]) || (bm[1] === 's' && bm[3] === '.js'))) {
const fresh = { 'Cache-Control': 'no-store, no-cache, must-revalidate, private, max-age=0', Pragma: 'no-cache', Expires: '0', ETag: '"' + crypto.randomBytes(8).toString('hex') + '"', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff', 'X-Robots-Tag': 'noindex' };
const host = reqHost(req) || SITE_HOST;
if (bm[1] === 'i') {
const xq = u.searchParams.get('x'); const im = await bannerspin.image(bm[2], req, xq != null && /^\d{1,4}$/.test(xq) ? Number(xq) : null);
if (!im) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end(); }
if (im.url) { res.writeHead(302, Object.assign({}, fresh, { Location: im.url, 'Referrer-Policy': 'no-referrer' })); return res.end(); }
let body = null, type = 'image/png';
if (im.local) { const f = bannerspin.readImage(im.local); if (f) { body = f.buf; type = f.mime; } }
if (!body) body = bannerspin.blankPng(im.size[0], im.size[1]);
res.writeHead(200, Object.assign({}, fresh, { 'Content-Type': type, 'Content-Length': String(body.length), 'Content-Disposition': 'inline' })); return res.end(req.method === 'HEAD' ? '' : body);
}
if (bm[1] === 's') {
const js = await bannerspin.script(bm[2], req, (IS_PROD ? 'https' : 'http') + '://' + (req.headers.host || host));
if (!js) { res.writeHead(404, { 'Content-Type': 'application/javascript' }); return res.end('/* not found */'); }
res.writeHead(200, Object.assign({}, fresh, { 'Content-Type': 'application/javascript; charset=utf-8' })); return res.end(req.method === 'HEAD' ? '' : js);
}
const ck = await bannerspin.click(bm[2], req, host);
if (ck && ck.url) { res.writeHead(302, { Location: ck.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade', 'X-Robots-Tag': 'noindex' }); return res.end(); }
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(host, 'gone'));
} }
// -- ad zones on members' sites: the tag, the ad, the viewable beacon, the click. Any origin may call these.
if (p === '/z.js') { const zf = path.join(PUBLIC_DIR, 'z.js'); try { const body = fs.readFileSync(zf); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); return res.end(body); } catch (e) {} }
if (p === '/api/zone/serve' && req.method === 'GET') {
@@ -1058,7 +1099,7 @@ const server = http.createServer(async (req, res) => {
if (isLinkHost(req)) {
const page = { '/': 'home', '/disclosure': 'disclosure', '/terms': 'terms', '/privacy': 'privacy', '/abuse': 'abuse', '/robots.txt': 'robots' }[p];
if (!page) { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone')); }
if (page === 'robots') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nDisallow: /r/\n'); }
if (page === 'robots') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nDisallow: /r/\nDisallow: /c/\nDisallow: /s/\n'); }
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(linkSitePage(reqHost(req), page));
}
@@ -2098,6 +2139,59 @@ const server = http.createServer(async (req, res) => {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await health.checkRotation(s.email, m[1]); return json(res, r.error ? (/No such/.test(r.error) ? 404 : 429) : 200, r, { 'Cache-Control': 'no-store' });
}
// -- Banner Spin builder (2026-10-18). Every route takes GET and POST: the shell's api() helper always POSTs.
if (p === '/api/my/bannerspins' && (req.method === 'GET' || req.method === 'POST')) {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = req.method === 'POST' ? await readBody(req) : {};
if (req.method === 'GET' || b.list || !b.name) {
const hs = domains.hosts();
return json(res, 200, { spins: await bannerspin.list(s.email), tier: await bannerspin.tierFor(s.email), tiers: bannerspin.TIERS, sizes: Object.keys(bannerspin.SIZES), maxBytes: bannerspin.MAX_BYTES, off: bannerspin.settings().off,
hosts: hs.length ? hs : [{ host: SITE_HOST, channel: 'social', label: 'Social', note: 'The app host (no link domains are live)' }] }, { 'Cache-Control': 'no-store' });
}
const r = await bannerspin.create(s.email, b); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/bannerspins/upload' && req.method === 'POST') { // raw image body; JPG / PNG / GIF, 150 KB, counts against the 10 uploads a day
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const t = await bannerspin.tierFor(s.email); if (!t.ok) return json(res, 403, { error: t.reason });
const ct = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' };
if (!EXT[ct]) return json(res, 400, { error: 'Use a JPG, PNG or GIF file.' });
const key = s.email + ':' + new Date().toISOString().slice(0, 10);
if ((uploadCounts.get(key) || 0) >= 10) return json(res, 400, { error: 'Upload limit for today reached (10 files).' });
let buf; try { buf = await readRaw(req, bannerspin.MAX_BYTES); } catch (e) { return json(res, 400, { error: 'That image is over 150 KB. Save it smaller (fewer colors or frames for a GIF) and try again.' }); }
const magicOk = buf.length > 16 && ((ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) || (ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) || (ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8'));
if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' });
const d = bannerspin.dims(buf, ct);
const name = crypto.randomBytes(12).toString('hex') + '.' + EXT[ct];
uploadCounts.set(key, (uploadCounts.get(key) || 0) + 1);
fs.writeFileSync(path.join(UPLOADS_DIR, name), buf);
content.noteUpload(name, s.email, buf.length, ct, ''); bannerspin.noteImage(s.email, name, d.w, d.h, buf.length, ct);
const want = bannerspin.SIZES[String(u.searchParams.get('size') || '')];
return json(res, 200, { ok: true, url: '/uploads/' + name, w: d.w, h: d.h, bytes: buf.length, warn: want && d.w && (d.w !== want[0] || d.h !== want[1]) ? 'This image is ' + d.w + 'x' + d.h + '; the Banner Spin is ' + want[0] + 'x' + want[1] + '. It will be stretched to fit.' : '', left: 10 - uploadCounts.get(key) });
}
m = /^\/api\/my\/bannerspins\/(\d+)(\/stats|\/banner(?:\/(\d+))?)?$/.exec(p);
if (m && (req.method === 'GET' || req.method === 'POST')) {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (m[2] === '/stats') { const r = await bannerspin.stats(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such Banner Spin.' }); }
if (req.method !== 'POST') return json(res, 405, { error: 'POST only.' });
const b = await readBody(req); let r;
if (m[3]) r = await bannerspin.updateBanner(s.email, m[1], m[3], b);
else if (m[2]) r = await bannerspin.addBanner(s.email, m[1], b);
else r = await bannerspin.update(s.email, m[1], b);
return json(res, r.error ? 400 : 200, r);
}
// admin: every Banner Spin; the feature switch + tier grants (POST /api/admin/bannerspins { off } | { email, grant }); one Banner Spin or one banner off / on
if (p === '/api/admin/bannerspins' && (req.method === 'GET' || req.method === 'POST')) {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
const b = req.method === 'POST' ? await readBody(req) : {};
if (b.off != null || b.grant) { const r = bannerspin.setGlobal(b); content.invalidate(); return json(res, r.error ? 400 : 200, r); }
return json(res, 200, { spins: bannerspin.adminAll(), settings: bannerspin.settings(), totals: bannerspin.totals() }, { 'Cache-Control': 'no-store' });
}
m = /^\/api\/admin\/bannerspins\/(\d+)$/.exec(p);
if (m && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
const r = bannerspin.adminSet(m[1], await readBody(req)); content.invalidate(); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/strip' && req.method === 'GET') { // status strip under every Control Room screen
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
let served = 0; try { served = (await rotator.summary(s.email, 1)).totals.served; } catch (e) {}