// 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'); const audiences = require('./audiences'); let DATA_DIR = null, ads = null, siteHost = 'linkspin.app'; const SIZES = { '728x90': [728, 90], '468x60': [468, 60], '300x250': [300, 250], '336x280': [336, 280], '250x250': [250, 250], '125x125': [125, 125], '160x600': [160, 600], '120x600': [120, 600], '320x50': [320, 50] }; // + 336x280 / 250x250 / 125x125 / 120x600 (Marty 2026-10-07) // neutral file names on purpose: EasyList blocks any URL with an IAB size token like '-728x90.' (Marty's own blocker hid // the first zone test on stackpol.com, 2026-10-08) const HOUSE = { '728x90': '/art/house-leader.svg', '468x60': '/art/house-strip.svg', '300x250': '/art/house-box.svg', '336x280': '/art/house-panel.svg', '250x250': '/art/house-square.svg', '125x125': '/art/house-tile.svg', '160x600': '/art/house-tower.svg', '120x600': '/art/house-column.svg', '320x50': '/art/house-bar.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: {}, pay: [] }; } for (const k of ['zones', 'imps', 'pay']) 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; // day keys in Central time (reports and the publisher strip count days the way Marty reads them) const dayFmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit' }); const dayKey = ts => dayFmt.format(new Date(ts)); 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, nasViewsPerCreditVerified: 8, capPerVisitorDay: 50, houseOn: 1, nasOn: 0 }, s); } // nasOn default OFF: the network tier in zones is switched on with NAS at the end of testing (Marty 2026-10-09) // Publisher tiers (2026-10-10): every zone starts Standard; an admin marks a reviewed site Verified, and its network-ad // views pay at the better rate (1 credit per nasViewsPerCreditVerified views instead of nasViewsPerCredit). Member // campaign views pay the same on both tiers. The rate is applied when a view is credited (seen), not when it is served. const TIERS = ['standard', 'verified']; function tierOf(z) { return z && z.tier === 'verified' ? 'verified' : 'standard'; } function rateFor(z, nas, s) { s = s || settings(); if (!nas) return s.viewsPerCredit; return tierOf(z) === 'verified' ? s.nasViewsPerCreditVerified : s.nasViewsPerCredit; } // 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, tier: tierOf(z), 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, tier: 'standard', 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; // retargeting: a real view on the declared site puts the visitor in the zone owner's automatic audience (30 days) if (!off && !vis.bot && geoOpts && (geoOpts.vid || geoOpts.soft)) { try { audiences.hit(audiences.defaultFor(z.owner), geoOpts.vid, geoOpts.soft); } catch (e) {} } // 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 (verified zones keep their own // network meter, since their rate differs); whole credits go to the owner and are logged for the publisher reports const key = z.owner + (imp.nas ? (tierOf(z) === 'verified' ? '|nasv' : '|nas') : ''); const per = rateFor(z, !!imp.nas, s); 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; J.db.pay.push({ ts: Date.now(), z: z.id, n: cr, nas: imp.nas ? 1 : 0 }); if (J.db.pay.length > 100000) J.db.pay = J.db.pay.slice(-80000); 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); if (body.tier != null) { const t = String(body.tier).toLowerCase(); if (!TIERS.includes(t)) return { error: 'Tier is standard or verified.' }; z.tier = t; } J.save(); return { ok: true, zone: Object.assign(pubZone(z), { owner: z.owner, note: z.adminNote || '' }) }; } // admin Member content (2026-10-18): every zone with the same 30-day numbers, imps grouped in ONE pass (pubZone filters all imps per zone) function adminAll() { const since30 = Date.now() - 30 * DAY; const g = {}, last = {}; for (const i of J.db.imps) { last[i.z] = i.ts; if (i.ts >= since30 && !i.bot) (g[i.z] = g[i.z] || []).push(i); } return J.db.zones.map(z => { const imps = g[z.id] || []; const st = statusOf(z, imps); const seen = imps.filter(i => i.ok).length; return { id: z.id, name: z.name, site: z.site, size: z.size, tier: tierOf(z), active: !!z.active, paused: !!z.adminPaused, note: z.adminNote || '', owner: z.owner, created: z.created, views30: imps.length, viewable30: seen, viewablePct: imps.length ? Math.round(seen / imps.length * 100) : null, clicks30: imps.filter(i => i.k).length, offsite30: imps.filter(i => i.off).length, credits: z.credits || 0, status: st.state, statusLabel: st.label, lastSeen: last[z.id] || 0 }; }); } 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) }; } // -- publisher program totals (Reports screen + the public strip): the last N days, Central days, per day and per zone. // "live" = switched on, not admin-paused, and seen by a real visitor inside the window. Credits are read from the pay log // (kept since 2026-10-10; credits granted before that are in each zone's lifetime total only). function publisherTotals(days) { days = Math.max(1, Math.min(365, Number(days) || 7)); const since = Date.now() - days * DAY; const imps = J.db.imps.filter(i => i.ts >= since && !i.bot); const pays = J.db.pay.filter(p => p.ts >= since); const byDay = {}, byZone = {}, seenZ = new Set(); const dayRec = ts => { const k = dayKey(ts); return byDay[k] = byDay[k] || { day: k, views: 0, viewable: 0, credits: 0 }; }; const zoneRec = id => { if (byZone[id]) return byZone[id]; const z = J.db.zones.find(x => x.id === id) || {}; return byZone[id] = { id, name: z.name || id, site: z.site || '', size: z.size || '', tier: tierOf(z), owner: z.owner || '', views: 0, viewable: 0, credits: 0 }; }; for (const i of imps) { const d = dayRec(i.ts), zr = zoneRec(i.z); d.views++; zr.views++; if (i.ok) { d.viewable++; zr.viewable++; } if (!i.off) seenZ.add(i.z); } for (const p of pays) { dayRec(p.ts).credits += p.n; zoneRec(p.z).credits += p.n; } const live = J.db.zones.filter(z => z.active && !z.adminPaused && seenZ.has(z.id)).length; return { days, zones: J.db.zones.length, live, views: imps.length, viewable: imps.filter(i => i.ok).length, credits: pays.reduce((n, p) => n + p.n, 0), byDay: Object.values(byDay).sort((a, b) => a.day < b.day ? -1 : 1), byZone: Object.values(byZone).sort((a, b) => b.views - a.views) }; } // the public "Network right now" strip on /publishers: 7-day totals plus the rates, cached a minute let pubCache = null; function publisherPublic() { if (pubCache && Date.now() - pubCache.ts < 60000) return pubCache.data; const t = publisherTotals(7); const s = settings(); const data = { zones: t.zones, live: t.live, views7: t.views, viewable7: t.viewable, credits7: t.credits, sizes: Object.keys(SIZES), networkSizes: Array.from(NAS_SIZES), tiers: TIERS, rates: { viewsPerCredit: s.viewsPerCredit, nasViewsPerCredit: s.nasViewsPerCredit, nasViewsPerCreditVerified: s.nasViewsPerCreditVerified, capPerVisitorDay: s.capPerVisitorDay }, warmup: WARMUP, holdRatio: HOLD_RATIO, updated: Date.now() }; pubCache = { ts: Date.now(), data }; return data; } module.exports = { init, SIZES, NAS_SIZES, TIERS, WARMUP, HOLD_RATIO, settings, tierOf, rateFor, nasFrame, list, create, update, tag, serve, seen, click, totals, publisherTotals, publisherPublic, adminList, adminSet, adminAll };