From dd2244272bfdb199584beee588120d00b5e5b0b3 Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 23 Oct 2026 18:10:46 -0500 Subject: [PATCH] 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 --- convtrack.js | 252 +++++++++++++++++++++++++++++++++++++++++++++++++++ postbacks.js | 7 +- public/cv.js | 34 +++++++ public/t.js | 72 +++++++++++++++ rotator.js | 29 +++++- server.js | 93 ++++++++++++++++++- zones.js | 4 +- 7 files changed, 477 insertions(+), 14 deletions(-) create mode 100644 convtrack.js create mode 100644 public/cv.js create mode 100644 public/t.js diff --git a/convtrack.js b/convtrack.js new file mode 100644 index 0000000..bfced8e --- /dev/null +++ b/convtrack.js @@ -0,0 +1,252 @@ +// 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 +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 = { 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 }; diff --git a/postbacks.js b/postbacks.js index c34a40b..217c9d4 100644 --- a/postbacks.js +++ b/postbacks.js @@ -17,7 +17,7 @@ const J = { db: null, FILE: () => path.join(DATA_DIR, 'postbacks.json'), save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } }; function init(opts) { DATA_DIR = opts.dataDir; ownHosts = opts.ownHosts || (() => []); rotator = opts.rotator; SOURCES = opts.sources || null; J.load(); } const norm = e => String(e || '').trim().toLowerCase(); -const EVENTS = ['join', 'lead', 'wallet', 'purchase', 'external']; +const EVENTS = ['join', 'lead', 'wallet', 'purchase', 'external', 'goal']; // 'goal' = any conversion-pixel goal (2026-10-23); {event} carries the goal's name const MACRO = /\{([a-z0-9_]{1,24})\}/gi; function isPrivateIp(ip) { @@ -102,7 +102,8 @@ async function fire(owner, event, ctx) { const q = (ctx.q || {}); const vals = { clickid: q.clickid || q.cid || q.click_id || q.external_id || q.visitor_id || '', subid: q.subid || q.sub_id || q.s1 || '', s1: q.s1 || q.sub1 || '', s2: q.s2 || q.sub2 || '', s3: q.s3 || q.sub3 || '', s4: q.s4 || q.sub4 || '', s5: q.s5 || q.sub5 || '', source: ctx.source || '', event, payout: ctx.payout != null ? ctx.payout : '', currency: ctx.currency || 'USD', txid: ctx.txid || '', lsid: ctx.lsid || '', code: ctx.code || '', country: ctx.country || '', device: ctx.device || '' }; for (const [k, v] of Object.entries(q)) if (/^(utm_[a-z]+|sub\d|s\d|aff_sub\d?|t\d|cost|zone|placement|site|campaign|creative|banner|keyword|geo|os|browser|carrier|format)$/.test(k) && vals[k] == null) vals[k] = v; - for (const p of J.db.items.filter(x => x.owner === o && x.enabled && x.events.includes(event))) { + const listens = evs => (evs || []).includes(event) || (!!ctx.goal && (evs || []).includes('goal')); + for (const p of J.db.items.filter(x => x.owner === o && x.enabled && listens(x.events))) { if (!rateOk(o)) break; const url = fill(p.url, vals); let r = await deliver(p, url, Object.assign({}, ctx, { event })); @@ -112,7 +113,7 @@ async function fire(owner, event, ctx) { // the traffic source that sent this click (and only that one) hears about it through its own postback if (ctx.sourceId && SOURCES) { const s = SOURCES.forFire(o, ctx.sourceId); - if (s && (s.events || []).includes(event) && rateOk(o)) { + if (s && listens(s.events) && rateOk(o)) { const url = fill(s.postbackUrl, vals); let r = await deliver(s, url, Object.assign({}, ctx, { event, viaSource: s.id })); if (!r.ok && !ctx.test) { await new Promise(res => setTimeout(res, 4000)); r = await deliver(s, url, Object.assign({}, ctx, { event, viaSource: s.id })); } diff --git a/public/cv.js b/public/cv.js new file mode 100644 index 0000000..2f0e98e --- /dev/null +++ b/public/cv.js @@ -0,0 +1,34 @@ +/* LinkSpin goal pixel, script version (conversion pixel, 2026-10-23). Paste on your thank-you page: + * (optional &value=19.95) + * It sends the click id from this page's address, or the one the landing tag (t.js) kept on your site, to LinkSpin. + * The image version (cv.gif) works without scripts; this one is surer because it can read what the landing tag kept. + * It never throws and never blocks your page. + */ +(function () { + try { + var RX = /^[a-z0-9]{6,24}$/i, W = window; + function stored() { + var v = ''; + try { var j = JSON.parse(W.localStorage.getItem('ls_clk') || 'null'); if (j && RX.test(j.id || '') && Date.now() - (j.ts || 0) < 30 * 864e5) v = j.id; } catch (e) {} + if (!v) { try { var m = /(?:^|;\s*)ls_clk=([a-z0-9]{6,24})/i.exec(document.cookie || ''); if (m) v = m[1]; } catch (e) {} } + return v; + } + var q = new URLSearchParams(location.search); + var inUrl = q.get('lsclk') || q.get('lsid') || q.get('clickid') || ''; + var c = '', m = ''; + if (RX.test(inUrl)) { c = inUrl; m = 'url'; } else { c = stored(); m = c ? 'stored' : ''; } + var list = document.getElementsByTagName('script'); + for (var i = 0; i < list.length; i++) { + var s = list[i]; + try { + if (!/\/cv\.js(\?|$)/.test(s.src || '') || s.getAttribute('data-ls-done')) continue; + s.setAttribute('data-ls-done', '1'); + var u = new URL(s.src, location.href), px = u.searchParams.get('px') || ''; + if (!/^px[a-f0-9]{10}$/.test(px)) continue; + var goal = u.searchParams.get('goal') || '', value = u.searchParams.get('value'); + var out = u.origin + '/cv.gif?px=' + px + (goal ? '&goal=' + encodeURIComponent(goal) : '') + (value != null && value !== '' ? '&value=' + encodeURIComponent(value) : '') + (c ? '&c=' + encodeURIComponent(c) + '&m=' + m : '') + (u.searchParams.get('test') === '1' ? '&test=1' : '') + '&r=' + Math.random().toString(36).slice(2, 8); + var im = new Image(1, 1); im.src = out; + } catch (e) {} + } + } catch (e) { /* never break the member's page */ } +})(); diff --git a/public/t.js b/public/t.js new file mode 100644 index 0000000..210d2a8 --- /dev/null +++ b/public/t.js @@ -0,0 +1,72 @@ +/* LinkSpin landing tag (conversion pixel, 2026-10-23). Paste once on your landing page: + * + * It reads the click id LinkSpin or InstantAdPay put on the link (lsclk, lsid or clickid in the address), keeps it on YOUR + * site for 30 days (localStorage + a first-party cookie, both named ls_clk), copies it into hidden form fields named lsclk, + * lsid or clickid, and adds it to links that stay on your site. Nothing personal is read or stored. + * It never throws and never blocks your page: every step is wrapped, and it only runs after the page has its scripts. + */ +(function () { + try { + var KEY = 'ls_clk', RX = /^[a-z0-9]{6,24}$/i, DAYS = 30, W = window; + var me = document.currentScript; + if (!me) { var all = document.getElementsByTagName('script'); for (var i = all.length - 1; i >= 0; i--) { if (/\/t\.js(\?|$)/.test(all[i].src || '')) { me = all[i]; break; } } } + if (!me || !me.src) return; + var src = new URL(me.src, location.href), base = src.origin, px = src.searchParams.get('px') || ''; + var framed = true; try { framed = W.top !== W.self; } catch (e) { framed = true; } + var https = location.protocol === 'https:'; + function setCookie(v) { + try { document.cookie = KEY + '=' + v + '; path=/; max-age=' + (DAYS * 86400) + (https ? (framed ? '; SameSite=None; Secure' : '; SameSite=Lax; Secure') : '; SameSite=Lax'); } catch (e) {} + } + function stored() { + var v = ''; + try { var j = JSON.parse(W.localStorage.getItem(KEY) || 'null'); if (j && RX.test(j.id || '') && Date.now() - (j.ts || 0) < DAYS * 864e5) v = j.id; } catch (e) {} + if (!v) { try { var m = /(?:^|;\s*)ls_clk=([a-z0-9]{6,24})/i.exec(document.cookie || ''); if (m) v = m[1]; } catch (e) {} } + return v; + } + function keep(v) { try { W.localStorage.setItem(KEY, JSON.stringify({ id: v, ts: Date.now() })); } catch (e) {} setCookie(v); } + var q = new URLSearchParams(location.search); + var fresh = q.get('lsclk') || q.get('lsid') || ''; + var id = ''; + if (RX.test(fresh)) { id = fresh; keep(id); } + else { + id = stored(); + // a generic clickid only when we hold nothing better (it may be another network's id) + var g = q.get('clickid') || ''; if (!id && RX.test(g)) { id = g; keep(id); fresh = g; } + } + // tell LinkSpin the landing happened (sets its own 30-day cookie and the 24 h match); only for a fresh id + if (fresh && RX.test(fresh) && /^px[a-f0-9]{10}$/.test(px)) { try { var im = new Image(1, 1); im.src = base + '/t.gif?px=' + px + '&c=' + encodeURIComponent(fresh) + '&r=' + Math.random().toString(36).slice(2, 8); } catch (e) {} } + var LS = W.LinkSpin = W.LinkSpin || {}; + LS.clickId = function () { return id || stored(); }; + LS.goal = function (pixelId, name, value) { + try { + var c = id || stored(); var u = base + '/cv.gif?px=' + encodeURIComponent(pixelId) + (name ? '&goal=' + encodeURIComponent(name) : '') + (value != null && value !== '' ? '&value=' + encodeURIComponent(value) : '') + (c ? '&c=' + encodeURIComponent(c) + '&m=stored' : '') + '&r=' + Math.random().toString(36).slice(2, 8); + var im2 = new Image(1, 1); im2.src = u; + } catch (e) {} + }; + if (!id) return; + var NAMES = ['lsclk', 'lsid', 'clickid']; + function fillForms(root) { + try { + var f = (root || document).querySelectorAll('input[name="lsclk"],input[name="lsid"],input[name="clickid"]'); + for (var i = 0; i < f.length; i++) if (!f[i].value) f[i].value = id; + } catch (e) {} + } + fillForms(); + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', function () { fillForms(); }); + document.addEventListener('submit', function (e) { fillForms(e.target); }, true); + var host = location.hostname.replace(/^www\./, ''); + function decorate(a) { + try { + if (!a || !a.href || a.getAttribute('data-ls-skip') != null) return; + var u = new URL(a.href, location.href); + if (!/^https?:$/.test(u.protocol) || u.hostname.replace(/^www\./, '') !== host) return; + if (u.pathname === location.pathname && u.search === location.search && u.hash) return; // an anchor on this page + for (var i = 0; i < NAMES.length; i++) if (u.searchParams.has(NAMES[i])) return; + u.searchParams.set('lsclk', id); a.href = u.toString(); + } catch (e) {} + } + function onClick(e) { try { var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; if (a) decorate(a); } catch (er) {} } + document.addEventListener('click', onClick, true); + document.addEventListener('auxclick', onClick, true); + } catch (e) { /* never break the member's page */ } +})(); diff --git a/rotator.js b/rotator.js index 83033a7..8cce16d 100644 --- a/rotator.js +++ b/rotator.js @@ -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=. + // 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= 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 }; diff --git a/server.js b/server.js index e5de542..8446627 100644 --- a/server.js +++ b/server.js @@ -63,6 +63,7 @@ const carry = require('./carry'); // sponsor carry-over: engine acti const rotator = require('./rotator'); const health = require('./health'); // destination health checks + auto-pause (2026-10-10) const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29) +const convtrack = require('./convtrack'); // conversion pixel: goals, ad click ids, landing tag + goal pixel, per-goal reports (2026-10-23) const bannerspin = require('./bannerspin'); // Banner Spin: one image URL + one click URL rotating up to 25 banners (2026-10-18) const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12) const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/ (2026-09-29) @@ -657,7 +658,8 @@ async function boot() { setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000); setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000); const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []); - rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources }); + rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources, wantsClickId: owner => convtrack.goalsOf(owner).length > 0 }); + convtrack.init({ dataDir: DATA_DIR, rotator, campaignOf: id => ads.campaignById(id) }); // destination health: every 30 min, first pass 2 min after boot; a pause lands in the owner's on-site inbox (same path as the payment notices) health.init({ rotator, bannerspin, dataDir: DATA_DIR, notify: (email, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, html) }); setTimeout(() => health.tick().catch(e => console.error('health', e.message)), 2 * 60 * 1000); @@ -799,6 +801,23 @@ function readRaw(req, maxBytes) { req.on('error', reject); }); } +// conversion pixel (2026-10-23): the click-id cookie on our own host. SameSite=None so the goal pixel (a third-party image +// on the member's thank-you page) can still send it where the browser allows third-party cookies; 30 days like the window. +// the image pixel cannot read the thank-you page's address, but a browser that sends the full referrer hands it to us +function refClickId(req) { try { const r = new URL(String(req.headers.referer || '')); const v = r.searchParams.get('lsclk') || r.searchParams.get('lsid') || ''; return /^[a-z0-9]{6,24}$/i.test(v) ? v : ''; } catch (e) { return ''; } } +function clickCookie(id) { return 'ls.clk=' + id + '; Path=/; Max-Age=2592000; ' + (IS_PROD ? 'SameSite=None; Secure' : 'SameSite=Lax'); } +// an ad click: record a click id for the campaign and append ?lsclk= to the target (existing params kept, an lsclk +// already there left alone). A spin-link target passes it on, so the spin-link click inherits the ad as its source. +// Never blocks the click: on any failure the visitor goes to the target unchanged. +async function adClickTarget(campOrId, url, req, extra) { + try { + const camp = typeof campOrId === 'object' ? campOrId : await ads.campaignById(campOrId); if (!camp) return { url }; + let self = false; try { const s = await auth.fromRequest(req); self = !!(s && s.email && String(s.email).toLowerCase() === String(camp.owner || '').toLowerCase()); } catch (e) {} + const id = convtrack.recordAdClick(camp, req, Object.assign({ country: viewerGeo(req).cc || '', self }, extra || {})); if (!id) return { url }; + let out = url; try { const t = new URL(url); if (!t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {} + return { url: out, cookie: clickCookie(id), id }; + } catch (e) { console.error('ad click id', e.message); return { url }; } +} function readBody(req) { return new Promise((resolve, reject) => { let d = ''; let n = 0; @@ -1115,7 +1134,7 @@ function linkSitePage(host, page) { home: '

