Files
linkspin/convtrack.js
T

255 lines
22 KiB
JavaScript

// Conversion pixel (Marty approved 2026-10-23, "Go with the conversion pixel"). LinkSpin is the single source of truth
// for goals and goal conversions, for its own members AND for InstantAdPay members (their LinkSpin shell account, same
// email, holds the goals; InstantAdPay reads and edits them over the signed partner call).
//
// - Goals: a member names a goal ("subscriber", "sale", optional default value). Each goal has a PUBLIC pixel id
// (px + 10 hex). It is not a secret: it can only ever count conversions for clicks its owner owns.
// - Ad clicks: every LinkSpin ad click (/api/ads/click, zone clicks) gets a click id 'a' + 11 hex; every InstantAdPay
// ad click is pushed here with its own id 'i' + 11 hex (/api/partner/clicks). Spin-link clicks keep the rotator's
// 10-hex lsid; a spin-link click that arrived through an ad carries that ad click as `ac` (rotator.js).
// - Landing tag (/t.js) stores the click id on the member's own site; the goal pixel (/cv.gif, /cv.js) reports it.
// Matching order: the click id in the URL > the landing tag's stored id > LinkSpin's cookie > the 24 h IP+UA soft key.
// The method that matched is kept on the conversion so Reports can say how solid each count is.
// - Rules: each goal counts once per click (per ROOT click: an ad click and the spin-link click it led to are one
// click), only within 30 days of a real click, only for clicks the pixel's owner owns (the ad's owner or the spin
// link's owner), per-pixel and per-IP rate limits. A test conversion is recorded apart and never counted.
// Storage: DATA_DIR/convtrack.json (JSON in both modes, like rotator.json / postbacks.json), debounced writes.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const DAY = 86400000, WINDOW_MS = 30 * DAY, SOFT_MS = 24 * 3600000, MAX_GOALS = 20;
const MAX_CLICKS = 300000, MAX_CONV = 100000;
let FILE = null, S = null, dirty = false, rotator = null, campaignOf = async () => null;
function load() {
if (S) return S;
try { S = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { S = null; }
if (!S || typeof S !== 'object') S = {};
S.v = 1; S.goals = S.goals || {}; S.clicks = S.clicks || {}; S.soft = S.soft || {}; S.conv = Array.isArray(S.conv) ? S.conv : []; S.camps = S.camps || {}; S.tests = S.tests || {};
return S;
}
function save() { dirty = true; }
function flush() { if (!dirty || !S || !FILE) return; dirty = false; try { fs.writeFileSync(FILE + '.tmp', JSON.stringify(S)); fs.renameSync(FILE + '.tmp', FILE); } catch (e) { console.error('convtrack save', e.message); } }
function init(opts) {
FILE = path.join(opts.dataDir, 'convtrack.json'); rotator = opts.rotator || null; if (opts.campaignOf) campaignOf = opts.campaignOf;
S = null; load();
if (!opts.noTimers) { setInterval(flush, 3000).unref(); setInterval(prune, 3600000).unref(); }
}
const norm = e => String(e || '').trim().toLowerCase();
const isPx = v => /^px[a-f0-9]{10}$/.test(String(v || ''));
const isClickId = v => /^[a-z0-9]{6,24}$/i.test(String(v || ''));
const isAdId = v => /^[ai][a-f0-9]{11}$/.test(String(v || ''));
const cleanName = v => { const s = String(v == null ? '' : v).trim().toLowerCase().replace(/\s+/g, '_'); return /^[a-z0-9_-]{1,32}$/.test(s) ? s : ''; };
const cleanValue = v => { if (v === '' || v == null) return 0; const n = Number(v); return Number.isFinite(n) && n >= 0 ? Math.min(Math.round(n * 100) / 100, 100000) : 0; };
const newPx = () => { for (;;) { const id = 'px' + crypto.randomBytes(5).toString('hex'); if (!load().goals[id]) return id; } };
const newAdClickId = () => 'a' + crypto.randomBytes(6).toString('hex').slice(0, 11);
function ipOf(req) { return String(req.headers['x-forwarded-for'] || (req.socket && req.socket.remoteAddress) || '').split(',')[0].trim(); }
// the soft key: InstantAdPay computes exactly the same thing for its ad clicks (contract 2026-10-23)
function softKey(req) { return 's:' + crypto.createHash('sha256').update(ipOf(req) + '|' + String(req.headers['user-agent'] || '')).digest('hex').slice(0, 20); }
// ── goals ───────────────────────────────────────────────────────────────────────────────────────────────────────
function pubGoal(g) { return { px: g.px, name: g.name, value: g.value || 0, created: g.created, lastTest: (load().tests[g.px] || 0) || null }; }
function goalsOf(owner) { const o = norm(owner); return Object.values(load().goals).filter(g => g.owner === o).sort((a, b) => a.created - b.created); }
function goal(px) { return load().goals[String(px || '')] || null; }
function createGoal(owner, body) {
const o = norm(owner); if (!o) return { error: 'Sign in first.' };
const name = cleanName(body && body.name); if (!name) return { error: 'Name the goal with letters, numbers, - or _ (for example subscriber or sale), up to 32.' };
const mine = goalsOf(o);
if (mine.length >= MAX_GOALS) return { error: 'Up to ' + MAX_GOALS + ' goals per account. Remove one first.' };
if (mine.some(g => g.name === name)) return { error: 'You already have a goal called ' + name + '.' };
const g = { px: newPx(), owner: o, name, value: cleanValue(body && body.value), created: Date.now() };
load().goals[g.px] = g; save(); flush(); return { ok: true, goal: pubGoal(g) };
}
function updateGoal(owner, px, body) {
const g = goal(px); if (!g || g.owner !== norm(owner)) return { error: 'No such goal.' };
if (body.remove) { delete load().goals[g.px]; delete load().tests[g.px]; save(); flush(); return { ok: true, removed: true }; } // its past conversions stay in the log (the reports show them under the name)
if (body.name != null) { const n = cleanName(body.name); if (!n) return { error: 'Name the goal with letters, numbers, - or _ , up to 32.' }; if (goalsOf(g.owner).some(x => x.px !== g.px && x.name === n)) return { error: 'You already have a goal called ' + n + '.' }; g.name = n; }
if (body.value != null) g.value = cleanValue(body.value);
save(); flush(); return { ok: true, goal: pubGoal(g) };
}
// ── clicks ──────────────────────────────────────────────────────────────────────────────────────────────────────
function noteSoft(sk, id, owner, ts) {
if (!sk || !/^s:[a-f0-9]{20}$/.test(sk) || !id) return;
const st = load(); const now = ts || Date.now();
const list = (st.soft[sk] || []).filter(x => now - x[1] <= SOFT_MS && x[0] !== id);
list.push([id, now, norm(owner)]); st.soft[sk] = list.slice(-6); save();
}
// a LinkSpin ad click (banner, text, zone). Returns the click id to append to the target.
function recordAdClick(camp, req, extra) {
if (!camp || !camp.id) return null;
const st = load(); const id = newAdClickId(); const ua = String(req.headers['user-agent'] || '');
const sk = softKey(req);
let pl = String((extra && extra.placement) || ''); if (!pl) { try { const r = new URL(String(req.headers.referer || '')); pl = (r.hostname.replace(/^www\./, '') + r.pathname).slice(0, 80); } catch (e) {} }
st.clicks[id] = { id, k: 'ad', camp: Number(camp.id), cname: String(camp.name || camp.title || '').slice(0, 80), type: camp.type || '', owner: norm(camp.owner), ts: Date.now(), sk,
c: (extra && extra.country) || '', dv: /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop', pl, self: extra && extra.self ? 1 : undefined, target: String(camp.targetUrl || '').slice(0, 300) };
noteSoft(sk, id, camp.owner); trimClicks(); save();
return id;
}
// InstantAdPay pushes its ad clicks (signed partner call); an upsert by id, so a row sent twice is harmless
function importClicks(rows) {
const st = load(); let n = 0;
for (const r of (Array.isArray(rows) ? rows.slice(0, 500) : [])) {
const id = String(r && r.id || ''); if (!/^i[a-f0-9]{11}$/.test(id)) continue;
const owner = norm(r.owner); if (!owner || owner.length > 190) continue;
const ts = Number(r.ts) || Date.now(); if (ts > Date.now() + 600000 || Date.now() - ts > WINDOW_MS) continue;
const sk = /^s:[a-f0-9]{20}$/.test(String(r.sk || '')) ? String(r.sk) : '';
const had = !!st.clicks[id];
st.clicks[id] = { id, k: 'iap', camp: Number(r.camp) || 0, cname: String(r.cname || '').slice(0, 80), type: String(r.type || '').slice(0, 12), owner, ts, sk,
c: String(r.c || '').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 2), dv: r.dv === 'mobile' ? 'mobile' : 'desktop', pl: String(r.pl || '').slice(0, 80), self: r.self ? 1 : undefined, target: String(r.target || '').slice(0, 300) };
if (r.camp) { const key = 'iap:' + Number(r.camp); const cur = st.camps[key] || {}; if (!cur.ts || ts >= cur.ts) st.camps[key] = { owner, name: String(r.cname || '').slice(0, 80), spent: Math.max(0, Number(r.spent) || 0), ts }; }
if (!had && sk) noteSoft(sk, id, owner, ts);
n++;
}
if (n) { trimClicks(); save(); }
return n;
}
function trimClicks() {
const st = load(); const keys = Object.keys(st.clicks); if (keys.length <= MAX_CLICKS) return;
keys.sort((a, b) => st.clicks[a].ts - st.clicks[b].ts); for (const k of keys.slice(0, keys.length - Math.floor(MAX_CLICKS * 0.8))) delete st.clicks[k];
}
function prune() {
const st = load(); const now = Date.now();
for (const k in st.clicks) if (now - st.clicks[k].ts > WINDOW_MS + DAY) delete st.clicks[k];
for (const k in st.soft) { const l = st.soft[k].filter(x => now - x[1] <= SOFT_MS); if (l.length) st.soft[k] = l; else delete st.soft[k]; }
for (const k in st.camps) if (now - st.camps[k].ts > 400 * DAY) delete st.camps[k];
if (st.conv.length > MAX_CONV) st.conv = st.conv.slice(-Math.floor(MAX_CONV * 0.8));
save(); flush();
}
// What a click id is, who owns it, where it came from. Spin-link clicks live in rotator.json.
function lookup(id) {
id = String(id || ''); if (!isClickId(id)) return null;
const st = load();
const ad = st.clicks[id];
if (ad) return { id, root: id, ts: ad.ts, owners: [ad.owner], ad };
if (rotator && rotator.hitById) {
const h = rotator.hitById(id); if (!h || !h.hit || h.hit.bot) return null;
const via = h.hit.ac && st.clicks[h.hit.ac] ? st.clicks[h.hit.ac] : null;
return { id, root: via ? via.id : id, ts: via ? Math.min(via.ts, h.hit.ts) : h.hit.ts, owners: [h.owner].concat(via ? [via.owner] : []), ad: via, spin: h };
}
return null;
}
// ── the goal pixel ─────────────────────────────────────────────────────────────────────────────────────────────
const RL = { px: new Map(), ip: new Map() };
function rateOk(map, key, max, ms) { const now = Date.now(); const a = (map.get(key) || []).filter(t => now - t < ms); if (a.length >= max) { map.set(key, a); return false; } a.push(now); map.set(key, a); if (map.size > 50000) map.clear(); return true; }
setInterval(() => { const now = Date.now(); for (const m of [RL.px, RL.ip]) for (const [k, a] of m) if (!a.some(t => now - t < 3600000)) m.delete(k); }, 600000).unref();
const LIMITS = { pxPerMin: 60, pxPerHour: 1000, ipPerMin: 20 };
// q: { px, goal, value, c (click id from the page), m ('url'|'stored', who found it), test }
// cookies: { 'ls.clk', 'ls.click' }. Returns { result, method?, conv? } where result is counted | dup | nomatch | unknown | limited | test | refused
function record(q, req, cookies) {
const g = goal(q.px); if (!g) return { result: 'unknown' };
const sk = softKey(req); const ip = sk; // the soft key doubles as the per-visitor rate key (no raw IP held)
if (!rateOk(RL.ip, ip, LIMITS.ipPerMin, 60000)) return { result: 'limited' };
if (!rateOk(RL.px, g.px + ':m', LIMITS.pxPerMin, 60000) || !rateOk(RL.px, g.px + ':h', LIMITS.pxPerHour, 3600000)) return { result: 'limited' };
if (q.test) { load().tests[g.px] = Date.now(); save(); return { result: 'test', at: load().tests[g.px] }; }
const now = Date.now(); let refused = 0;
const tryId = (id, method) => {
const L = lookup(id); if (!L) return null;
if (!L.owners.includes(g.owner)) { refused++; return null; } // someone else's click: never counted for this pixel
if (now - L.ts > WINDOW_MS) return null;
return Object.assign(L, { method });
};
let hit = null;
if (isClickId(q.c)) hit = tryId(q.c, q.m === 'stored' ? 'stored' : 'url');
if (!hit) for (const ck of ['ls.clk', 'ls.click']) { const v = cookies && cookies[ck]; if (!hit && isClickId(v)) hit = tryId(v, 'cookie'); }
if (!hit) { const list = (load().soft[sk] || []).filter(x => x[2] === g.owner && now - x[1] <= SOFT_MS).sort((a, b) => b[1] - a[1]); for (const x of list) { hit = tryId(x[0], 'soft'); if (hit) break; } }
if (!hit) return { result: refused ? 'refused' : 'nomatch' };
const st = load();
if (st.conv.some(c => c.px === g.px && (c.root === hit.root || c.click === hit.id || c.root === hit.id))) return { result: 'dup', method: hit.method };
const ad = hit.ad, sp = hit.spin;
const value = q.value != null && q.value !== '' ? cleanValue(q.value) : (g.value || 0);
const self = ad && ad.self ? 1 : undefined; // the advertiser's own click: kept as a test, never in the counts
const conv = { id: crypto.randomBytes(6).toString('hex'), ts: now, px: g.px, goal: g.name, owner: g.owner, click: hit.id, root: hit.root, method: hit.method, value,
k: ad ? ad.k : 'spin', camp: ad ? ad.camp : undefined, cname: ad ? ad.cname : undefined, ctype: ad ? ad.type : undefined,
rot: sp ? sp.rotation.id : undefined, rcode: sp ? sp.rotation.code : undefined, rname: sp ? sp.rotation.name : undefined,
dest: sp ? sp.destUrl : (ad ? ad.target : undefined), sr: sp ? (sp.hit.sr || undefined) : undefined, src: sp ? sp.hit.s : (ad ? ad.pl : undefined),
c: (sp ? sp.hit.c : ad && ad.c) || '', dv: (sp ? sp.hit.dv : ad && ad.dv) || '', self };
for (const k of Object.keys(conv)) if (conv[k] === undefined) delete conv[k];
st.conv.push(conv); save();
return { result: 'counted', method: hit.method, conv, hit };
}
// the postback context for a counted conversion (postbacks.fire)
function postbackCtx(r) {
const c = r.conv, sp = r.hit && r.hit.spin;
return { q: sp ? (sp.hit.q || {}) : {}, source: c.src || '', country: c.c || '', device: c.dv || '', lsid: c.click, code: c.rcode || '', sourceId: c.sr || '', payout: c.value || 0, currency: 'USD', label: c.goal };
}
// the landing tag's beacon: it saw a click id on the member's page. Returns the id when it is a real click of the pixel's owner.
function landing(px, id, req) {
const g = goal(px); if (!g || !isClickId(id)) return null;
if (!rateOk(RL.ip, softKey(req) + ':t', 60, 60000)) return null;
const L = lookup(id); if (!L || !L.owners.includes(g.owner) || Date.now() - L.ts > WINDOW_MS) return null;
noteSoft(softKey(req), id, g.owner); return id;
}
// ── reports ─────────────────────────────────────────────────────────────────────────────────────────────────────
// per goal: totals, match methods, and breakdowns by ad campaign (LinkSpin + InstantAdPay), spin link, destination
// and traffic source. Cost per goal on ad campaigns = the campaign's credits spent / its conversions of that goal.
async function report(owner, days, opts) {
const o = norm(owner); const since = Date.now() - (Math.max(1, Math.min(400, Number(days) || 30))) * DAY;
const goals = goalsOf(o); const st = load();
const conv = st.conv.filter(c => c.owner === o && c.ts >= since && !c.self);
const selfTests = st.conv.filter(c => c.owner === o && c.ts >= since && c.self).length;
const methods = { url: 0, stored: 0, cookie: 0, soft: 0 };
const byGoal = {};
const at = (gname) => (byGoal[gname] = byGoal[gname] || { goal: gname, n: 0, value: 0, methods: { url: 0, stored: 0, cookie: 0, soft: 0 }, campaigns: {}, links: {}, dests: {}, sources: {} });
for (const c of conv) {
const G = at(c.goal); G.n++; G.value += c.value || 0; G.methods[c.method] = (G.methods[c.method] || 0) + 1; methods[c.method] = (methods[c.method] || 0) + 1;
if (c.camp) { const key = (c.k === 'iap' ? 'iap:' : 'ls:') + c.camp; const x = G.campaigns[key] = G.campaigns[key] || { key, site: c.k === 'iap' ? 'InstantAdPay' : 'LinkSpin', id: c.camp, name: c.cname || '', n: 0, value: 0 }; x.n++; x.value += c.value || 0; }
if (c.rot) { const x = G.links[c.rot] = G.links[c.rot] || { id: c.rot, code: c.rcode, name: c.rname || '', n: 0, value: 0 }; x.n++; x.value += c.value || 0; }
if (c.dest) { let d = c.dest; try { const u = new URL(c.dest); d = u.hostname.replace(/^www\./, '') + u.pathname.replace(/\/$/, ''); } catch (e) {} const x = G.dests[d] = G.dests[d] || { k: d, n: 0 }; x.n++; }
{ const key = c.sr ? 'src:' + c.sr : (c.src || '(direct)'); const x = G.sources[key] = G.sources[key] || { k: key, sourceId: c.sr || '', n: 0 }; x.n++; }
}
// clicks per ad campaign in the same window, and the cost basis
const clicksBy = {}; for (const k in st.clicks) { const a = st.clicks[k]; if (a.owner !== o || a.ts < since || a.self) continue; const key = (a.k === 'iap' ? 'iap:' : 'ls:') + a.camp; clicksBy[key] = (clicksBy[key] || 0) + 1; }
const meta = (opts && opts.sourceMeta) || {};
const out = [];
for (const gname of new Set(goals.map(g => g.name).concat(Object.keys(byGoal)))) {
const G = byGoal[gname] || at(gname);
const campaigns = [];
for (const x of Object.values(G.campaigns)) {
let spent = null, asOf = null;
if (x.site === 'LinkSpin') { try { const cp = await campaignOf(x.id); if (cp && norm(cp.owner) === o) { spent = Number(cp.spent || 0) + Number(cp.accrued || 0); if (!x.name) x.name = cp.name || ''; } } catch (e) {} }
else { const cm = st.camps['iap:' + x.id]; if (cm && cm.owner === o) { spent = cm.spent; asOf = cm.ts; if (!x.name) x.name = cm.name; } }
campaigns.push(Object.assign(x, { clicks: clicksBy[x.key] || 0, spent, spentAsOf: asOf, costPer: spent != null && x.n ? Math.round(spent / x.n * 100) / 100 : null, rate: clicksBy[x.key] ? Math.round(x.n / clicksBy[x.key] * 1000) / 10 : null }));
}
campaigns.sort((a, b) => b.n - a.n);
const sources = Object.values(G.sources).map(x => Object.assign(x, { name: x.sourceId ? ((meta[x.sourceId] || {}).name || 'Deleted source') : x.k })).sort((a, b) => b.n - a.n).slice(0, 15);
const g = goals.find(y => y.name === gname);
out.push({ goal: gname, px: g ? g.px : null, removed: !g, n: G.n, value: Math.round(G.value * 100) / 100, methods: G.methods, campaigns,
links: Object.values(G.links).sort((a, b) => b.n - a.n).slice(0, 15), dests: Object.values(G.dests).sort((a, b) => b.n - a.n).slice(0, 15), sources });
}
return { days: Number(days) || 30, goals: goals.map(g => Object.assign(pubGoal(g), { conv: conv.filter(c => c.px === g.px).length, lastAt: (conv.filter(c => c.px === g.px).pop() || {}).ts || null })),
byGoal: out, methods, total: conv.length, selfTests };
}
// InstantAdPay's view: goals + per IAP campaign conversions (and clicks) for this owner
// goal conversions (not the owner's own tests) since a moment, for the Engine Room's goals dial (2026-10-24)
function countSince(owner, since) { const o = norm(owner); return load().conv.filter(c => c.owner === o && c.ts >= since && !c.self).length; }
function partnerSummary(owner, days) {
const o = norm(owner); const since = Date.now() - (Math.max(1, Math.min(90, Number(days) || 30))) * DAY; const st = load();
const conv = st.conv.filter(c => c.owner === o && c.ts >= since && !c.self);
const byCampaign = {};
for (const k in st.clicks) { const a = st.clicks[k]; if (a.k !== 'iap' || a.owner !== o || a.ts < since || a.self) continue; const b = byCampaign[a.camp] = byCampaign[a.camp] || { clicks: 0, conv: {}, value: {} }; b.clicks++; }
for (const c of conv) if (c.k === 'iap' && c.camp) { const b = byCampaign[c.camp] = byCampaign[c.camp] || { clicks: 0, conv: {}, value: {} }; b.conv[c.px] = (b.conv[c.px] || 0) + 1; b.value[c.px] = Math.round(((b.value[c.px] || 0) + (c.value || 0)) * 100) / 100; }
const methods = { url: 0, stored: 0, cookie: 0, soft: 0 }; for (const c of conv) methods[c.method] = (methods[c.method] || 0) + 1;
const goals = goalsOf(o).map(g => { const mine = conv.filter(c => c.px === g.px); return Object.assign(pubGoal(g), { conv: mine.length, convDays: Number(days) || 30, lastAt: mine.length ? mine[mine.length - 1].ts : null }); });
return { ok: true, goals, byCampaign, methods };
}
function csv(owner, days) {
const o = norm(owner); const since = Date.now() - (Math.max(1, Math.min(400, Number(days) || 30))) * DAY;
const esc = v => { const s = v == null ? '' : String(v); return /[",\n]/.test(s) || /^[=+\-@]/.test(s) ? '"' + (/^[=+\-@]/.test(s) ? "'" : '') + s.replace(/"/g, '""') + '"' : s; };
const ctFmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
const lines = ['time_central,goal,value,match_method,site,campaign_id,campaign,spin_link,destination,source,country,device,click_id'];
for (const c of load().conv) if (c.owner === o && c.ts >= since && !c.self) lines.push([ctFmt.format(new Date(c.ts)).replace(',', ''), c.goal, c.value || 0, c.method, c.k === 'iap' ? 'InstantAdPay' : (c.k === 'ad' ? 'LinkSpin ad' : 'Spin link'), c.camp || '', c.cname || '', c.rcode || '', c.dest || '', c.src || '', c.c || '', c.dv || '', c.click].map(esc).join(','));
return lines.join('\n') + '\n';
}
// "Send a test conversion" from a screen (InstantAdPay's partner call, or the Control Room when it cannot load the image)
function testGoal(owner, px) { const g = goal(px); if (!g || g.owner !== norm(owner)) return { error: 'No such goal.' }; load().tests[g.px] = Date.now(); save(); flush(); return { ok: true, at: load().tests[g.px] }; }
function adminCounts() { const st = load(); return { goals: Object.keys(st.goals).length, clicks: Object.keys(st.clicks).length, conversions: st.conv.length }; }
module.exports = { countSince, init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS };