// LinkSpin Zones (2026-09-29): an ad slot a member puts on their own site with one line of code. It shows the // engine's member banner campaigns (the same pool the ad viewer serves, so every zone adds real delivery for paid // campaigns) with a LinkSpin house creative as the fallback, and pays the site owner credits per VIEWABLE // impression: at least half the banner on screen for one second, reported by the tag, bots excluded, capped per // visitor per zone per day. Rates are settings, defaults = the ad viewer's own rate (2 credits per 10 views). 'use strict'; const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); let DATA_DIR = null, ads = null, siteHost = 'linkspin.app'; const SIZES = { '728x90': [728, 90], '468x60': [468, 60], '300x250': [300, 250], '160x600': [160, 600], '320x50': [320, 50] }; const HOUSE = { '728x90': '/banners/linkspin-728x90.svg', '468x60': '/banners/linkspin-468x60.svg', '300x250': '/banners/linkspin-300x250.svg', '160x600': '/banners/linkspin-160x600.svg', '320x50': '/banners/linkspin-320x50.svg' }; const NAS_SIZES = new Set(['728x90', '468x60']); // the sizes Network Ad Space serves through its showadss.php tag const NAS_TAG = (w, h) => ''; const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i; const J = { db: null, FILE: () => path.join(DATA_DIR, 'zones.json'), load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, zones: [], imps: [], acc: {} }; } for (const k of ['zones', 'imps']) if (!Array.isArray(this.db[k])) this.db[k] = []; if (!this.db.acc) this.db.acc = {}; }, save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } }; function init(opts) { DATA_DIR = opts.dataDir; ads = opts.ads; siteHost = opts.siteHost || siteHost; J.load(); } const norm = e => String(e || '').trim().toLowerCase(); const DAY = 86400000; function settings() { let s = {}; try { s = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'zone-rates.json'), 'utf8')); } catch (e) {} return Object.assign({ viewsPerCredit: 5, nasViewsPerCredit: 10, capPerVisitorDay: 50, houseOn: 1, nasOn: 1 }, s); } // the document an NAS fallback renders in: our own frame, so the NAS tag's document.write lands in a page we control function nasFrame(size) { const wh = SIZES[size]; if (!wh || !NAS_SIZES.has(size)) return null; return '
' + NAS_TAG(wh[0], wh[1]) + ''; } // Earning status (Marty, 2026-09-29): a zone earns only once its first WARMUP on-site views have landed with at least // HOLD_RATIO of them viewable; below that it keeps serving but stops earning; an admin pause serves house only. const WARMUP = 100, HOLD_RATIO = 0.4; function statusOf(z, imps) { if (z.adminPaused) return { state: 'paused', label: 'Paused by admin' }; if (!z.active) return { state: 'off', label: 'Off' }; const onSite = imps.filter(i => !i.off); const seen = onSite.filter(i => i.ok).length; if (onSite.length < WARMUP) return { state: 'warming', label: 'Warming up: ' + onSite.length + '/' + WARMUP + ' views', warm: onSite.length }; if (seen / onSite.length < HOLD_RATIO) return { state: 'hold', label: 'On hold: under ' + Math.round(HOLD_RATIO * 100) + '% viewable' }; return { state: 'earning', label: 'Earning' }; } function impsOf(z) { const since30 = Date.now() - 30 * DAY; return J.db.imps.filter(i => i.z === z.id && i.ts >= since30 && !i.bot); } function pubZone(z) { const imps = impsOf(z); const seen = imps.filter(i => i.ok).length; const clicks = imps.filter(i => i.k).length; const last = J.db.imps.filter(i => i.z === z.id).slice(-1)[0]; const ratio = imps.length ? seen / imps.length : 0; const st = statusOf(z, imps); return { id: z.id, name: z.name, site: z.site, size: z.size, active: !!z.active, created: z.created, views30: imps.length, viewable30: seen, viewablePct: imps.length ? Math.round(ratio * 100) : null, clicks30: clicks, credits: z.credits || 0, grade: !imps.length ? null : ratio >= 0.6 ? 'A' : ratio >= 0.4 ? 'B' : 'C', lastSeen: last ? last.ts : 0, house30: imps.filter(i => i.house).length, nas30: imps.filter(i => i.nas).length, campaign30: imps.filter(i => i.camp).length, offsite30: imps.filter(i => i.off).length, status: st.state, statusLabel: st.label, paused: !!z.adminPaused }; } // the site the tag is running on, from the browser's referrer (cross-origin fetches still send the origin); matches the // declared site or any subdomain of it function siteHostOf(req) { try { return new URL(String(req.headers.referer || req.headers.origin || '')).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } } function onDeclaredSite(z, host) { const s = String(z.site || '').replace(/^www\./, ''); return !!host && !!s && (host === s || host.endsWith('.' + s)); } async function list(owner) { return J.db.zones.filter(z => z.owner === norm(owner)).map(pubZone); } async function create(owner, body) { if (J.db.zones.filter(z => z.owner === norm(owner)).length >= 50) return { error: 'Up to 50 zones per account.' }; const size = SIZES[String(body.size || '')] ? String(body.size) : '728x90'; const name = String(body.name || '').trim().slice(0, 60) || 'Zone'; const site = String(body.site || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0].split(':')[0].slice(0, 80); if (!/^[a-z0-9.-]+$/.test(site) || !site.includes('.')) return { error: 'Enter the site the tag will live on, like myblog.com. Paid ads only serve on that site.' }; const z = { id: 'ls-' + crypto.randomBytes(3).toString('hex'), owner: norm(owner), name, site, size, active: true, created: Date.now(), credits: 0 }; J.db.zones.push(z); J.save(); return { ok: true, zone: pubZone(z) }; } async function update(owner, id, body) { const z = J.db.zones.find(z => z.id === id && z.owner === norm(owner)); if (!z) return { error: 'No such zone.' }; if (body.remove) { J.db.zones = J.db.zones.filter(x => x !== z); J.save(); return { ok: true, removed: true }; } if (body.name != null) z.name = String(body.name).trim().slice(0, 60) || z.name; if (body.site != null) { const site = String(body.site).trim().toLowerCase().replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0].split(':')[0].slice(0, 80); if (!/^[a-z0-9.-]+$/.test(site) || !site.includes('.')) return { error: 'Enter a site like myblog.com.' }; z.site = site; } if (body.active != null) z.active = !!body.active; J.save(); return { ok: true, zone: pubZone(z) }; } function tag(z) { return ''; } // -- serving function visitorOf(req) { const ua = String(req.headers['user-agent'] || ''); const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim(); return { v: crypto.createHash('sha256').update(new Date().toISOString().slice(0, 10) + '|' + ip + '|' + ua).digest('hex').slice(0, 16), bot: BOT.test(ua) || !ua }; } async function serve(zoneId, req, geoOpts) { const z = J.db.zones.find(z => z.id === String(zoneId)); if (!z || !z.active) return null; const [w, h] = SIZES[z.size]; const vis = visitorOf(req); const s = settings(); // origin lock: paid inventory (campaigns, network ads) only on the declared site; anywhere else, or with no referrer, // the tag shows the house banner and nothing is earned. An admin pause does the same. const off = !onDeclaredSite(z, siteHostOf(req)); const paidOk = !vis.bot && !off && !z.adminPaused; // waterfall: 1) a LinkSpin member campaign 2) a Network Ad Space ad (NAS serves 728x90 and 468x60) 3) the LinkSpin house banner let ad = null; if (paidOk) { try { ad = await ads.serve('banner', Object.assign({ width: w, height: h, excludeEmail: z.owner }, geoOpts || {})); } catch (e) { ad = null; } } const nas = !ad && paidOk && s.nasOn && NAS_SIZES.has(z.size); const house = !ad && !nas; if (house && !s.houseOn) return null; const imp = { id: crypto.randomBytes(6).toString('hex'), z: z.id, ts: Date.now(), v: vis.v, bot: vis.bot ? 1 : 0, ok: 0, k: 0, house: house ? 1 : 0, nas: nas ? 1 : 0, camp: ad ? ad.id : 0, off: off ? 1 : 0 }; J.db.imps.push(imp); if (J.db.imps.length > 300000) J.db.imps = J.db.imps.slice(-200000); J.save(); if (nas) return { imp: imp.id, w, h, kind: 'nas', frame: '/z/nas?s=' + z.size + '&i=' + imp.id, nas: true }; return { imp: imp.id, w, h, kind: house ? 'house' : 'campaign', img: ad ? (ad.image || ad.imageUrl || ad.src || '') : HOUSE[z.size], alt: ad ? (ad.title || 'Advertisement') : 'LinkSpin: one link, every page you promote', click: '/api/zone/click/' + imp.id, house }; } // the tag says the banner was at least half visible for a second: credit the owner (rate-limited per visitor per zone per day) async function seen(impId, req) { const imp = J.db.imps.find(i => i.id === String(impId)); if (!imp || imp.ok || imp.bot) return { ok: false }; if (Date.now() - imp.ts > 10 * 60000) return { ok: false }; const z = J.db.zones.find(z => z.id === imp.z); if (!z) return { ok: false }; const s = settings(); const day = new Date().toISOString().slice(0, 10); const todayByVisitor = J.db.imps.filter(i => i.z === z.id && i.v === imp.v && i.ok && new Date(i.ts).toISOString().slice(0, 10) === day).length; imp.ok = 1; const earning = statusOf(z, impsOf(z)).state === 'earning'; if (earning && todayByVisitor < s.capPerVisitorDay && !imp.house && !imp.off) { // house and off-site views are not paid // LinkSpin campaign views and NAS views accrue on separate meters with their own rates; whole credits go to the owner const key = z.owner + (imp.nas ? '|nas' : ''); const per = imp.nas ? s.nasViewsPerCredit : s.viewsPerCredit; J.db.acc[key] = (J.db.acc[key] || 0) + 1; if (per > 0 && J.db.acc[key] >= per) { const cr = Math.floor(J.db.acc[key] / per); J.db.acc[key] -= cr * per; z.credits = (z.credits || 0) + cr; try { await ads.addEarned(z.owner, cr, { log: { kind: 'earn', note: 'Zone views: ' + z.name + (imp.nas ? ' (network)' : ''), ref: 'zone:' + z.id, rollup: true } }); } catch (e) {} } } J.save(); return { ok: true }; } async function click(impId) { const imp = J.db.imps.find(i => i.id === String(impId)); if (!imp) return null; imp.k = 1; J.save(); if (imp.house || !imp.camp) return 'https://' + siteHost + '/'; try { return (await ads.click(imp.camp)) || ('https://' + siteHost + '/'); } catch (e) { return 'https://' + siteHost + '/'; } } // -- admin: every zone with its owner, site, mix and status; pause/resume async function adminList() { return J.db.zones.map(z => Object.assign(pubZone(z), { owner: z.owner, note: z.adminNote || '' })).sort((a, b) => b.views30 - a.views30); } async function adminSet(id, body) { const z = J.db.zones.find(z => z.id === String(id)); if (!z) return { error: 'No such zone.' }; if (body.paused != null) z.adminPaused = !!body.paused; if (body.note != null) z.adminNote = String(body.note).slice(0, 200); J.save(); return { ok: true, zone: Object.assign(pubZone(z), { owner: z.owner, note: z.adminNote || '' }) }; } function totals() { const since = Date.now() - 30 * DAY; const imps = J.db.imps.filter(i => i.ts >= since && !i.bot); return { zones: J.db.zones.length, views30: imps.length, viewable30: imps.filter(i => i.ok).length, clicks30: imps.filter(i => i.k).length, nas30: imps.filter(i => i.nas).length, credits: J.db.zones.reduce((n, z) => n + (z.credits || 0), 0) }; } module.exports = { init, SIZES, NAS_SIZES, WARMUP, HOLD_RATIO, settings, nasFrame, list, create, update, tag, serve, seen, click, totals, adminList, adminSet };