Conversion linkage, LinkSpin side (Marty 2026-11-07, "Yes ship these"): InstantAdPay's sign-ups, wallet links and package purchases on a click count for the click's owner, in one Conversions list. Reporting only: no sponsor, payout, credit or chain path changes.

The landing tag (t.js) adds the kept click id to links to linkspin.app, instantadpay.com and the share domains, also inside a member's own redirect link (Orlando's buttons are go.opgnetwerk.com/go?u=<encoded join link>). Spin and Banner Spin links are left alone and only LinkSpin's own id shapes travel. A spin link or Banner Spin pointed straight at those sites carries lsclk with no goal set up.

netconv.js: new partner op 'events' on /api/partner/conv. Append-only ledger DATA_DIR/netconv.jsonl so two app copies cannot overwrite each other, marks.claim plus the ledger keys for once-only, join and wallet once per root click, every purchase by its own key, 30 days from click to event, the first account on a click owns it, the click owner's own account and own clicks kept as tests, each row keeps what the click was so later events survive the hit ageing out of the rotator. Spin events mirror into rotator.conv (replayed on a timer) so per-link counts, sources and placements see them; postbacks fire as for LinkSpin's own conversions.

Reports > Conversions lists goals, joins, wallets, purchases, leads and partner postbacks with values, each once; per-link Conv. counts include goals. /join keeps lsclk as well as lsid. Guide, /conversions, privacy and chatbot (CANNED + FACTS) updated; reports.js and join.js tags bumped.

The false Pages webhook claim is gone from chatbot.js, join.js and the home page: leads go to the member's list and CSV, or into a pasted autoresponder form.

