Conversion pixel engine (Marty approved 2026-10-23): goals with public pixel ids, click ids on every ad click (lsclk, 'a'+11 hex), spin links pass the ad click on, landing tag /t.js + goal pixel /cv.gif /cv.js matching url > stored > cookie > 24 h soft key, once per click, 30-day window, owner check, rate limits, goal postbacks (event 'goal'), member + signed partner APIs for InstantAdPay

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-23 18:10:46 -05:00
parent ff8b8abc77
commit dd2244272b
7 changed files with 477 additions and 14 deletions
+25 -4
View File
@@ -12,6 +12,7 @@ const path = require('path');
const crypto = require('crypto');
let DATA_DIR = null, geo = null, OWN_HOSTS = () => [], SOURCES = null; // SOURCES = sources.js (traffic sources, 2026-10-12)
let WANTS_CLICK_ID = () => false; // conversion pixel (2026-10-23): owner -> true when they have a goal, so their destinations get ?lsclk=
const DAY = 86400000;
const J = {
db: null,
@@ -19,7 +20,7 @@ const J = {
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, rotations: [], hits: [], conv: [] }; } if (!this.db.conv) this.db.conv = []; },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }
};
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; J.load(); }
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; J.load(); }
const norm = e => String(e || '').trim().toLowerCase();
const newCode = () => { const a = 'abcdefghjkmnpqrstuvwxyz23456789'; let s = ''; for (let i = 0; i < 6; i++) s += a[crypto.randomInt(a.length)]; return s; };
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
@@ -168,13 +169,18 @@ async function resolve(code, req) {
const d = (r.paused || off) ? null : pick(r, cell);
const url = d ? d.url : (r.fallback || null);
const ref = String(req.headers.referer || ''); let src = 'direct'; try { if (ref) src = new URL(ref).hostname.replace(/^www\./, ''); } catch (e) {}
// an ad click that led here (conversion pixel, 2026-10-23): InstantAdPay and LinkSpin ad clicks append ?lsclk=<i|a + 11 hex>.
// The spin-link click inherits the ad as its source; the goal pixel credits the ad campaign AND this link.
let ac = ''; try { const v = String(new URL(req.url, 'http://x').searchParams.get('lsclk') || ''); if (/^[ai][a-f0-9]{11}$/.test(v)) ac = v; } catch (e) {}
if (ac) src = ac[0] === 'i' ? 'InstantAdPay ad' : 'LinkSpin ad';
const device = /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop';
// click ids and sub ids that rode in on the link (tracker / traffic-network params), kept per click
const q = {}; try { const sp = new URL(req.url, 'http://x').searchParams; let n = 0; for (const [k, val] of sp) { const key = String(k).toLowerCase(); if (n >= 20) break; if (/^(clickid|click_id|cid|subid|sub_id|s[1-5]|sub[1-5]|t[1-5]|aff_sub[1-5]?|utm_(source|medium|campaign|term|content)|src|source|campaign|zone|placement|cost|creative|site|banner|keyword|geo|os|browser|device|carrier|format|external_id|visitor_id)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } } catch (e) {}
const id = crypto.randomBytes(6).toString('hex').slice(0, 10);
// sr = the traffic source attached to the link at click time, so the network that sent this click is the one told about its conversion
J.db.hits.push({ id, r: r.id, d: d ? d.id : 0, ts: Date.now(), v, c: country, s: src, dv: device, bot: bot ? 1 : 0, oh: off ? 1 : undefined, q: Object.keys(q).length ? q : undefined, sr: r.sourceId || undefined });
if (J.db.hits.length > 200000) J.db.hits = J.db.hits.slice(-150000);
J.db.hits.push({ id, r: r.id, d: d ? d.id : 0, ts: Date.now(), v, c: country, s: src, dv: device, bot: bot ? 1 : 0, oh: off ? 1 : undefined, q: Object.keys(q).length ? q : undefined, sr: r.sourceId || undefined, ac: ac || undefined });
if (HIT_IX) HIT_IX.set(id, J.db.hits.length - 1);
if (J.db.hits.length > 200000) { J.db.hits = J.db.hits.slice(-150000); HIT_IX = null; }
J.save();
let out = url;
if (out) {
@@ -183,6 +189,9 @@ async function resolve(code, req) {
out = out.replace(/\{([a-z0-9_]{1,24})\}/gi, (m, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()]));
// our own pages get the click id automatically, so a join can be matched back to this click without any macro
try { const t = new URL(out); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid')) { t.searchParams.set('lsid', id); out = t.toString(); } } catch (e) {}
// conversion pixel (2026-10-23): when the owner tracks goals, or the click came from an ad, the destination also gets
// ?lsclk=<this click id> for the landing tag (/t.js) to keep. Existing params stay; an lsclk already there is left alone.
if (!bot && (ac || WANTS_CLICK_ID(r.owner))) { try { const t = new URL(out); if (!t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {} }
}
return { url: out, dest: d, rotation: r, lsid: id };
}
@@ -244,6 +253,18 @@ async function stats(owner, id) {
return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length, best: bestHours(r), offHours: hits.filter(h => h.oh).length,
subs: Object.entries(subs).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
}
// conversion pixel (2026-10-23): a click by id, with its link and destination. An index over the hits array, rebuilt lazily
// after new hits (the pixel asks rarely; a rebuild over 200k hits is a few ms).
let HIT_IX = null;
function hitById(id, again) {
if (!HIT_IX) { HIT_IX = new Map(); for (let i = 0; i < J.db.hits.length; i++) HIT_IX.set(J.db.hits[i].id, i); }
let i = HIT_IX.get(String(id)); let h = i == null ? null : J.db.hits[i];
if (i != null && (!h || h.id !== String(id))) { HIT_IX = null; return again ? null : hitById(id, true); } // the array moved under the index (trim, demo sweep): rebuild once
if (!h) return null;
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
const d = (r.destinations || []).find(x => x.id === h.d);
return { hit: h, owner: r.owner, rotation: { id: r.id, code: r.code, name: r.name }, destUrl: d ? d.url : (r.fallback || '') };
}
function totals() { return { rotations: J.db.rotations.length, hits: J.db.hits.length }; }
// ── demo spins (home page, 2026-10-07) ─────────────────────────────────────────────────────────────────────
@@ -294,5 +315,5 @@ function adminAll() {
destinations: (r.destinations || []).map(d => ({ id: d.id, url: d.url, label: d.label || '', weight: d.weight, active: !!d.active, autoPaused: d.autoPaused || 0, health: d.health ? { state: d.health.state, note: d.health.note || '', checkedAt: d.health.checkedAt || 0 } : null })),
hits: o.hits, hits7: o.hits7, bots: o.bots, conversions: cv[r.id] || 0 }; });
}
module.exports = { init, adminAll, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday,
module.exports = { init, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday,
pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource };