Zones guardrails: origin lock to the declared site, warm-up then earning, hold under 40% viewable, admin Zones pane with pause

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-09-29 17:38:08 -05:00
parent e36b590788
commit cfb9ed13d0
5 changed files with 79 additions and 18 deletions
+41 -12
View File
@@ -22,17 +22,34 @@ 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 '<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}body{width:' + wh[0] + 'px;height:' + wh[1] + 'px}img{border:0;display:block}</style></head><body>' + NAS_TAG(wh[0], wh[1]) + '</body></html>'; }
function pubZone(z) {
const since30 = Date.now() - 30 * DAY; const imps = J.db.imps.filter(i => i.z === z.id && i.ts >= since30 && !i.bot);
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;
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 };
// 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?:\/\//, '').split('/')[0].slice(0, 80);
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) };
}
@@ -40,7 +57,7 @@ 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) z.site = String(body.site).trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0].slice(0, 80);
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) };
}
@@ -50,12 +67,15 @@ function visitorOf(req) { const ua = String(req.headers['user-agent'] || ''); co
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 (!vis.bot) { try { ad = await ads.serve('banner', Object.assign({ width: w, height: h, excludeEmail: z.owner }, geoOpts || {})); } catch (e) { ad = null; } }
const nas = !ad && !vis.bot && s.nasOn && NAS_SIZES.has(z.size);
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 };
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 };
@@ -68,7 +88,8 @@ async function seen(impId, req) {
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;
if (todayByVisitor < s.capPerVisitorDay && !imp.house) { // house views are not paid: nobody bought them
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;
@@ -82,5 +103,13 @@ async function click(impId) {
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, settings, nasFrame, list, create, update, tag, serve, seen, click, totals };
module.exports = { init, SIZES, NAS_SIZES, WARMUP, HOLD_RATIO, settings, nasFrame, list, create, update, tag, serve, seen, click, totals, adminList, adminSet };