' + H + '

This domain is a link forwarding service operated by ' + brand + ', a member advertising network. Links on this domain forward visitors in one step to pages published by our members and their partners.

We do not host the pages you land on, and we do not collect payment information here. If a link forwarded you somewhere you did not expect, or to content that looks unsafe, tell us on the report page and we will pull the link.

What we record

When a link is followed we record the day, the country, the referring site, the device type and a one-day anonymous visitor token. We do not store your IP address or any personal data. Details are in the privacy policy.

', disclosure: '

Affiliate and advertising disclosure

Links forwarded through ' + H + ' may be affiliate links or paid advertisements. The member who published a link may earn a commission or advertising credit if you buy something or sign up on the page you land on. This never changes the price you pay.

' + brand + ' itself is an advertising platform. Members buy ad packages and earn commissions when people they referred buy ad packages. No income is guaranteed to anyone; results depend on effort, and any earnings examples on member pages are illustrations, not promises.

The pages you are forwarded to belong to their publishers. We are not responsible for their claims, and we remove links that are reported and found to violate our terms.

', terms: '

Terms of use

By following a link on ' + H + ' you agree to these terms.

The service

' + H + ' forwards visitors to destinations chosen by ' + brand + ' members. We provide the forwarding only. We do not endorse, verify or control the destination pages, and we are not a party to any transaction you make there.