QA: bash qa/run.sh netconv (57 checks, also runs in member).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-07 07:46:43 -06:00
parent 01ef4e9260
commit eedc15bc13
18 changed files with 456 additions and 34 deletions
+5 -2
View File
@@ -331,7 +331,7 @@ async function click(code, req, reqHost) {
url = url.replace(/\{([a-z0-9_]{1,24})\}/gi, (mm, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()]));
try { const t = new URL(url); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid') && !/^\/r\//.test(t.pathname)) { t.searchParams.set('lsid', id); url = t.toString(); } } catch (e) {}
// straight to a page: the click id rides along for the landing tag (a spin-link target adds its own on the /r/ hop)
if (!bot) { let spinHop = false; try { spinHop = /^\/r\/[a-z0-9]{4,12}$/i.test(new URL(url).pathname); } catch (e) {} if (!spinHop) { try { if (WANTS_CLICK_ID(s.owner)) url = WITH_CLICK_ID(url, id); } catch (e) {} } }
if (!bot) { let spinHop = false; try { spinHop = /^\/r\/[a-z0-9]{4,12}$/i.test(new URL(url).pathname); } catch (e) {} if (!spinHop) { try { if (WANTS_CLICK_ID(s.owner, url)) url = WITH_CLICK_ID(url, id); } catch (e) {} } }
}
return { url, lsid: id, banner: b, matched: m, owner: s.owner };
}
@@ -348,10 +348,13 @@ function clickById(id) {
async function convert(lsid, ev, facts) {
const c = J.db.clicks.find(x => x.id === String(lsid)); if (!c) return null;
const s = J.db.spins.find(x => x.id === c.s); if (!s) return null;
if (!J.db.conv.some(x => x.lsid === c.id && x.ev === ev)) { J.db.conv.push({ lsid: c.id, s: s.id, b: c.b, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: c.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
if (!J.db.conv.some(x => x.lsid === c.id && x.ev === ev)) { J.db.conv.push({ lsid: c.id, s: s.id, b: c.b, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: c.sr || undefined, key: facts && facts.key ? String(facts.key) : undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
return { owner: s.owner, code: s.code, rotationId: 0, bannerSpinId: s.id, bannerId: c.b, q: c.q || {}, s: c.h || 'direct', c: c.c || '', dv: c.dv, sourceId: c.sr || '' };
}
// a member's Banner Spin conversions as rows (netconv.unified); rows with a key are the ledger's and are skipped there
function convRows(owner, since) { const ids = new Set(J.db.spins.filter(x => x.owner === String(owner || '').trim().toLowerCase()).map(x => x.id)); return J.db.conv.filter(c => ids.has(c.s) && c.ts >= since); }
// ── stats (phase 3, 2026-10-20): one aggregation for the builder's Stats tab and the Reports screen ──
// Views are the counted impressions (bots, prefetches and servers left out); bots and server loads are reported beside
// them. Clicks are rows (bots flagged), so day / country / device come from human clicks, the same way spin links report.
+4 -4
View File
File diff suppressed because one or more lines are too long
+11 -1
View File
@@ -270,6 +270,16 @@ async function report(owner, days, opts) {
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 };
}
// goal conversions as rows, own-click tests left out. goalRows() = every row that came through a spin link, in the rotator's own
// shape, so per-link counts include goals (2026-11-07); memoized on the length of the log, the pixel only ever appends to it.
let GR = { n: -1, rows: [] };
function goalRows() { const c = load().conv; if (GR.n !== c.length) GR = { n: c.length, rows: c.filter(x => x.rot && !x.self).map(x => ({ r: x.rot, lsid: x.click, ev: 'goal: ' + x.goal, ts: x.ts, value: x.value || 0, sr: x.sr })) }; return GR.rows; }
function goalRowsOf(owner, since) { const o = norm(owner); return load().conv.filter(c => c.owner === o && c.ts >= since && !c.self); }
// the click-side test of "is this the owner's own": the click was theirs, or the converting browser is one they sign in from
function selfFor(L, owner, sk) {
const st = load(), ad = L.ad, o = norm(owner);
return !!(st.selfIds[L.id] || st.selfIds[L.root] || (ad && ad.owner === o && (ad.self || (ad.sk && isOwnerSk(o, ad.sk)))) || (sk && isOwnerSk(o, sk)));
}
// 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; }
@@ -305,4 +315,4 @@ function withClickId(target, id) {
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
}
module.exports = { noteOwner, noteSession, importOwners, isOwnerSk, markSelfClick, withClickId, 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 };
module.exports = { goalRows, goalRowsOf, selfFor, noteOwner, noteSession, importOwners, isOwnerSk, markSelfClick, withClickId, 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 };
+134
View File
@@ -0,0 +1,134 @@
// Network conversions (Marty 2026-11-07, "Yes ship these"). REPORTING ONLY: nothing here touches sponsors, payouts, credits or
// the chain. InstantAdPay reports sign-ups, wallet links and package purchases by accounts that arrived on a LinkSpin click
// (op 'events' on /api/partner/conv, signed); LinkSpin counts them for the click's owner.
//
// - The ledger is DATA_DIR/netconv.jsonl: append-only, one write per event, so the two app copies of a deploy can both add
// to it without rewriting each other (unlike the JSON stores that rewrite the whole file). Each copy re-reads it when its
// size changes.
// - Once: marks.claim is true for exactly one copy; a key already in the ledger is a dup, so a repeat after marks are pruned
// is still refused. join and wallet count once per ROOT click (an ad click and the spin click it led to are one click), and
// each purchase counts by its own key (tx + log index). A click belongs to the first account seen on it.
// - Window: convtrack's rule, 30 days from the real click to the EVENT (not to delivery, so a retry queue never loses one).
// - The click owner's own account, and own clicks, are kept as tests: in the ledger with self:1, never counted, no postback.
// - Each row carries what the click was, so a later event still counts after the hit aged out of the rotator.
// - Spin-link events are mirrored into rotator.conv (per-link counts, sources, Reports) and Banner Spin events into its
// own conv; the mirror is replayed from the ledger on a timer, so a copy that lost a write during a deploy heals.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const EVENTS = ['join', 'wallet', 'purchase'];
let FILE = null, C = null, R = null, B = null, P = null, M = null;
let st = { size: -1, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() };
const norm = e => String(e || '').trim().toLowerCase();
const DAY = 86400000;
const acctHash = email => crypto.createHash('sha256').update('netconv|' + norm(email)).digest('hex').slice(0, 16); // never the address itself
function init(o) {
FILE = path.join(o.dataDir, 'netconv.jsonl'); C = o.convtrack; R = o.rotator; B = o.bannerspin || null; P = o.postbacks || null; M = o.marks;
st = { size: -1, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() }; refresh();
if (!o.noTimers) { setTimeout(() => syncMirror().catch(() => {}), 30000).unref(); setInterval(() => syncMirror().catch(() => {}), 300000).unref(); }
}
function refresh() {
let size = 0; try { size = fs.statSync(FILE).size; } catch (e) {}
if (size === st.size) return st;
const n = { size, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() };
let raw = ''; try { raw = fs.readFileSync(FILE, 'utf8'); } catch (e) {}
for (const line of raw.split('\n')) {
if (!line) continue; let r; try { r = JSON.parse(line); } catch (e) { continue; }
n.rows.push(r); n.keys.add(String(r.k).split('|')[0]);
for (const [m, id] of [[n.byClick, r.click], [n.byRoot, r.root]]) { const a = m.get(id); if (a) a.push(r); else m.set(id, [r]); }
}
st = n; return st;
}
// the facts of a click, for one owner, as they stand now
function factsOf(L, o) {
const sp = L.spin, ad = L.ad, bs = L.bspin, mineSpin = !!(sp && sp.owner === o), mineAd = !!(ad && ad.owner === o);
return { kind: mineSpin ? 'spin' : (mineAd ? ad.k : (bs ? 'bspin' : (ad ? ad.k : 'spin'))),
camp: mineAd ? ad.camp : undefined, cname: mineAd ? ad.cname : undefined,
rot: mineSpin ? sp.rotation.id : undefined, rcode: mineSpin ? sp.rotation.code : undefined, rname: mineSpin ? sp.rotation.name : undefined, d: mineSpin ? sp.hit.d : undefined, sr: mineSpin ? (sp.hit.sr || undefined) : undefined,
bcode: bs ? bs.spin.code : undefined, src: (sp ? sp.hit.s : (bs ? (bs.click.h || 'direct') : (ad ? ad.pl : ''))) || '', c: (sp ? sp.hit.c : (bs ? bs.click.c : ad && ad.c)) || '', dv: (sp ? sp.hit.dv : (bs ? bs.click.dv : ad && ad.dv)) || '',
q: (sp ? sp.hit.q : (bs ? bs.click.q : undefined)) || undefined };
}
// e: { k, ev, click, email, value, ts, tx, sk }. Returns { result }: counted | self | dup | other | expired | nomatch | bad.
// Every one of those is final: the sender stops retrying on any answer.
async function record(e) {
const ev = String(e && e.ev || ''), k = String(e && e.k || '').slice(0, 120), click = String(e && e.click || ''); const email = norm(e && e.email);
if (!EVENTS.includes(ev) || !k || !C.isClickId(click) || !email || email.length > 190) return { result: 'bad' };
let S = refresh(); if (S.keys.has(k)) return { result: 'dup' };
const now = Date.now(); const at = Math.min(Number(e.ts) || now, now);
const L = C.lookup(click); const prior = S.byClick.get(click) || null;
if (!L && !prior) return { result: 'nomatch' };
const root = prior ? prior[0].root : L.root; const clickTs = prior ? prior[0].clickTs : L.ts;
if (at - clickTs > C.WINDOW_MS) return { result: 'expired' };
const acct = acctHash(email); const seen = S.byRoot.get(root) || [];
if (seen.length && seen[0].acct !== acct) return { result: 'other' }; // one click, one person: the first account on it
if (ev !== 'purchase' && seen.some(r => r.ev === ev)) return { result: 'dup' };
if (!(await M.claim('net:' + (ev === 'purchase' ? k : root + ':' + ev)))) return { result: 'dup' };
const owners = L ? [...new Set(L.owners)] : [...new Set((prior || []).map(r => r.owner))];
const value = ev === 'purchase' ? C.cleanValue(e.value) : 0;
const sk = /^s:[a-f0-9]{20}$/.test(String(e.sk || '')) ? String(e.sk) : '';
const tx = String(e.tx || '').slice(0, 80) || undefined;
const rows = owners.map(o => {
const was = (prior || []).find(r => r.owner === o);
const f = L ? factsOf(L, o) : { kind: was.kind, camp: was.camp, cname: was.cname, rot: was.rot, rcode: was.rcode, rname: was.rname, d: was.d, sr: was.sr, bcode: was.bcode, src: was.src, c: was.c, dv: was.dv, q: was.q };
const self = email === o || !!(was && was.self) || seen.some(r => r.owner === o && r.self) || (L ? C.selfFor(L, o, sk) : false);
const row = Object.assign({ k: owners.length > 1 ? k + '|' + o : k, ev, ts: at, rec: now, value, acct, click, root, clickTs, owner: o, tx, self: self ? 1 : undefined }, f);
for (const x of Object.keys(row)) if (row[x] === undefined) delete row[x];
return row;
});
fs.appendFileSync(FILE, rows.map(r => JSON.stringify(r) + '\n').join('')); // one write: the whole event lands or none of it
refresh();
let counted = false;
for (const r of rows) {
if (r.self) continue;
counted = true;
await mirror(r).catch(err => console.error('netconv mirror', err.message));
if (P) P.fire(r.owner, ev, { q: r.q || {}, source: r.src, country: r.c, device: r.dv, lsid: click, code: r.rcode || r.bcode || '', sourceId: r.sr || '', payout: value, currency: 'USD', txid: tx || '', label: ev }).catch(err => console.error('netconv postback', err.message));
}
return { result: counted ? 'counted' : 'self' };
}
// LinkSpin's own sign-ups, wallets and purchases that arrived on an ad click (a / i ids): the rotator cannot see those clicks
async function fromLinkSpin(lsid, ev, facts) {
const f = facts || {}; if (!EVENTS.includes(ev) || f.key || !f.email) return null;
const k = 'ls:' + ev + ':' + (ev === 'purchase' ? (f.txid || crypto.randomBytes(6).toString('hex')) : acctHash(f.email));
await record({ k, ev, click: lsid, email: f.email, value: f.payout, ts: Date.now(), tx: f.txid });
return null;
}
async function mirror(r) {
const key = r.k.split('|')[0];
if (r.rot) return R.convert(r.click, r.ev, { payout: r.value, label: r.ev === 'purchase' ? 'InstantAdPay' : undefined, key, ts: r.ts, bound: { r: r.rot, d: r.d, sr: r.sr } });
if (r.kind === 'bspin' && r.click[0] === 'k') return R.convert(r.click, r.ev, { payout: r.value, key, ts: r.ts });
return null;
}
async function syncMirror() { for (const r of refresh().rows) if (!r.self && r.rot) await mirror(r).catch(() => {}); }
const mineSince = (o, since) => refresh().rows.filter(r => r.owner === o && r.ts >= since);
const ORDER = ['join', 'lead', 'wallet', 'purchase', 'external'];
// Reports > Conversions: everything once. Rows mirrored into the rotator are read from the rotator (which also holds
// LinkSpin's own joins, wallets, purchases, leads and partner postbacks), the ledger adds only what the rotator cannot
// hold (ad clicks, Banner Spin clicks), Banner Spin's own rows add its site events, goals come from the pixel.
function unified(owner, days) {
const o = norm(owner); const since = Date.now() - Math.max(1, Number(days) || 30) * DAY;
const m = {}; const buyers = new Set();
const add = (k, v) => { const x = m[k] = m[k] || { k, n: 0, value: 0 }; x.n++; x.value += Number(v) || 0; };
for (const c of R.convRows(o, since)) { add(c.ev, c.value); if (c.ev === 'purchase') buyers.add(c.lsid); }
if (B && B.convRows) for (const c of B.convRows(o, since)) { if (c.key) continue; add(c.ev, c.value); if (c.ev === 'purchase') buyers.add(c.lsid); }
for (const r of mineSince(o, since)) { if (r.self || r.rot) continue; add(r.ev, r.value); if (r.ev === 'purchase') buyers.add(r.root); }
const goals = {}; for (const c of C.goalRowsOf(o, since)) { const g = goals[c.goal] = goals[c.goal] || { k: 'goal:' + c.goal, n: 0, value: 0 }; g.n++; g.value += c.value || 0; }
const rows = ORDER.filter(k => m[k]).map(k => m[k]).concat(Object.keys(m).filter(k => !ORDER.includes(k)).map(k => m[k]), Object.values(goals).sort((a, b) => b.n - a.n)).map(x => Object.assign(x, { value: Math.round(x.value * 100) / 100 }));
return { rows, joins: (m.join || {}).n || 0, wallets: (m.wallet || {}).n || 0, purchases: (m.purchase || {}).n || 0, buyers: buyers.size, goals: Object.values(goals).reduce((n, g) => n + g.n, 0) };
}
// InstantAdPay's Campaigns card: the same rows, and the events on each of the member's InstantAdPay ad campaigns
function partner(owner, days) {
const o = norm(owner); const d = Math.max(1, Math.min(90, Number(days) || 30)); const since = Date.now() - d * DAY;
const byCampaign = {};
for (const r of mineSince(o, since)) { if (r.self || r.kind !== 'iap' || !r.camp) continue; const b = byCampaign[r.camp] = byCampaign[r.camp] || { join: 0, wallet: 0, purchase: 0, value: 0 }; b[r.ev]++; b.value = Math.round((b.value + (r.value || 0)) * 100) / 100; }
const selfEvents = mineSince(o, since).filter(r => r.self).length;
return { rows: unified(o, d).rows, byCampaign, selfEvents, days: d };
}
function adminCounts() { const a = refresh().rows; return { rows: a.length, counted: a.filter(r => !r.self).length }; }
module.exports = { init, record, fromLinkSpin, unified, partner, syncMirror, adminCounts, EVENTS };
+1 -1
View File
@@ -133,7 +133,7 @@ async function test(owner, id) {
// a conversion happened for an account: find the click that brought them, record it on the rotator, fire the owner's postbacks
async function convertFor(email, event, facts) {
const c = clickOf(email); if (!c) return null;
const hit = rotator && rotator.convert ? await rotator.convert(c.lsid, event, facts || {}) : null;
const hit = rotator && rotator.convert ? await rotator.convert(c.lsid, event, Object.assign({}, facts || {}, { email: norm(email) })) : null;
if (!hit) return null;
const ctx = Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: c.lsid, code: hit.code, sourceId: hit.sourceId || '' }, facts || {});
try { await fire(hit.owner, event, ctx); } catch (e) {}
+1 -1
View File
@@ -13,7 +13,7 @@
ledger: { eyebrow: 'No back office', h: 'No back office. <em>No payday.</em>', lead: 'Your last program paid you on the 15th, if it paid you. Here every payout is a public transaction on Polygon you can read yourself, and the contract holds zero balance.', points: ['Every payout is public. Click it, read it, verify it.', 'The contract has no pause button and no owner power over money.', 'Join free by email. The ledger is one click from your dashboard.'], cta: 'Check the ledger yourself, then decide', sub: 'free account by email' },
two: { eyebrow: 'The referral side, exactly as coded', h: 'Two buyers open <em>level two.</em>', lead: 'Every direct buyer pays you half of their package from their very first purchase. Two qualifying buyers open level two at 20 percent. Five open level three at 10 percent. Constants in a verified contract.', points: ['Half of every direct purchase, instantly.', 'Level 2 at two qualifying buyers, level 3 at five.', 'Your invite link is live the moment you are in.'], cta: 'Start your line. Two buyers is the target.', sub: 'free account by email' },
links: { video: 'links', eyebrow: 'One link, every page you promote', h: 'Stop <em>juggling links.</em>', lead: 'One short link stands in for all of yours. Behind it, the pages you promote, served in turn by the weights you set, with hours, caps and a fallback. The link never changes, so every copy out in the world keeps working.', points: ['Weights, hours of the day, daily caps, a fallback.', 'A report by source, country and device; your tracker click id filled in.', 'Free. Try a spin on the home page with no account.'], cta: 'Make your first spin link', sub: 'free account by email' },
pages: { video: 'pages', eyebrow: 'Bridge pages in a minute', h: 'Point it at any offer. <em>Get a page.</em>', lead: 'Paste the address of the offer you promote. LinkSpin reads its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on a clean pages domain. Leads are yours.', points: ['Bridge, review or squeeze. Your colours, a niche hero image.', 'Leads to your own list: CSV or webhook.', 'Put the page behind your spin link and send traffic by weight.'], cta: 'Scan an offer you already promote', sub: 'free account by email' },
pages: { video: 'pages', eyebrow: 'Bridge pages in a minute', h: 'Point it at any offer. <em>Get a page.</em>', lead: 'Paste the address of the offer you promote. LinkSpin reads its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on a clean pages domain. Leads are yours.', points: ['Bridge, review or squeeze. Your colours, a niche hero image.', 'Leads to your own list with a CSV download, or paste your autoresponder form.', 'Put the page behind your spin link and send traffic by weight.'], cta: 'Scan an offer you already promote', sub: 'free account by email' },
zones: { video: 'zones', eyebrow: 'Your site pays you', h: 'One script tag. <em>Ad credits for every viewable view.</em>', lead: 'A zone is an ad slot on your own site in any of nine sizes. Member campaigns show first, then network ads, then a house banner. Viewable impressions pay you ad credits you spend on your own campaigns.', points: ['Viewable = half the banner on screen for one second. Bots never count.', 'Paid ads only on the site you declared.', 'Credits spend on your own banner or text campaign.'], cta: 'Add a zone, paste the tag', sub: 'free account by email' },
audiences: { video: 'audiences', eyebrow: 'Retargeting, built in', h: 'Reach your own visitors <em>again.</em>', lead: 'Everyone who views your pages or your zones is remembered for 30 days in an audience you own. Paste a pixel on any other site you control. Then show a campaign only to them, or never to them.', points: ['My visitors is automatic. Named audiences take one pixel line.', 'Show only to, or never show to, on any banner or text campaign.', 'Honest match: cookie plus a 24-hour fallback, nothing personal stored.'], cta: 'See your audiences', sub: 'free account by email' },
stack: { video: 'stack', eyebrow: 'Three tools, zero dollars', h: 'A rotator, a page builder, an ad slot. <em>Free.</em>', lead: 'Join with just an email and the whole stack is yours: spin links, bridge pages and a zone for your site. View a few ads a day and you earn credits for your first campaign. Buy a package only if you want more.', points: ['No wallet, no card, nothing to install.', 'Spin links, pages and zones never need a package.', 'Packages from $10 when you want more reach.'], cta: 'Start with the free stack', sub: 'type your email, get a code, that is the whole signup' },
+4 -1
View File
@@ -20,6 +20,7 @@
CR.tile({ k: 'Bots dropped', v: fmt(t.bots), series: sb, delta: CR.delta(b1, b0, 'vs prior'), note: t.served ? Math.round(t.bots / (t.served + t.bots) * 100) + '% of hits' : '' }),
CR.tile({ k: 'Joins', v: fmt(t.joins), note: t.unique ? (t.joins / t.unique * 100).toFixed(1) + '% of unique' : '' }),
CR.tile({ k: 'Buyers', v: fmt(t.purchases), hi: true, note: t.joins ? Math.round(t.purchases / t.joins * 100) + '% of joins' : '' }),
CR.tile({ k: 'Goals', v: fmt(t.goals) }),
CR.tile({ k: 'Partner conversions', v: fmt(t.external) }),
// Banner Spin totals beside spin links (2026-10-20)
CR.tile({ k: 'Banner views', v: fmt(((s.bannerSpins || {}).totals || {}).imps), note: ((s.bannerSpins || {}).count || 0) + ' Banner Spin' + (((s.bannerSpins || {}).count || 0) === 1 ? '' : 's') }),
@@ -34,7 +35,9 @@
const hmax = Math.max(1, ...(s.hours || [])); $('hourBars').innerHTML = (s.hours || []).map((n, i) => '<i class="' + (n >= hmax * 0.6 ? '' : 'dim') + '" style="height:' + Math.round(n / hmax * 100) + '%" title="' + i + ':00 UTC · ' + n + '"></i>').join('');
const best = (s.hours || []).map((n, i) => [n, i]).sort((a, b) => b[0] - a[0]).slice(0, 3).filter(x => x[0]).map(x => x[1] + ':00');
$('hourNote').textContent = best.length ? 'Busiest hours (UTC): ' + best.join(', ') + '. Hour rules per link come next.' : 'No clicks yet.';
$('convRows').innerHTML = kv(s.conversions || [], 0);
// one list (2026-11-07): site and network events first, then goals, a value beside anything that has one
const CONV_NAME = { join: 'Joins', lead: 'Leads', wallet: 'Wallets', purchase: 'Purchases', external: 'Partner postbacks' };
$('convRows').innerHTML = kv((s.conversions || []).map(x => ({ k: (CONV_NAME[x.k] || String(x.k).replace(/^goal:\s*/, 'Goal: ')) + (x.value ? ' \u00b7 $' + Number(x.value).toFixed(2) : ''), n: x.n })), 0);
// -- Pages and Zones (2026-10-10): one bar per Central day in the range (empty days are zero), totals, per-item table
const dayBars = (barsId, axisId, rows, f, g, empty) => {
const map = {}; (rows || []).forEach(r => { map[r.day] = r; });
+4 -1
View File
@@ -121,6 +121,7 @@
<li class="f-win"><span class="k">5</span><b>Counted in Conversions</b>Against the ad, spin link, page and source that sent them, with cost per goal.</li>
</ol>
<p class="muted" style="font-size:13px">The id is random. It identifies the click, not the person. Nothing personal is read from your page or sent anywhere. An ad click and the spin-link click it led to count as one click.</p>
<p class="muted" style="font-size:13px"><b>Sending people to LinkSpin or InstantAdPay?</b> Those two count by themselves, with no goal and no pixel. The landing tag adds the click id to your links to either site, also when the address sits inside a redirect link of your own. A spin link or Banner Spin pointed straight at either site carries it too. Then their sign-up, wallet link and each package they buy within 30 days of the click show in <a href="/reports">Reports</a> under Conversions, purchases with their USD price. This is reporting only. It never changes who a sponsor is or what anyone is paid.</p>
</div>
</div>
@@ -227,6 +228,7 @@
<tr><td>Cookie</td><td>Exact, through LinkSpin's own cookie. Some browsers block it.</td></tr>
<tr><td>24 h match</td><td>The same network and browser within a day of the click. A good guess, not proof.</td></tr>
<tr><td>Test / last test</td><td>When your last test conversion arrived. Tests are recorded apart and never counted.</td></tr>
<tr><td>Joins, wallets, purchases</td><td>In Reports, under Conversions, beside your goals. People who came through your click and signed up, linked a wallet or bought a package on LinkSpin or InstantAdPay. A sign-up and a wallet count once per click, every package counts on its own with its USD price, all within 30 days of the click. Your own account is left out.</td></tr>
</tbody>
</table>
<div class="pb" style="border-top:1px solid var(--line)"><p class="muted" style="font-size:13px">Each goal gets its own report: by ad campaign (LinkSpin and InstantAdPay), by spin link, by Banner Spin, by destination page and by traffic source (a source you named under Sources, or else the referring site or ad placement). Press CSV for every conversion with its time in Central time, goal, value, match method, campaign, spin link, page, source, country and device. The counting rules: each goal counts once per click, only within 30 days of a real click, and only for clicks on your own ads, links and Banner Spins. Your own clicks on any of them (made while signed in, or from a browser you sign in from) are kept as tests: the note at the top of "How sure is each count" says how many.</p></div>
@@ -258,7 +260,8 @@
<div><dt>Will the tags slow down or break my page?</dt><dd>No. Both load in the background, never stop your page from showing and do nothing visible. If LinkSpin cannot be reached, your page works exactly as before.</dd></div>
<div><dt>Do I need a separate goal for each link or ad?</dt><dd>No. One goal covers every ad and spin link you own. Each conversion is counted against whichever click sent that visitor.</dd></div>
<div><dt>I advertise on InstantAdPay too. Do I set it up twice?</dt><dd>No. Your InstantAdPay goals are these same goals, held on your LinkSpin account under the same email. One landing tag and one goal pixel count clicks from both sites.</dd></div>
<div><dt>Is any personal data sent?</dt><dd>No. The click id is random. No name or email from your page is read or sent.</dd></div>
<div><dt>Is any personal data sent?</dt><dd>No. The click id is random. No name or email from your page is read or sent. When someone joins InstantAdPay on your click, the two sites match the event to your click server to server, and your reports show counts and values, never who the person is.</dd></div>
<div><dt>Why does a sign-up I sent not show?</dt><dd>The click has to reach the join page. Check that your landing tag is on the page and the link is a real link (a button that only runs a script cannot carry it), and that the visitor opened it from your click within the last 30 days. People who joined before this was switched on on 2026-11-07 cannot be matched afterwards.</dd></div>
</dl>
</div>
</div>
+1
View File
@@ -37,6 +37,7 @@
<div class="two">
<div class="panel">
<h2>Set it up in 3 steps</h2>
<div class="muted" style="margin:2px 0 6px">Goals show here with their cost. <a href="/reports">Reports</a> shows everything in one list: goals, plus joins, wallets and purchases on LinkSpin and InstantAdPay.</div>
<div style="margin:2px 0 6px"><a href="/conversion-tracking" target="_blank" rel="noopener">How to set it up: the step-by-step guide with copy-paste examples (WordPress, page builders, Aweber, GetResponse)</a></div>
<ol class="steps">
<li><b>Landing page:</b> paste the landing tag once, before &lt;/body&gt;. It keeps the click id on your own site for 30 days.</li>
+1 -1
View File
@@ -117,7 +117,7 @@
<article id="pages" class="tile card">
<svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="4" width="16" height="16" rx="2"/><path d="M8 9h8M8 13h6"/></svg>
<h3 class="disp">Pages</h3>
<p>Point us at any offer. We read its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on your link domain. Leads are yours: list, CSV, webhook.</p>
<p>Point us at any offer. We read its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on your link domain. Leads are yours: your own list and a CSV download, or paste your autoresponder form.</p>
<div class="foot-row"><span class="tag t">bridge</span><span class="tag t">review</span><span class="tag t">squeeze</span><span class="tag ok">leads: yours</span></div>
</article>
<article id="zones" class="tile card">
+1 -1
View File
@@ -107,6 +107,6 @@ body.squeeze .card{position:sticky;top:16px}
</div>
</footer>
<script src="/assets/common.js?v=20261107tg"></script>
<script src="/assets/join.js?v=20261009b"></script>
<script src="/assets/join.js?v=20261107nc"></script>
</body>
</html>
+1 -1
View File
@@ -30,7 +30,7 @@
<p>When someone opens one of your spin links or sees a zone on your site, we record the time, the destination chosen, the country, the device type, the referring site and any click id or tracking parameters in the link, plus a daily-salted hash of the visitor that is not reversible to a person. These records power your reports and are kept for the life of the link.</p>
<h2 class="disp">Conversion tracking</h2>
<p>When someone clicks an ad on LinkSpin or InstantAdPay, or a spin link whose owner tracks goals, we give that click a random click id and add it to the address they land on (as <code>lsclk</code>). We keep the click with its time, campaign, country, device type and where it was clicked, plus a one-way hash of the network address and browser that we use only to match a conversion within 24 hours. We do not store the IP address itself.</p>
<p>Advertisers who use our landing tag (<code>t.js</code>) keep that click id on their own website for 30 days, in the browser's local storage and a cookie named <code>ls_clk</code> on their site. When the visitor later reaches the advertiser's thank-you page, the goal pixel (<code>cv.gif</code> or <code>cv.js</code>) tells us the goal was reached for that click id, so the advertiser can see how many of their clicks became, say, subscribers or sales, and what each cost. We also set a cookie named <code>ls.clk</code> on our own domain when an ad is clicked, so the pixel can still match where the advertiser's site has no tag. Nothing personal is read or stored by the tag or the pixel: no names, emails or form contents. A conversion only ever counts for the advertiser who owns the click.</p>
<p>Advertisers who use our landing tag (<code>t.js</code>) keep that click id on their own website for 30 days, in the browser's local storage and a cookie named <code>ls_clk</code> on their site. When the visitor later reaches the advertiser's thank-you page, the goal pixel (<code>cv.gif</code> or <code>cv.js</code>) tells us the goal was reached for that click id, so the advertiser can see how many of their clicks became, say, subscribers or sales, and what each cost. We also set a cookie named <code>ls.clk</code> on our own domain when an ad is clicked, so the pixel can still match where the advertiser's site has no tag. Nothing personal is read or stored by the tag or the pixel: no names, emails or form contents. A conversion only ever counts for the advertiser who owns the click. The tag also adds the click id to links to LinkSpin and InstantAdPay. If you then join InstantAdPay, it keeps the click id with your account and tells LinkSpin about your sign-up, wallet link and package purchases on that click, so the owner of the click sees counts and values in their reports, never who you are.</p>
<h2 class="disp">Leads on your pages</h2>
<p>Email addresses entered on a page you publish belong to you and are shown only to you. We store them so you can download them or forward them to your own autoresponder. Visitors are told on the page who is collecting their email.</p>
<h2 class="disp">What we do not collect</h2>
+2 -2
View File
@@ -42,7 +42,7 @@
<div style="display:grid;gap:16px;align-content:start">
<div class="panel"><h2>Top links</h2><div class="tbl top"><div class="hd"><span>Link</span><span class="r">Unique</span><span class="r">Clicks</span><span class="r">Conv.</span></div><div id="topRows"></div></div></div>
<div class="panel"><h2>Your best hours</h2><div class="bars" id="hourBars" style="grid-template-columns:repeat(24,minmax(0,1fr));height:80px"></div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div><div class="muted" id="hourNote"></div></div>
<div class="panel"><h2>Conversions</h2><div class="kv" id="convRows"></div><div class="muted">Joins, wallets and purchases matched to a click on one of your links, plus anything a partner reported by postback. Your own goals (subscribers, sales) and cost per goal are on <a href="/conversions">Conversions</a>.</div></div>
<div class="panel"><h2>Conversions</h2><div class="kv" id="convRows"></div><div class="muted">Everything your clicks led to, each event once: your goals, plus joins, wallets and package purchases on LinkSpin and InstantAdPay, and anything a partner reported by postback. People count when they arrive on a click of yours, through your landing tag or a spin link pointed straight at either site, within 30 days of the click. Your own account and own clicks are left out. Set up goals and see cost per goal on <a href="/conversions">Conversions</a>.</div></div>
</div>
</div>
<!-- Pages: views, uniques, clicks through and leads on the member's bridge / review / squeeze pages (2026-10-10) -->
@@ -91,6 +91,6 @@
</div>
</div>
<script src="/assets/cr-shell.js?v=20261107tg"></script>
<script src="/assets/reports.js?v=20261020bs3"></script>
<script src="/assets/reports.js?v=20261107nc"></script>
</body>
</html>
+37 -2
View File
@@ -2,7 +2,8 @@
* <script async src="https://linkspin.app/t.js?px=YOUR_PIXEL_ID"></script>
* 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.
* lsid or clickid, and adds it to links that stay on your site. Links to InstantAdPay and LinkSpin carry it too, also inside a
* redirect link of your own, so a sign-up or purchase there is counted on your click. 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 () {
@@ -65,7 +66,41 @@
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) {} }
// links to the network (2026-11-07): a bridge page's button carries the click to InstantAdPay or LinkSpin, which report sign-ups
// and purchases against it. Also inside a redirect link of the member's own (go.example.com/go?u=https%3A%2F%2Finstantadpay.com...):
// only that one parameter is rewritten, every other one keeps its exact encoding. Spin and Banner Spin links are left alone, they
// make their own click. Only LinkSpin's own id shapes travel, never another network's clickid. Done on load, again when the page
// is ready and at the click, so a page script that rewrites its links first or later does not lose it.
var NET = /*ls-net*/["linkspin.app","instantadpay.com","instantadpay.link","ctbgo.com","mylinehq.com"]/*ls-net*/;
var OURS = /^(?:[a-f0-9]{10}|[aik][a-f0-9]{11})$/;
function netUrl(s) {
try { var u = new URL(s); return /^https?:$/.test(u.protocol) && NET.indexOf(u.hostname.toLowerCase().replace(/^www\./, '')) >= 0 && !/^\/(r|c|i)\//.test(u.pathname) ? u : null; } catch (e) { return null; }
}
function carries(u) { for (var i = 0; i < NAMES.length; i++) if (u.searchParams.has(NAMES[i])) return true; return false; }
function addId(s) { var h = s.indexOf('#'), b = h < 0 ? s : s.slice(0, h), t = h < 0 ? '' : s.slice(h); return b + (b.indexOf('?') < 0 ? '?' : /[?&]$/.test(b) ? '' : '&') + 'lsclk=' + encodeURIComponent(id) + t; }
function network(a) {
try {
if (!OURS.test(id) || a.getAttribute('data-ls-skip') != null) return false;
var href = a.href, n = netUrl(href);
if (n) { if (!carries(n)) a.href = addId(href); return true; }
var u = new URL(href); if (!/^https?:$/.test(u.protocol) || !u.search) return false;
var parts = u.search.slice(1).split('&'), found = false, changed = false;
for (var i = 0; i < parts.length; i++) {
var eq = parts[i].indexOf('='); if (eq < 1) continue;
var v; try { v = decodeURIComponent(parts[i].slice(eq + 1).replace(/\+/g, ' ')); } catch (e) { continue; }
var inner = /^https?:/i.test(v) ? netUrl(v) : null; if (!inner) continue;
found = true; if (carries(inner)) continue;
parts[i] = parts[i].slice(0, eq + 1) + encodeURIComponent(addId(v)); changed = true;
}
if (changed) a.href = href.slice(0, href.indexOf('?') + 1) + parts.join('&') + (u.hash || '');
return found;
} catch (e) { return false; }
}
function sweep() { try { var l = document.querySelectorAll('a[href]'); for (var i = 0; i < l.length; i++) network(l[i]); } catch (e) {} }
sweep();
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', sweep);
W.addEventListener('load', sweep);
function onClick(e) { try { var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; if (a && !network(a)) decorate(a); } catch (er) {} }
document.addEventListener('click', onClick, true);
document.addEventListener('auxclick', onClick, true);
} catch (e) { /* never break the member's page */ }
+210
View File
@@ -0,0 +1,210 @@
// Conversion linkage, LinkSpin half (2026-11-07, reporting only). Throwaway data, no production data, nothing leaves the machine.
// 1) unit: netconv.js + convtrack.js + rotator.js on a temp dir: sign-up, wallet, purchases counted once with values; duplicate
// delivery; own account and own browser kept as tests; 30-day window by event time; first account owns the click; an event
// after the hit aged out of the rotator; InstantAdPay ad clicks; goals and events in one list without counting anything twice;
// per-link counts; postbacks once, never for a test.
// 2) two processes on one data dir (a deploy's overlap): the same events raced from both, each counted once, none lost.
// 3) browser (Playwright, if present): the landing tag on another origin decorates links to the network, directly and inside a
// redirect link (Orlando's go?c=...&u=... shape), keeps existing params, leaves other links alone, survives a page script
// that rewrites the link, and a stored id still decorates on a later page. Spin links are left alone.
// node qa/netconv.test.mjs Env: PORT (default 8983), PW
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const PORT = Number(process.env.PORT || 8983);
const DAY = 86400000;
let failed = 0, passed = 0; const out = [];
const check = (ok, what, detail) => { out.push((ok ? 'PASS ' : 'FAIL ') + what + (!ok && detail !== undefined ? ' :: ' + (typeof detail === 'string' ? detail : JSON.stringify(detail)) : '')); if (ok) passed++; else failed++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const rq = (ip, ua) => ({ url: '/r/x', headers: { 'user-agent': ua || 'Mozilla/5.0 UnitUA', 'x-forwarded-for': ip }, socket: {} });
// ---------- 1) unit ----------
const UD = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-unit-'));
const C = require(path.join(site, 'convtrack.js')), R = require(path.join(site, 'rotator.js')), N = require(path.join(site, 'netconv.js')), M = require(path.join(site, 'marks.js'));
M.init({ dataDir: UD });
const fired = [];
const P = { fire: async (o, ev, ctx) => { fired.push({ o, ev, ctx }); return []; } };
const initAll = () => { R.init({ dataDir: UD, ownHosts: () => ['linkspin.app'], wantsClickId: o => C.goalsOf(o).length > 0, isNetworkHost: h => ['instantadpay.com'].includes(h), goalRows: () => C.goalRows() }); C.init({ dataDir: UD, rotator: R, noTimers: true }); N.init({ dataDir: UD, convtrack: C, rotator: R, postbacks: P, marks: M, noTimers: true }); };
initAll();
const OWNER = 'orlando@u.test';
const rot = (await R.create(OWNER, { name: 'Bridge spin' })).rotation;
await R.addDest(OWNER, rot.id, { url: 'https://instantadpay.com/join/opgnetwerk', weight: 1 });
const hit = async ip => { const r = await R.resolve(rot.code, rq(ip)); return { id: r.lsid, url: r.url }; };
const a = await hit('198.51.100.1');
check(new URL(a.url).searchParams.get('lsclk') === a.id, 'a spin link straight at InstantAdPay carries lsclk with no goal set up', a.url);
const ev = (k, ev_, click, email, extra) => Object.assign({ k, ev: ev_, click, email, ts: Date.now() }, extra || {});
let r = await N.record(ev('join:a', 'join', a.id, 'lead1@u.test'));
check(r.result === 'counted', 'sign-up on a spin click counted', r);
check((await N.record(ev('join:a', 'join', a.id, 'lead1@u.test'))).result === 'dup', 'the same sign-up delivered twice counts once');
check((await N.record(ev('join:other-key', 'join', a.id, 'lead1@u.test'))).result === 'dup', 'a second sign-up on one click counts once');
check((await N.record(ev('wallet:a', 'wallet', a.id, 'lead1@u.test'))).result === 'counted', 'wallet link counted');
check((await N.record(ev('purchase:0xa:1', 'purchase', a.id, 'lead1@u.test', { value: 5, tx: '0xa' }))).result === 'counted', 'first purchase counted');
check((await N.record(ev('purchase:0xa:1', 'purchase', a.id, 'lead1@u.test', { value: 5, tx: '0xa' }))).result === 'dup', 'the same purchase delivered twice counts once');
check((await N.record(ev('purchase:0xb:1', 'purchase', a.id, 'lead1@u.test', { value: 20, tx: '0xb' }))).result === 'counted', 'a second package on the same click counts on its own');
let u = N.unified(OWNER, 30);
const row = (U, k) => (U.rows.find(x => x.k === k) || { n: 0, value: 0 });
check(row(u, 'join').n === 1 && row(u, 'wallet').n === 1 && row(u, 'purchase').n === 2 && row(u, 'purchase').value === 25, 'Reports: 1 join, 1 wallet, 2 purchases worth $25.00', u.rows);
check(u.buyers === 1, 'two packages by one click are one buyer', u.buyers);
const link = await R.get(OWNER, rot.id);
check(link.conversions === 4, 'the link shows 4 conversions', link.conversions);
const lst = await R.stats(OWNER, rot.id);
check(lst.conversions.some(x => /^purchase/.test(x.k) && x.n === 2), 'the link stats list both purchases', lst.conversions);
const sum = await R.summary(OWNER, 30);
check(sum.top[0].conv === 4, 'Reports top links: Conv. 4', sum.top[0]);
await N.syncMirror();
check(N.unified(OWNER, 30).rows.find(x => x.k === 'purchase').n === 2 && (await R.get(OWNER, rot.id)).conversions === 4, 'replaying the ledger into the rotator adds nothing');
check(fired.filter(f => f.ev === 'join').length === 1 && fired.filter(f => f.ev === 'purchase').length === 2, 'postbacks fire once per counted event', fired.map(f => f.ev));
check(fired.find(f => f.ev === 'purchase').ctx.payout === 5 && fired.find(f => f.ev === 'purchase').ctx.txid === '0xa', 'the purchase postback carries the value and the tx');
// a LinkSpin site join on the same click stays one join
await R.convert(a.id, 'join', {});
check(N.unified(OWNER, 30).rows.find(x => x.k === 'join').n === 1, 'a LinkSpin join on the same click does not add a second join');
// own account, own browser
const b = await hit('198.51.100.2'); fired.length = 0;
r = await N.record(ev('join:own', 'join', b.id, 'Orlando@U.test'));
check(r.result === 'self', "the click owner's own account is not counted", r);
r = await N.record(ev('purchase:0xself:1', 'purchase', b.id, 'orlando@u.test', { value: 100 }));
check(r.result === 'self' && fired.length === 0, 'its purchases are not counted and fire no postback', r);
const c1 = await hit('198.51.100.3'); const skO = C.softKey(rq('192.0.2.7', 'OwnerUA')); C.noteOwner(OWNER, skO);
check((await N.record(ev('join:ownsk', 'join', c1.id, 'stranger1@u.test', { sk: skO }))).result === 'self', "a sign-up from a browser the owner signs in from is a test");
check((await N.record(ev('purchase:0xownsk:1', 'purchase', c1.id, 'stranger1@u.test', { value: 9 }))).result === 'self', 'and stays one on that click');
const c2 = await hit('198.51.100.4'); C.markSelfClick(c2.id, OWNER, rq('1.1.1.1'), OWNER);
check((await N.record(ev('join:ownclick', 'join', c2.id, 'stranger2@u.test'))).result === 'self', "the owner's own click is a test");
check(row(N.unified(OWNER, 30), 'purchase').value === 25, 'none of that moved the totals');
// window, unknown clicks, first account
const d2 = await hit('198.51.100.6'); const hd2 = R.hitById(d2.id).hit; hd2.ts = Date.now() - 31 * DAY;
check((await N.record(ev('join:late', 'join', d2.id, 'late2@u.test'))).result === 'expired', 'an event more than 30 days after the click does not count');
const d3 = await hit('198.51.100.7'); R.hitById(d3.id).hit.ts = Date.now() - 31 * DAY;
check((await N.record(ev('join:latedelivery', 'join', d3.id, 'late3@u.test', { ts: Date.now() - 2 * DAY }))).result === 'counted', 'the window runs to the event, so a delayed delivery still counts');
check((await N.record(ev('join:nosuch', 'join', 'abcdef0123', 'x@u.test'))).result === 'nomatch', 'an unknown click is refused');
check((await N.record(ev('join:bad', 'nonsense', a.id, 'x@u.test'))).result === 'bad' && (await N.record({ k: 'x' })).result === 'bad', 'bad events are refused');
const e1 = await hit('198.51.100.8');
await N.record(ev('join:first', 'join', e1.id, 'first@u.test'));
check((await N.record(ev('purchase:0xsecond:1', 'purchase', e1.id, 'second@u.test', { value: 5 }))).result === 'other', 'a click belongs to the first account on it');
// the hit ages out of the rotator: later events still count on the link
const f = await hit('198.51.100.9');
await N.record(ev('join:aged', 'join', f.id, 'aged@u.test'));
{ const file = path.join(UD, 'rotator.json'); const db = JSON.parse(fs.readFileSync(file, 'utf8')); db.hits = db.hits.filter(h => h.id !== f.id); fs.writeFileSync(file, JSON.stringify(db)); initAll(); }
check(!R.hitById(f.id), 'the hit is gone from the rotator');
const before = (await R.get(OWNER, rot.id)).conversions;
check((await N.record(ev('purchase:0xaged:1', 'purchase', f.id, 'aged@u.test', { value: 50 }))).result === 'counted', 'a purchase after the hit aged out still counts');
check((await R.get(OWNER, rot.id)).conversions === before + 1, 'and lands on the link');
// InstantAdPay ad click: no rotator, in the ledger, on the campaign
C.importClicks([{ id: 'i0123456789a', camp: 7, cname: 'My ad', owner: 'adv@u.test', ts: Date.now(), sk: '', type: 'banner' }]);
check((await N.record(ev('join:ad', 'join', 'i0123456789a', 'adlead@u.test'))).result === 'counted', 'an InstantAdPay ad click counts');
await N.record(ev('purchase:0xad:1', 'purchase', 'i0123456789a', 'adlead@u.test', { value: 20 }));
const pa = N.partner('adv@u.test', 30);
check(pa.byCampaign[7] && pa.byCampaign[7].join === 1 && pa.byCampaign[7].purchase === 1 && pa.byCampaign[7].value === 20, 'the campaign shows its join and purchase', pa.byCampaign);
check(row(N.unified('adv@u.test', 30), 'purchase').value === 20, 'ad events are in the one list (not in the rotator)');
check((await N.record(ev('join:adown', 'join', 'i0123456789a', 'adv@u.test'))).result !== 'counted', "the ad owner's own account is not counted");
// goals and events in one list; a goal is not an event and nothing is listed twice
const g = C.createGoal(OWNER, { name: 'subscriber', value: '2' }); const px = g.goal.px;
const gh = await hit('198.51.100.10');
const fake = { headers: { 'user-agent': 'GoalUA', 'x-forwarded-for': '198.51.100.11' }, socket: {} };
check(C.record({ px, c: gh.id, m: 'url' }, fake, {}).result === 'counted', 'a goal converts on a spin click');
await N.record(ev('join:gh', 'join', gh.id, 'goalman@u.test'));
const U2 = N.unified(OWNER, 30);
check(row(U2, 'goal:subscriber').n === 1 && row(U2, 'goal:subscriber').value === 2, 'goals are in the one list with their value', U2.rows);
const before2 = (await R.get(OWNER, rot.id));
check(before2.conversions >= 2 && before2.convBy['goal: subscriber'] === 1, 'per-link counts include goals', before2.convBy);
const s2 = await R.summary(OWNER, 30);
check(s2.conversions.filter(x => x.k === 'goal: subscriber').length === 1, 'and the top-links count sees it once');
// ---------- 2) two processes, one data dir ----------
{
const worker = path.join(UD, 'worker.cjs'); const DD = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-race-'));
fs.writeFileSync(worker, `
const path = require('path'); const site = ${JSON.stringify(site)}; const DD = ${JSON.stringify(DD)};
const C = require(path.join(site, 'convtrack.js')), R = require(path.join(site, 'rotator.js')), N = require(path.join(site, 'netconv.js')), M = require(path.join(site, 'marks.js'));
M.init({ dataDir: DD }); R.init({ dataDir: DD, ownHosts: () => [] }); C.init({ dataDir: DD, rotator: R, noTimers: true }); N.init({ dataDir: DD, convtrack: C, rotator: R, marks: M, noTimers: true });
(async () => { const until = Number(process.argv[2]); while (Date.now() < until) await new Promise(r => setTimeout(r, 5));
const out = []; for (let i = 0; i < 40; i++) out.push((await N.record({ k: 'purchase:0xrace:' + i, ev: 'purchase', click: 'abcdef0123', email: 'race@u.test', value: 1, ts: Date.now() })).result);
out.push((await N.record({ k: 'join:race', ev: 'join', click: 'abcdef0123', email: 'race@u.test', ts: Date.now() })).result);
process.stdout.write(JSON.stringify(out)); })().catch(e => { process.stdout.write(JSON.stringify({ error: e.message })); }); `);
const seed = { v: 1, rotations: [{ id: 1, owner: 'race-owner@u.test', name: 'r', code: 'raceee', fallback: '', destinations: [], created: Date.now(), paused: false, nextDest: 1 }], hits: [{ id: 'abcdef0123', r: 1, d: 0, ts: Date.now(), v: 'x', c: '', s: 'direct', dv: 'desktop', bot: 0 }], conv: [] };
fs.writeFileSync(path.join(DD, 'rotator.json'), JSON.stringify(seed));
const until = Date.now() + 1200;
const run = () => new Promise(res => { const p = spawn(process.execPath, [worker, String(until)], { stdio: ['ignore', 'pipe', 'inherit'] }); let o = ''; p.stdout.on('data', c => o += c); p.on('close', () => { try { res(JSON.parse(o)); } catch (e) { res({ error: o }); } }); });
const [x, y] = await Promise.all([run(), run()]);
const all = [].concat(x, y);
check(Array.isArray(x) && Array.isArray(y), 'both copies ran', { x, y });
check(all.filter(v => v === 'counted').length === 41, '41 events raced from two copies: exactly 41 counted', all.filter(v => v === 'counted').length);
const rows = fs.readFileSync(path.join(DD, 'netconv.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
check(rows.length === 41 && new Set(rows.map(r => r.k)).size === 41, 'the ledger holds each event once, none lost', rows.length);
}
// ---------- 3) the landing tag in a browser, on another origin ----------
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
if (fs.existsSync(PW)) {
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-b-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'localtest', SITE_HOST: '127.0.0.1:' + PORT });
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_API_KEY', 'OPENROUTER_API_KEY', 'LS_SYNC_SECRET']) delete env[k];
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: 'ignore' });
try {
for (let i = 0; i < 40; i++) { try { const r = await fetch('http://127.0.0.1:' + PORT + '/t.js', { signal: AbortSignal.timeout(2000) }); if (r.ok) break; } catch (e) {} await sleep(500); }
const tag = await (await fetch('http://127.0.0.1:' + PORT + '/t.js')).text();
check(/"instantadpay\.com"/.test(tag) && !tag.includes('/*ls-net*/'), '/t.js is served with the network host list filled in');
const pw = require(PW); const br = await pw.chromium.launch(); const ctx = await br.newContext(); const page = await ctx.newPage();
const errors = []; page.on('pageerror', e => errors.push(e.message));
const BTN = 'https://go.opgnetwerk.test/go?c=bridge-a&u=https%3A%2F%2Finstantadpay.com%2Fjoin%2Fopgnetwerk&keep=a%20b';
const html = `<!doctype html><title>bridge</title><body>
<a id="wrap" class="cta" data-c="x" href="${BTN.replace(/&/g, '&amp;')}">IAP through a redirect</a>
<a id="wrapls" href="https://go.opgnetwerk.test/go?c=b&amp;u=http%3A%2F%2F127.0.0.1%2Fjoin%2Fopgnetwerk">LinkSpin through a redirect</a>
<a id="direct" href="https://instantadpay.com/join/opgnetwerk?v=play#top">direct</a>
<a id="share" href="https://www.instantadpay.link/opgnetwerk">share domain</a>
<a id="has" href="https://instantadpay.com/join/x?lsclk=abcdef0123">already has one</a>
<a id="spin" href="http://127.0.0.1/r/abc123">spin link</a>
<a id="other" href="https://bix.example/?a=1">other site</a>
<a id="wrapother" href="https://go.opgnetwerk.test/go?u=https%3A%2F%2Fbix.example%2F">redirect to another site</a>
<a id="skip" data-ls-skip href="https://instantadpay.com/join/y">opted out</a>
<a id="anchor" href="#sec">anchor</a><a id="late-target" href="/next">next</a>
<script>var s=new URLSearchParams(location.search).get('src');if(s){var a=document.getElementById('wrap'),h=a.getAttribute('href'),q=h.indexOf('?'),p=new URLSearchParams(h.slice(q+1));p.set('c','x-'+s);a.setAttribute('href',h.slice(0,q)+'?'+p.toString());}</script>
<script async src="http://127.0.0.1:${PORT}/t.js?px=px0123456789"></script><script async src="http://127.0.0.1:${PORT}/t.js?px=pxabcdef0123"></script></body>`;
const later = '<!doctype html><title>next</title><body><a id="direct" href="https://instantadpay.com/join/opgnetwerk">x</a><script async src="http://127.0.0.1:' + PORT + '/t.js?px=px0123456789"></script></body>';
const noid = html;
const bridge = http.createServer((q, s) => { s.writeHead(200, { 'Content-Type': 'text/html' }); s.end(new URL(q.url, 'http://x').pathname === '/next' ? later : noid); }).listen(PORT + 1);
const BR = 'http://localhost:' + (PORT + 1);
const ID = 'abc123def0';
await page.goto(BR + '/lp?src=banner&lsclk=' + ID); await sleep(700);
const hrefOf = sel => page.$eval(sel, a => a.href);
const wrap = await hrefOf('#wrap'); const wu = new URL(wrap);
check(new URL(wu.searchParams.get('u')).searchParams.get('lsclk') === ID, "Orlando's redirect link: the click id is inside the u address", wrap);
check(new URL(wu.searchParams.get('u')).pathname === '/join/opgnetwerk' && wu.searchParams.get('c') === 'x-banner', 'the redirect link keeps its address and its other params', wrap);
check(new URL(new URL(await hrefOf('#wrapls')).searchParams.get('u')).searchParams.get('lsclk') === ID, 'the LinkSpin button through the redirect too');
check(await hrefOf('#direct') === 'https://instantadpay.com/join/opgnetwerk?v=play&lsclk=' + ID + '#top', 'a direct link: existing param and #hash stay', await hrefOf('#direct'));
check(new URL(await hrefOf('#share')).searchParams.get('lsclk') === ID, 'share domains are network hosts (www stripped)');
check(await hrefOf('#has') === 'https://instantadpay.com/join/x?lsclk=abcdef0123', 'a link already carrying a click id is left alone');
check(await hrefOf("#spin").then(h => h.split("127.0.0.1")[1]) === "/r/abc123", 'spin links are left alone, they make their own click');
check(await hrefOf('#other') === 'https://bix.example/?a=1' && !/lsclk/.test(await hrefOf('#wrapother')), 'other sites are left alone, redirected or not');
check(await hrefOf('#skip') === 'https://instantadpay.com/join/y', 'data-ls-skip is respected');
await page.click('#late-target'); await sleep(600);
check(new URL(page.url()).searchParams.get('lsclk') === ID, 'same-site links still carry it, as before');
await page.goto(BR + '/next'); await sleep(600);
check(new URL(await hrefOf('#direct')).searchParams.get('lsclk') === ID, 'a later page with no id in the address: the stored id still decorates');
// a foreign clickid is not one of ours: stored as before, never carried to the network
const c2x = await br.newContext(); const p2 = await c2x.newPage();
await p2.goto(BR + '/lp?clickid=foreign12345678'); await sleep(600);
check(await p2.$eval('#direct', a => a.href) === 'https://instantadpay.com/join/opgnetwerk?v=play#top', "another network's clickid never travels to the network");
// no id at all: the page is untouched
const c3x = await br.newContext(); const p3 = await c3x.newPage();
await p3.goto(BR + '/lp'); await sleep(500);
check(await p3.$eval('#direct', a => a.href) === 'https://instantadpay.com/join/opgnetwerk?v=play#top', 'no click id: links untouched');
check(errors.length === 0, 'no page errors', errors);
await br.close(); bridge.close();
} finally { srv.kill(); }
} else out.push('SKIP browser part (no Playwright at ' + PW + ')');
console.log(out.join('\n'));
console.log('\n' + passed + ' passed, ' + failed + ' failed');
process.exit(failed ? 1 : 0);
+4
View File
@@ -7,6 +7,7 @@
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard + carry activation regression
# bash qa/run.sh tankhold # holding tank: network alignment first, plain-activation hold (never a purchase), 24-hour rotation, payouts on at assignment (unit with a mocked clock + fake engine, then a local copy with a mock InstantAdPay)
# bash qa/run.sh netconv # conversion linkage: InstantAdPay's joins, wallets, purchases counted once, own account left out, window, aged hits, two copies racing, one Reports list, the landing tag on network links
# bash qa/run.sh lsid # page-builder lead -> rotator conversion + postback, audience pixel events and cookieless hits
# bash qa/run.sh convpixel # conversion pixel: ad click ids, landing tag + goal pixel (url/stored/cookie/soft), dedupe, window, owner check, cost per goal, IAP partner calls, browser + framed
# bash qa/run.sh nas # Network Ad Space billing: stop snapshot, active-only reconcile, restart without phantom delivery, the 1/N network + partner-zone rate (stubbed NAS, throwaway data)
@@ -67,6 +68,7 @@ elif [ "$MODE" = "member" ]; then
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
node qa/tank-hold.test.mjs || status=1
node qa/profile-policy.test.cjs || status=1
node qa/netconv.test.mjs || status=1
elif [ "$MODE" = "policy" ]; then
node qa/profile-policy.test.cjs || status=1
elif [ "$MODE" = "sponsorfollow" ]; then
@@ -83,6 +85,8 @@ elif [ "$MODE" = "loginqueue" ]; then
node qa/loginqueue.e2e.mjs || status=1
elif [ "$MODE" = "convpixel" ]; then
node qa/convpixel.test.mjs || status=1
elif [ "$MODE" = "netconv" ]; then
node qa/netconv.test.mjs || status=1
elif [ "$MODE" = "lsid" ]; then
node qa/lsid-pixel.test.mjs || status=1
elif [ "$MODE" = "kb" ]; then
+19 -9
View File
@@ -13,6 +13,7 @@ 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=
let IS_NETWORK = () => false, GOAL_ROWS = () => []; // 2026-11-07: a page on a network host always gets the click id (InstantAdPay reports joins, wallets, purchases against it); goal conversions as rotator-shaped rows for per-link counts
const DAY = 86400000;
const J = {
db: null,
@@ -20,7 +21,8 @@ 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; if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; 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; if (opts.isNetworkHost) IS_NETWORK = opts.isNetworkHost; if (opts.goalRows) GOAL_ROWS = opts.goalRows; J.load(); }
const convOf = (rid) => J.db.conv.filter(c => c.r === rid).concat(GOAL_ROWS().filter(c => c.r === rid)); // a link's conversions: site and network events, and goals
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;
@@ -83,7 +85,7 @@ function pub(r) {
const since7 = Date.now() - 7 * DAY;
const perDest = {};
for (const h of hits) { const d = perDest[h.d] = perDest[h.d] || { hits: 0, hits7: 0, uniques: new Set() }; d.hits++; if (h.ts >= since7) d.hits7++; d.uniques.add(h.v); }
const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
const conv = convOf(r.id); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
const since30 = Date.now() - 30 * DAY;
return { id: r.id, code: r.code, name: r.name, owner: r.owner, created: r.created, fallback: r.fallback || '', paused: !!r.paused, conversions: conv.length, convBy,
hours: r.hours || null, tz: r.tz || 'visitor', offHours30: hits.filter(h => h.oh && h.ts >= since30 && !h.bot).length, fallbackHealth: r.fallbackHealth || null, sourceId: r.sourceId || '',
@@ -191,19 +193,27 @@ async function resolve(code, req) {
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) {} }
if (!bot) { try { const t = new URL(out); if ((ac || WANTS_CLICK_ID(r.owner) || IS_NETWORK(t.hostname)) && !t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {} }
}
return { url: out, dest: d, rotation: r, lsid: id };
}
// conversions: record an event against the click that brought the person (dedupe per click + event)
// Banner Spin clicks (bannerspin.js, 2026-10-18) carry their own click ids ('k' + 11 hex); an id we do not know is handed to it
let EXT_CONVERT = null; function setExternalConvert(fn) { EXT_CONVERT = fn; }
// facts.key (netconv.js, 2026-11-07): every purchase InstantAdPay reports counts by its own key, not once per click; facts.bound =
// the click as first recorded, so an event still lands on its link after the hit aged out of the array
async function convert(lsid, ev, facts) {
const h = J.db.hits.find(x => x.id === String(lsid)); if (!h) return EXT_CONVERT ? EXT_CONVERT(lsid, ev, facts) : null;
const f = facts || {}; const key = f.key ? String(f.key) : ''; const id = String(lsid);
let h = J.db.hits.find(x => x.id === id);
if (!h && f.bound && f.bound.r) h = { id, r: f.bound.r, d: f.bound.d, sr: f.bound.sr };
if (!h) return EXT_CONVERT ? EXT_CONVERT(lsid, ev, facts) : null;
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
if (!J.db.conv.some(c => c.lsid === h.id && c.ev === ev)) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: h.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
const dup = J.db.conv.some(c => key && ev === 'purchase' ? c.key === key : (c.lsid === h.id && c.ev === ev && (ev !== 'purchase' || !c.key)));
if (!dup) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Number(f.ts) || Date.now(), value: Number(f.payout || 0) || 0, label: f.label ? String(f.label).slice(0, 40) : undefined, sr: h.sr || undefined, key: key || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
return { owner: r.owner, code: r.code, rotationId: r.id, q: h.q || {}, s: h.s, c: h.c, dv: h.dv, sourceId: h.sr || '' };
}
// a member's conversions as rows (Reports' one Conversions panel, netconv.unified): goals are added there, never here
function convRows(owner, since) { const ids = new Set(J.db.rotations.filter(r => r.owner === norm(owner)).map(r => r.id)); return J.db.conv.filter(c => ids.has(c.r) && c.ts >= since); }
// clicks, uniques and conversions per traffic source over `days` (non-bot), keyed by source id; for the Sources screen and Reports
async function sourceCounts(owner, days) {
const mine = J.db.rotations.filter(r => r.owner === norm(owner)); const ids = new Set(mine.map(r => r.id));
@@ -211,7 +221,7 @@ async function sourceCounts(owner, days) {
const at = sid => (out[sid] = out[sid] || { hits: 0, unique: new Set(), conv: 0, links: 0 });
for (const r of mine) if (r.sourceId) at(r.sourceId).links++;
for (const h of J.db.hits) if (h.sr && ids.has(h.r) && h.ts >= since && !h.bot) { const o = at(h.sr); o.hits++; o.unique.add(h.v); }
for (const c of J.db.conv) if (c.sr && ids.has(c.r) && c.ts >= since) at(c.sr).conv++;
for (const c of J.db.conv.concat(GOAL_ROWS())) if (c.sr && ids.has(c.r) && c.ts >= since) at(c.sr).conv++;
for (const k in out) out[k].unique = out[k].unique.size;
return out;
}
@@ -229,7 +239,7 @@ async function summary(owner, days) {
const dayMap = {}; for (const h of all) { const k = ctDay(h.ts); const d = dayMap[k] = dayMap[k] || { day: k, u: new Set(), b: 0 }; if (h.bot) d.b++; else d.u.add(h.v); }
const dlist = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1).map(d => ({ day: d.day, u: d.u.size, b: d.b }));
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
const conv = J.db.conv.filter(c => ids.has(c.r) && c.ts >= since); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
const conv = J.db.conv.concat(GOAL_ROWS()).filter(c => ids.has(c.r) && c.ts >= since); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
const top = mine.map(r => { const hs = hits.filter(h => h.r === r.id); return { id: r.id, name: r.name, code: r.code, hits: hs.length, unique: new Set(hs.map(h => h.v)).size, conv: conv.filter(c => c.r === r.id).length }; }).sort((a, b) => b.unique - a.unique).slice(0, 10);
// traffic sources (2026-10-12): per source, and per placement = the value the network's zone / placement / site macro carried
const meta = SOURCES && SOURCES.meta ? SOURCES.meta(owner) : {};
@@ -249,7 +259,7 @@ async function stats(owner, id) {
const days = {}; for (const h of hits) { const k = new Date(h.ts).toISOString().slice(0, 10); days[k] = (days[k] || 0) + 1; }
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
const subs = {}; for (const h of hits) if (h.q) for (const [k, v] of Object.entries(h.q)) { const key = k + '=' + v; subs[key] = (subs[key] || 0) + 1; }
const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
const conv = convOf(r.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
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 })) };
}
@@ -322,5 +332,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, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24,
module.exports = { init, convRows, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24,
pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource };
+16 -7
View File
@@ -65,6 +65,7 @@ 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 netconv = require('./netconv'); // network conversions: InstantAdPay's joins, wallets, purchases counted for the click's owner, reporting only (2026-11-07)
const marks = require('./marks'); // one-time claims shared by both app copies during a deploy (event_marks or exclusive files), 2026-10-24
const refill = require('./refill');
const refuel = require('./refuel');
@@ -706,7 +707,7 @@ 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, wantsClickId: owner => convtrack.goalsOf(owner).length > 0 });
rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources, wantsClickId: owner => convtrack.goalsOf(owner).length > 0, isNetworkHost: h => networkHosts().includes(String(h || '').toLowerCase().replace(/^www\./, '')), goalRows: () => convtrack.goalRows() });
convtrack.init({ dataDir: DATA_DIR, rotator, bannerspin, campaignOf: id => ads.campaignById(id) });
auth.onSeen((email, req) => convtrack.noteSession(email, req)); // own-click tests (2026-10-26): the soft keys a member signs in from
// 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)
@@ -715,8 +716,9 @@ async function boot() {
setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000);
setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources });
bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts, wantsClickId: owner => convtrack.goalsOf(owner).length > 0, withClickId: convtrack.withClickId });
rotator.setExternalConvert((lsid, ev, facts) => bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks
bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts, wantsClickId: (owner, url) => { if (convtrack.goalsOf(owner).length > 0) return true; try { return networkHosts().includes(new URL(url).hostname.toLowerCase().replace(/^www\./, '')); } catch (e) { return false; } }, withClickId: convtrack.withClickId });
rotator.setExternalConvert((lsid, ev, facts) => /^[ai]/.test(String(lsid)) ? netconv.fromLinkSpin(lsid, ev, facts) : bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks; ad clicks through the ledger
netconv.init({ dataDir: DATA_DIR, convtrack, rotator, bannerspin, postbacks, marks });
sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } });
zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST });
pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } });
@@ -881,6 +883,9 @@ function readRaw(req, maxBytes) {
// 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 ''; } }
// the sites of the network a click id may travel to (the landing tag's list, 2026-11-07): this site, InstantAdPay, its share domains
const NETWORK_HOSTS = String(process.env.NETWORK_HOSTS || 'instantadpay.com,instantadpay.link,ctbgo.com,mylinehq.com').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
function networkHosts() { return [...new Set([String(SITE_HOST || '').toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '')].concat(NETWORK_HOSTS))].filter(Boolean); }
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=<id> 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.
@@ -1434,7 +1439,7 @@ const server = http.createServer(async (req, res) => {
// -- 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(); }
try { let body = fs.readFileSync(path.join(PUBLIC_DIR, p.slice(1))); if (p === '/t.js') body = String(body).replace(/\/\*ls-net\*\/.*?\/\*ls-net\*\//, JSON.stringify(networkHosts())); 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' };
@@ -1570,7 +1575,7 @@ const server = http.createServer(async (req, res) => {
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit
const set = [];
set.push('iap.sponsor=' + tok + cookieTail); // last touch wins
{ const lsid = String(u.searchParams.get('lsid') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution)
{ const lsid = String(u.searchParams.get('lsid') || u.searchParams.get('lsclk') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution); lsclk is what the landing tag carries from a bridge page (2026-11-07)
const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup
if (ang) set.push('iap.angle=' + angle + cookieTail);
if (!cookies['iap.ref']) set.push('iap.ref=' + encodeURIComponent(coach.refHost(req.headers.referer)) + cookieTail); // first-touch source
@@ -2850,7 +2855,9 @@ const server = http.createServer(async (req, res) => {
const [spins, pg, zn] = await Promise.all([rotator.summary(s.email, days), pages.summary(s.email, days), zonereport.summary(s.email, days)]);
// Banner Spins beside spin links (phase 3, 2026-10-20)
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' });
// one Conversions panel (2026-11-07): site + network events and goals, each once; the tiles follow the same counts
const uni = netconv.unified(s.email, days);
return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, bannerSpins: bsum, days: spins.days, range: days, conversions: uni.rows, totals: Object.assign({}, spins.totals, { joins: uni.joins, wallets: uni.wallets, purchases: uni.buyers, purchaseCount: uni.purchases, goals: uni.goals }) }), { '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')) {
@@ -2992,9 +2999,11 @@ const server = http.createServer(async (req, res) => {
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();
// InstantAdPay's sign-ups, wallet links and purchases on a LinkSpin click (2026-11-07, reporting only): one answer per event
if (b.op === 'events') { const results = []; for (const ev of (Array.isArray(b.events) ? b.events.slice(0, 200) : [])) { let r = { result: 'bad' }; try { r = await netconv.record(ev); } catch (e) { console.error('netconv', e.message); return json(res, 500, { error: 'not recorded' }); } results.push({ k: String(ev && ev.k || '').slice(0, 120), result: r.result }); } return json(res, 200, { ok: true, results }); }
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 });
if (b.op === 'summary') r = Object.assign(convtrack.partnerSummary(email, b.days), { host: SITE_HOST, network: netconv.partner(email, b.days) });
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 });