Acceptable use

Members may not forward visitors to content that is illegal, deceptive, malicious, adult, or that impersonates another business. Links that violate this are removed and the member\'s account is closed. Automated access to this domain is not permitted except by search engines.

No warranty

The service is provided as is. We do not guarantee that any link will be available, and we are not liable for the content, availability or conduct of destination sites.

Contact

Questions about these terms: linkspin.co.

', - privacy: '

Privacy policy

This policy covers ' + H + ' and the link forwarding service on it.

What we collect

When you follow a link we record the date, your country (derived from your network address and then discarded), the site that referred you, whether you are on a phone or a computer, and an anonymous visitor token that changes every day and cannot be traced back to you. We do not store your IP address, your name, your email address or any account information on this domain.

Cookies

This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.

Why we collect it

So members can see how many people followed their links and from where. Counts are shown to the member who published the link, in aggregate, and to nobody else.

Retention

Link statistics are kept for up to thirteen months and then deleted.

Your rights

Because we hold no personal data on this domain there is nothing to access or delete here. For anything involving a ' + brand + ' member account, contact us through linkspin.co.

', + privacy: '

Privacy policy

This policy covers ' + H + ' and the link forwarding service on it.

What we collect

When you follow a link we record the date, your country (derived from your network address and then discarded), the site that referred you, whether you are on a phone or a computer, and an anonymous visitor token that changes every day and cannot be traced back to you. We do not store your IP address, your name, your email address or any account information on this domain.

Click ids

If the member who owns the link tracks goals, or you arrived from an ad, the page you are forwarded to gets a random click id in its address (lsclk). The site you land on may keep it for 30 days to count whether the visit led to a sign-up or a sale. It identifies the click, not you.

Cookies

This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.

Why we collect it

So members can see how many people followed their links and from where. Counts are shown to the member who published the link, in aggregate, and to nobody else.

Retention

Link statistics are kept for up to thirteen months and then deleted.

Your rights

Because we hold no personal data on this domain there is nothing to access or delete here. For anything involving a ' + brand + ' member account, contact us through linkspin.co.

', abuse: '

Report a link

If a link on ' + H + ' forwarded you to a page that is deceptive, unsafe, adult, or impersonates a business, tell us. We review every report and pull the link first, then ask questions.

Send the full link you clicked (it starts with https://' + H + '/r/ or https://' + H + '/c/) and what you saw, or the address of a banner image you want reviewed, to the support contact on linkspin.co. Reports are usually handled the same day.

', gone: '

That link is not active

The link you followed has been removed or has expired. Nothing was recorded. If you were expecting a specific page, ask the person who shared the link for a fresh one.

' }; @@ -1169,7 +1188,7 @@ const server = http.createServer(async (req, res) => { const u = new URL(req.url, 'http://x'); const p = u.pathname; // zone endpoints run on other people's sites and show only ad creatives, so they pass the curtain - const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18) + const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p === '/t.js' || p === '/t.gif' || p === '/cv.gif' || p === '/cv.js' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18) // support must reach everyone, invited or not (2026-10-16): someone locked out or not yet let in is exactly who needs it if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor @@ -1213,6 +1232,26 @@ const server = http.createServer(async (req, res) => { if (!am.vid) h['Set-Cookie'] = audiences.cookieHeader(audiences.newVid(), IS_PROD); res.writeHead(200, h); return res.end(JSON.stringify({ ad })); } + // -- conversion pixel (2026-10-23): /t.js the landing tag, /t.gif its beacon, /cv.gif + /cv.js the goal pixel. Any origin, + // never cached, always a 1x1 gif (the member's page never sees an error). X-LS-Result says what happened (tests, debugging). + if ((p === '/t.js' || p === '/cv.js') && (req.method === 'GET' || req.method === 'HEAD')) { + try { const body = fs.readFileSync(path.join(PUBLIC_DIR, p.slice(1))); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff' }); return res.end(req.method === 'HEAD' ? '' : body); } catch (e) { res.writeHead(404); return res.end(); } + } + if ((p === '/t.gif' || p === '/cv.gif') && req.method === 'GET') { + const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length), 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'X-LS-Result', 'X-Robots-Tag': 'noindex' }; + const px = String(u.searchParams.get('px') || ''); + try { + if (p === '/t.gif') { + const id = convtrack.isPx(px) ? convtrack.landing(px, String(u.searchParams.get('c') || ''), req) : null; + if (id) h['Set-Cookie'] = clickCookie(id); h['X-LS-Result'] = id ? 'stored' : 'ignored'; + } else if (convtrack.isPx(px)) { + const r = convtrack.record({ px, goal: u.searchParams.get('goal'), value: u.searchParams.get('value'), c: String(u.searchParams.get('c') || u.searchParams.get('lsclk') || u.searchParams.get('lsid') || u.searchParams.get('clickid') || refClickId(req) || ''), m: u.searchParams.get('m'), test: u.searchParams.get('test') === '1' }, req, parseCookies(req)); + h['X-LS-Result'] = r.result + (r.method ? ';' + r.method : ''); + if (r.result === 'counted' && !r.conv.self) postbacks.fire(r.conv.owner, r.conv.goal, Object.assign(convtrack.postbackCtx(r), { goal: true })).catch(e => console.error('goal postback', e.message)); + } else h['X-LS-Result'] = 'unknown'; + } catch (e) { console.error('conversion pixel', e.message); h['X-LS-Result'] = 'error'; } + res.writeHead(200, h); return res.end(PIXEL_GIF); + } // audience pixel: 1x1 gif, sets/refreshes the visitor cookie, records the hit (30-day membership) if (p === '/p.gif' && req.method === 'GET') { const a = String(u.searchParams.get('a') || ''); const vid = audiences.cookieVid(req); const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length) }; @@ -1229,7 +1268,7 @@ const server = http.createServer(async (req, res) => { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src https://www.networkadspace.com https://networkadspace.com 'unsafe-inline'; img-src https: http: data:; style-src 'unsafe-inline'; frame-src https: http:; frame-ancestors *; base-uri 'none'", 'Referrer-Policy': 'no-referrer' }); return res.end(html); } if (p === '/api/zone/seen' && (req.method === 'GET' || req.method === 'POST')) { await zones.seen(u.searchParams.get('i'), req); res.writeHead(204, corsCreds(req)); return res.end(); } - { const zm = /^\/api\/zone\/click\/([a-f0-9]{12})$/.exec(p); if (zm && req.method === 'GET') { const target = await zones.click(zm[1]); res.writeHead(302, { Location: target || '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); } } + { const zm = /^\/api\/zone\/click\/([a-f0-9]{12})$/.exec(p); if (zm && req.method === 'GET') { let ck = null; const target = await zones.click(zm[1], async (camp, url) => { const t = await adClickTarget(camp, url, req, { placement: 'zone' }); ck = t.cookie; return t.url; }); const zh = { Location: target || '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }; if (ck) zh['Set-Cookie'] = ck; res.writeHead(302, zh); return res.end(); } } // -- publisher program (2026-10-10): the public offer for site owners who carry zones, and its live "Network right now" // strip (7-day totals from zones.js, cached a minute). App host only; the link and pages domains stay single-purpose. // Today's POL price in US dollars for the member pages (Marty, 2026-10-22, same as InstantAdPay): the contract's own package @@ -2556,6 +2595,29 @@ const server = http.createServer(async (req, res) => { let bsum = null; try { bsum = await bannerspin.summary(s.email, days); } catch (e) { console.error('bannerspin summary', e.message); } return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, bannerSpins: bsum, days: spins.days, range: days }), { 'Cache-Control': 'no-store' }); } + // -- conversion pixel (2026-10-23): goals, per-goal reports, CSV, test. GET and POST (the shell's api() always POSTs). + if (p === '/api/my/conversions' && (req.method === 'GET' || req.method === 'POST')) { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = req.method === 'POST' ? await readBody(req).catch(() => ({})) : {}; + const days = Math.max(1, Math.min(365, Number(b.days || u.searchParams.get('days')) || 30)); + const r = await convtrack.report(s.email, days, { sourceMeta: sources.meta ? sources.meta(s.email) : {} }); + return json(res, 200, Object.assign(r, { host: SITE_HOST, base: (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, limits: convtrack.LIMITS, windowDays: 30, softHours: 24 }), { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/conversions/goals' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req).catch(() => ({})); const r = convtrack.createGoal(s.email, b); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/conversions\/goals\/(px[a-f0-9]{10})$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req).catch(() => ({})); const r = b.test ? convtrack.testGoal(s.email, m[1]) : convtrack.updateGoal(s.email, m[1], b); return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/conversions.csv' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const days = Math.max(1, Math.min(365, Number(u.searchParams.get('days')) || 30)); + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="linkspin-conversions-' + days + 'd.csv"', 'Cache-Control': 'no-store' })); + return res.end(convtrack.csv(s.email, days)); + } // -- traffic sources (2026-10-12). Every route takes GET and POST: the shell's api() helper always POSTs. if (p === '/api/sources/catalog' && (req.method === 'GET' || req.method === 'POST')) return json(res, 200, { catalog: sources.catalog(), keys: sources.KEYS }, { 'Cache-Control': 'public, max-age=300' }); if (p === '/api/my/sources' && (req.method === 'GET' || req.method === 'POST')) { @@ -2655,6 +2717,25 @@ const server = http.createServer(async (req, res) => { return json(res, 200, { ok: true, proto: SF.PROTO, rows: rows.length, imported: n, shells, updated, followed, followKept: kept, registry: await registry.count() }); } finally { carry.unhold(held); } } + // -- conversion pixel, InstantAdPay side (2026-10-23): its ad clicks arrive here (signed, upsert by id), and its members' + // goals live on their LinkSpin account (same email): summary for the Campaigns rows, create / update / remove / test. + if (p === '/api/partner/clicks' && req.method === 'POST') { + const sg = await readPartnerSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error }); + return json(res, 200, { ok: true, n: convtrack.importClicks(sg.body.clicks) }); + } + if (p === '/api/partner/conv' && req.method === 'POST') { + const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error }); + const b = sg.body; const email = String(b.email || '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) || email.length > 190) return json(res, 400, { error: 'Which member?' }); + let r; + if (b.op === 'summary') r = Object.assign(convtrack.partnerSummary(email, b.days), { host: SITE_HOST }); + else if (b.op === 'create') r = convtrack.createGoal(email, { name: b.name, value: b.value }); + else if (b.op === 'update') r = convtrack.updateGoal(email, b.px, { name: b.name, value: b.value === null ? 0 : b.value }); // null = clear the default (InstantAdPay sends it for an empty box) + else if (b.op === 'remove') r = convtrack.updateGoal(email, b.px, { remove: true }); + else if (b.op === 'test') r = convtrack.testGoal(email, b.px); + else return json(res, 400, { error: 'op must be summary, create, update, remove or test' }); + return json(res, r.error ? 400 : 200, r); + } // -- sponsor check between LinkSpin and InstantAdPay (2026-10-22, sponsorfollow.js). Partner side: InstantAdPay reads our // facts and, on an admin's pick in ITS Sponsor check, asks us to apply a sponsor (refused when the member is bound here). if (p === '/api/partner/sponsor-facts' && req.method === 'POST') { @@ -3388,7 +3469,8 @@ const server = http.createServer(async (req, res) => { const target = await ads.click(m[1]); if (!target) { res.writeHead(404, baseHeaders()); return res.end(); } coach.recordClick(m[1], req.headers.referer); // where the click happened - res.writeHead(302, baseHeaders({ Location: target })); + const t = await adClickTarget(m[1], target, req); // conversion pixel: click id recorded + ?lsclk= on the target (2026-10-23) + res.writeHead(302, baseHeaders(Object.assign({ Location: t.url }, t.cookie ? { 'Set-Cookie': t.cookie } : {}))); return res.end(); } if (p === '/api/my/audiences' && req.method === 'GET') { @@ -3779,6 +3861,7 @@ const server = http.createServer(async (req, res) => { } if (p === '/links') return sendFile(res, path.join(PUBLIC_DIR, 'links.html')); // Control Room: the links workspace, first screen of the new front end (2026-09-29) if (p === '/reports') return sendFile(res, path.join(PUBLIC_DIR, 'reports.html')); + if (p === '/conversions') return sendFile(res, path.join(PUBLIC_DIR, 'conversions.html')); // Control Room: conversion pixel goals + per-goal reports (2026-10-23) if (p === '/pages') return sendFile(res, path.join(PUBLIC_DIR, 'pages.html')); if (p === '/zones') return sendFile(res, path.join(PUBLIC_DIR, 'zones.html')); if (p === '/sources') return sendFile(res, path.join(PUBLIC_DIR, 'sources.html')); // Control Room: traffic sources, network macros + postbacks (2026-10-12) diff --git a/zones.js b/zones.js index 5d05e95..5668276 100644 --- a/zones.js +++ b/zones.js @@ -116,11 +116,11 @@ async function seen(impId, req) { } J.save(); return { ok: true }; } -async function click(impId) { +async function click(impId, decorate) { // decorate(campaignId, url) -> url: the conversion pixel's click id (2026-10-23) 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 + '/'; } + try { const url = await ads.click(imp.camp); if (!url) return 'https://' + siteHost + '/'; return decorate ? ((await decorate(imp.camp, url).catch(() => url)) || url) : url; } 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); }