Conversion tracking fixes (Marty approved 2026-10-26): own clicks are tests on every click type, Banner Spin straight-to-page clicks carry lsclk

1. Own clicks: a goal owner's own click on ANY click type (LinkSpin/InstantAdPay ads, spin links, Banner Spins) is kept as a test, never counted, never fires a goal postback. Own = ad click flagged self for that owner, a spin-link / Banner Spin click marked at click time (signed in as the owner, or from an owner soft key: markOwnClick in server.js), or the clicking or converting browser's soft key is one the owner signs in from. auth.onSeen notes LinkSpin session soft keys (throttled, kept 31 days in convtrack.json S.own); /api/partner/clicks takes owners [{owner, sk, ts}] from InstantAdPay before the clicks, so IAP members' own browsers are known too. Linked positions share the owner's email. X-LS-Result adds ;self. partnerSummary returns selfTests for the IAP card. Conversions screen copy: test with Send a test conversion and the &test=1 page check, own clicks never count (conversions.js ?v=20261026a).
3. Banner Spin: a click whose target is a direct page (not a /r/ spin link) gets ?lsclk=<k click id> when the owner tracks goals (string insert like lsconv.withClickId: params kept, before #hash, an existing lsclk never replaced). convtrack.lookup resolves k ids through bannerspin.clickById; conversions record k:'bspin' with the Banner Spin, banner, page and source; report By Banner Spin, CSV site 'Banner Spin', postback ctx with its sub ids.
Guides: /conversion-tracking (Banner Spin straight to a page now counted, own clicks on every type are tests, By Banner Spin), /refuel tile. Chatbot CANNED + FACTS, KNOWLEDGE_DATE 2026-10-26.
QA: convpixel 77/77 (new: owner soft keys, own ad/spin/Banner Spin/IAP clicks as tests, stranger still counts, own-browser conversion, withClickId, Banner Spin lsclk + By Banner Spin + spin-link banner untouched, selfTests in the IAP summary, no postback for own clicks); lsid 31/31; fuel all pass (engine.js / engine-room.js / kit.js untouched, byte-identical with InstantAdPay); bannerspin 75/75; member walk 0 bugs; public 0 bugs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-26 06:19:54 -05:00
parent 28192b61e9
commit 98e3ed36d8
10 changed files with 206 additions and 48 deletions
+7 -2
View File
@@ -141,10 +141,15 @@ function sessionCookie(token) {
return `iap.sid=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL / 1000}${IS_PROD ? '; Secure' : ''}`;
}
function clearCookie() { return 'iap.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
// onSeen (2026-10-26): told the email + request of every resolved session (conversion tracking keeps the soft keys a member
// signs in from, so their own clicks count as tests). Never throws into the caller.
let seenFn = null; function onSeen(fn) { seenFn = fn; }
async function fromRequest(req) {
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
if (!m) return null;
return impl().get(decodeURIComponent(m[1]));
const s = await impl().get(decodeURIComponent(m[1]));
if (s && s.email && seenFn) { try { seenFn(s.email, req); } catch (e) {} }
return s;
}
async function refreshMemberId(sess) {
if (!sess) return 0;
@@ -167,4 +172,4 @@ async function logout(req) {
if (s) await impl().drop(s.token);
}
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, refreshMemberId, logout };
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, onSeen, refreshMemberId, logout };
+19 -2
View File
@@ -21,6 +21,8 @@
// reloads count once per minute per banner. Clicks are rows like spin-link clicks, with the usual lsid click id
// ('k' + 11 hex, never valid hex so it can never collide with a rotator id), so joins / wallets / purchases and partner
// postbacks credit the banner (rotator.convert falls through to convert() here), and a traffic source's postback fires.
// Since 2026-10-26 a click that goes straight to a page also gets ?lsclk=<click id> when the owner tracks goals, so the
// conversion pixel (convtrack.js, clickById below) counts goals from Banner Spin banners that skip a spin link.
//
// Access. Members with at least one own package of $25 or more. Starter 2 Banner Spins x 5 banners; Builder (level 2
// open, 2 qualifying buyers) 5 x 15; Leader (level 3 open, 5 qualifying buyers) 10 x 25. Facts come from server.js
@@ -68,10 +70,14 @@ const J = { db: null, FILE: () => path.join(DATA_DIR, 'bannerspin.json'),
const C = { db: { v: 1, d: {} }, FILE: () => path.join(DATA_DIR, 'bannerspin-counts.json'),
read() { try { const x = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); return x && x.d ? x : { v: 1, d: {} }; } catch (e) { return { v: 1, d: {} }; } } };
let PENDING = { d: {} }, DIRTY = false, timer = null, lastPrune = 0;
// conversion pixel (2026-10-26): a click that goes straight to a page (not a spin link) gets ?lsclk=<this click id> when
// the owner tracks goals, the same rule spin links follow. server.js hands in the goal check and convtrack's string insert.
let WANTS_CLICK_ID = () => false, WITH_CLICK_ID = (u) => u;
function init(opts) {
DATA_DIR = opts.dataDir; UPLOADS_DIR = opts.uploadsDir || path.join(DATA_DIR, 'uploads'); rotator = opts.rotator || null; geo = opts.geo || null; SOURCES = opts.sources || null;
OWN_HOSTS = opts.ownHosts || OWN_HOSTS; FACTS = opts.facts || FACTS; ADMIN = norm(opts.adminEmail);
if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; if (opts.withClickId) WITH_CLICK_ID = opts.withClickId;
J.load(); C.db = C.read();
if (opts.schedule !== false) { timer = setInterval(() => { flush(); sweep(); }, FLUSH_MS); if (timer.unref) timer.unref(); }
}
@@ -324,8 +330,19 @@ async function click(code, req, reqHost) {
for (const [k, val] of Object.entries(q)) if (vals[k] == null) vals[k] = val;
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) {} } }
}
return { url, lsid: id, banner: b, matched: m };
return { url, lsid: id, banner: b, matched: m, owner: s.owner };
}
// conversion pixel (2026-10-26): a Banner Spin click by id, with its Banner Spin, banner and where it went
function clickById(id) {
id = String(id || ''); if (!/^k[a-f0-9]{11}$/.test(id)) return null;
const list = J.db.clicks; let c = null; for (let i = list.length - 1; i >= 0; i--) if (list[i].id === id) { c = list[i]; break; }
if (!c) return null;
const s = J.db.spins.find(x => x.id === c.s); if (!s) return null;
const b = c.b ? s.banners.find(x => x.id === c.b) || null : null;
return { click: c, owner: s.owner, spin: { id: s.id, code: s.code, name: s.name || '' }, banner: b ? { id: b.id, label: b.label || '' } : null, destUrl: b && !b.link ? (b.target || '') : (b ? '' : (s.fallback || '')) };
}
// conversions (rotator.convert falls through to here for a 'k' click id): dedupe per click + event
async function convert(lsid, ev, facts) {
@@ -463,4 +480,4 @@ const rawSpins = () => J.db.spins;
const save = () => J.save();
function imageSource(img) { const m = LOCAL_IMG.exec(String(img || '')); return m ? { file: path.join(UPLOADS_DIR, m[1]) } : /^https:\/\//i.test(String(img || '')) ? { url: String(img) } : null; }
const _test = { notes: () => NOTES, flush, vkey, cacheFlag, winnerOf };
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test };
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, clickById, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test };
+3 -3
View File
@@ -25,7 +25,7 @@ let DATA_DIR = null;
let chain = null;
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
const CONTRACT = '0x26Bdc556b94399bEdd69ae3ACA5aA6c54D946e8b';
const KNOWLEDGE_DATE = '2026-10-25'; // the day the CANNED answers and FACTS below were last checked against the site
const KNOWLEDGE_DATE = '2026-10-26'; // the day the CANNED answers and FACTS below were last checked against the site
function init(opts) {
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
@@ -81,7 +81,7 @@ const CANNED = [
a: 'A zone is an ad slot on your own site: one script tag, nine standard sizes (728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50). Each load shows a LinkSpin member campaign first, then a network ad, then our house banner if nothing paid fits. You earn ad credits per viewable impression (half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day): 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, or 1 per 8 on a Verified zone the admin has reviewed. A new zone earns after its first 100 on-site views with at least 40 percent viewable, and paid ads serve only on the site you declared, so copying the tag elsewhere earns nothing. Everything is explained at ' + SITE_URL + '/publishers and you add zones under Zones in your Control Room.' },
{ id: 'conversions', title: 'Conversion tracking (the conversion pixel)', q: ['How do I track sign-ups or sales from my ads?', 'What is the conversion pixel?', 'How do I see cost per lead?', 'How do I set up conversion tracking on WordPress?'], tags: ['conversion pixel', 'goal', 'cost per goal', 'landing tag', 'thank-you page', 'tracking', 'wordpress', 'setup guide'],
re: /(conversion (pixel|tracking)|goal pixel|landing tag|\bt\.js|cv\.(gif|js)|cost per (goal|conversion|lead|sale|sign ?up|subscriber)|track (a |my )?(goal|sale|sign ?up|subscriber|lead)s?|lsclk|thank.?you page|aweber|getresponse)/i,
a: 'The conversion pixel counts what happens after the click: a subscriber, a sale, any goal you name. Open Conversions in your Control Room and add a goal (for example subscriber). Then 1) paste the landing tag once on your landing page, 2) paste the goal pixel on your thank-you page, 3) press Send a test conversion. Every click on your LinkSpin and InstantAdPay ads and your spin links carries a click id (lsclk) the tag keeps on your site, so each goal counts once per click, within 30 days of the click, and only for your own clicks. Reports show conversions and cost per goal by ad campaign, spin link, page and traffic source, plus how each one was matched (from the address, kept by the tag, LinkSpin\'s cookie, or a 24-hour match). If your autoresponder (Aweber, GetResponse) shows its own thank-you page, set its thank-you redirect to a page on your own site that carries the pixel. A postback set to the event goal tells your tracker too. The step-by-step guide, with copy-paste examples for plain HTML, WordPress, page builders and autoresponder thank-you pages, how to read the report and a troubleshooting checklist: https://linkspin.app/conversion-tracking' },
a: 'The conversion pixel counts what happens after the click: a subscriber, a sale, any goal you name. Open Conversions in your Control Room and add a goal (for example subscriber). Then 1) paste the landing tag once on your landing page, 2) paste the goal pixel on your thank-you page, 3) press Send a test conversion (to check your real thank-you page, add &test=1 to its pixel and open the page once; the last test time updates). Every click on your LinkSpin and InstantAdPay ads, your spin links and your Banner Spins (banners that go straight to a page included) carries a click id (lsclk) the tag keeps on your site, so each goal counts once per click, within 30 days of the click, and only for clicks on your own ads and links. Your OWN clicks on your own ads, spin links or Banner Spins are kept as tests and never counted, so test with the button, not by signing up yourself. Reports show conversions and cost per goal by ad campaign, spin link, Banner Spin, page and traffic source, plus how each one was matched (from the address, kept by the tag, LinkSpin\'s cookie, or a 24-hour match). If your autoresponder (Aweber, GetResponse) shows its own thank-you page, set its thank-you redirect to a page on your own site that carries the pixel. A postback set to the event goal tells your tracker too. The step-by-step guide, with copy-paste examples for plain HTML, WordPress, page builders and autoresponder thank-you pages, how to read the report and a troubleshooting checklist: https://linkspin.app/conversion-tracking' },
{ id: 'sources', title: 'Traffic sources and postbacks', q: ['How do I track traffic I buy?', 'How do postbacks work?', 'Can I use PropellerAds or Zeropark?'], tags: ['sources', 'postback', 'paid traffic', 'ad network'],
re: /(traffic ?sources?|postback|macros?|propeller ?ads|zeropark|adsterra|exoclick|hilltop ?ads|rich ?ads|traffic ?stars|pop ?ads|campaign url|buy(ing)? traffic|paid traffic|ad network|s2s)/i,
a: 'Sources, in your Control Room, is for traffic you buy on networks like PropellerAds, Zeropark, Adsterra or ExoClick. Pick the network from the catalog (or define your own), fill in your account details, and the source remembers that network\'s macros and conversion postback. Point a spin link at it and the Share kit gives you the exact campaign URL to paste into the network, macros included. When a click from that source joins, leaves a lead, links a wallet or buys, LinkSpin fires the network\'s own postback with its click id, so the network learns what converts, and Reports breaks clicks and conversions down by source and by the zone or placement the macro carried. The older account-level Postbacks on the Links screen still work for your tracker.' },
@@ -161,7 +161,7 @@ function systemPrompt(kbBlock) {
FACTS:
- LEVEL 4 OVERRIDE (LIVE 2026-10-26, first payout Monday 2026-11-02): company paid, decided off chain, paid on chain. 3% of every LinkSpin package purchase (the POL actually paid) goes to the buyer's 4th upline on the LinkSpin contract sponsor chain if that member's contract buyerCount is 5 or more (qualifying buyer = referral whose first package was $25 or more; same bar as level 3); otherwise it hunts up to the next qualified upline, max 25 hops; company account #1 or nobody qualified = company keeps it; exactly one recipient per purchase. Paid weekly in POL every Monday after 9 AM Central for the previous Monday to Sunday Central week, from a company payer wallet via the contract's award(memberId); shown on the Wallet screen as 'Level 4 override' with a Polygon link. Under 0.01 POL carries to the next week. Purchases from the start date only, no back pay. Funded from the platform's 20%; the contract split is unchanged. Separate from InstantAdPay's override; qualification does not carry between sites. Never promise amounts.
${refuelFact()}- PRODUCT, all free with an email account: SPIN LINKS (the rotator: one short link, /r/<code>, rotates between destinations by weight; pause any destination; a fallback for when all are off; one-hop redirect; every click recorded with day, country, source, device and a daily-salted visitor hash; bots filtered on the server; click ids and sub ids such as clickid, subid, s1 to s4 pass through to the destination; split tests by tagging the same link with different sub ids; a demo spin on the home page needs no account; DAYPARTING is live: a 7x24 hours grid per spin and per destination, time zone by name or the local time of the visitor, presets, and 'my best hours' from the clicks of the member after 200 clicks; automatic HEALTH CHECKS are live: every destination is checked every 30 minutes, a dead or parked one is paused after three failing checks and resumed when it passes twice, the owner is told once, and Check now runs it on demand). PAGES (page builder: scan any offer URL, get a bridge, review or squeeze page; designs, palettes, layouts and niche presets with hero images; leads to the member's own list, CSV or webhook; published on the pages domain lookfirst.page; sales, advertorial and press-release layouts are coming). ZONES (an ad slot on the member's own site: one async script tag, nine sizes 728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50; waterfall = LinkSpin member campaign, then a network ad for 728x90 and 468x60, then the LinkSpin house banner; pays ad credits per VIEWABLE impression, half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day; rates 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, 1 per 8 on a Verified zone; warm-up: a zone earns after its first 100 on-site views with at least 40 percent viewable and goes on hold below that; origin lock: paid ads serve only on the declared site and its subdomains, elsewhere the house banner shows and nothing is earned; up to 50 zones per account; PUBLISHER PROGRAM at /publishers for site owners, tiers Standard (default) and Verified (admin-reviewed site, better network rate)). AUDIENCES (first-party retargeting: "My visitors" collects everyone who viewed the member's pages and zones for 30 days; a pixel tag /p.js for other sites; campaigns can "show only to" or "never show to" an audience; nothing personal stored). PROMO TOOLS at /tools#promo (social posts, text-a-friend, email swipes, banners, objection bank, hook videos; five hook angles with videos: links, pages, zones, audiences, stack; angle links are the invite link plus ?v=). REPORTS (every link in one view, plus Pages, Zones, and since 2026-10-12 Traffic sources and Placements). BLOG at /blog with RSS at /blog/feed.xml. TRAFFIC SOURCES at /sources (2026-10-12): a source is a record of a network the member buys traffic on, created from a catalog of networks (PropellerAds, Zeropark, Adsterra, ExoClick, HilltopAds, TrafficStars, PopAds and more, with each network's macro tokens and conversion postback URL; account-specific slots such as a goal id are filled in at creation) or defined by hand; a spin link is pointed at one source (Share kit on the Links screen, or the Sources screen), and then the Share kit's first row is the exact campaign URL for that network with its macros already in place; when a click that came through that source converts (join, lead, wallet, purchase, or a partner-reported conversion; the member picks which) LinkSpin fires that network's own postback with the network's click id and the payout, server to server, and only the network that sent the click is told; Reports show clicks, uniques and conversions by source and by placement (the value the network's zone, placement, site, campaign, creative, banner or keyword macro carried); up to 30 sources per account, 20 params each; a source with no postback still builds the campaign URL and shows in Reports; the account-level Postbacks list on the Links screen (for the member's own tracker) still works alongside. Knowledge checked on ${KNOWLEDGE_DATE}.
- CONVERSION PIXEL (LIVE 2026-10-23, Control Room > Conversions at ${SITE_URL}/conversions; InstantAdPay members see the same goals under Campaigns > Conversion tracking, held on their LinkSpin account): a member names GOALS (subscriber, sale, any word, optional default value, up to 20); each goal has a PUBLIC pixel id (px + 10 characters) that can only count clicks the member owns. EVERY CLICK GETS AN ID: LinkSpin ad clicks (banner, text, zones) and InstantAdPay ad clicks add lsclk=<click id> to the target address (other params kept); a spin link reached through an ad passes its own id on and inherits the ad as its source; spin links of a member with a goal add lsclk to the destination too. SETUP, 3 steps: 1) the LANDING TAG on the landing page, one line <script async src="https://${SITE_HOST}/t.js?px=PIXEL_ID"></script>, keeps the id on the member's own site 30 days (localStorage + a first-party cookie), fills hidden form fields named lsclk, lsid or clickid and adds the id to links that stay on the same site; 2) the GOAL PIXEL on the thank-you page, an image cv.gif?px=PIXEL_ID&goal=NAME (optional &value=19.95) or the script version cv.js that reads what the tag kept; 3) Send a test conversion (recorded apart, never counted). MATCHING ORDER: the click id in the address, then the id the tag kept, then LinkSpin's own cookie, then a 24-hour match on network + browser (a hash, no IP stored); the method is shown per goal so members see how solid each count is. RULES: each goal counts once per 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 the pixel owner's own clicks, rate limited per pixel and per visitor; the advertiser's own clicks are kept as tests. REPORTS per goal: conversions and cost per goal (the campaign's credits spent / its conversions, in that site's ad credits) by ad campaign (LinkSpin and InstantAdPay), spin link, destination page and traffic source, plus CSV export. POSTBACKS: a postback or traffic source set to the event 'goal' fires for every goal with {event} = the goal name. AUTORESPONDERS: when Aweber, GetResponse or another provider hosts the thank-you page, set its thank-you (success) redirect to the member's own page that carries the pixel; otherwise the pixel still counts through the cookie or the 24-hour match, less surely. The tag and pixel never break the page if LinkSpin cannot be reached and work inside traffic-exchange frames. SETUP GUIDE (public, 2026-10-24): ${SITE_URL}/conversion-tracking (InstantAdPay's copy: https://instantadpay.com/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, the last test time updates, then remove it), what to do without code on the thank-you page (image pixel = cookie or 24-hour match; LinkSpin.goal(pixelId, name) from the page's own code for a pop-up form; postbacks), how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest, a Banner Spin banner pointed straight at a page is not matched: point it at a spin link; a sign-up the member makes through their own spin link counts like anyone's, only their own AD clicks are kept as tests). Send members there for any setup question.
- CONVERSION PIXEL (LIVE 2026-10-23, Control Room > Conversions at ${SITE_URL}/conversions; InstantAdPay members see the same goals under Campaigns > Conversion tracking, held on their LinkSpin account): a member names GOALS (subscriber, sale, any word, optional default value, up to 20); each goal has a PUBLIC pixel id (px + 10 characters) that can only count clicks the member owns. EVERY CLICK GETS AN ID: LinkSpin ad clicks (banner, text, zones) and InstantAdPay ad clicks add lsclk=<click id> to the target address (other params kept); a spin link reached through an ad passes its own id on and inherits the ad as its source; spin links of a member with a goal add lsclk to the destination too, and so do Banner Spin clicks that go straight to a page (since 2026-10-26; a banner pointed at a spin link gets the spin link's id). SETUP, 3 steps: 1) the LANDING TAG on the landing page, one line <script async src="https://${SITE_HOST}/t.js?px=PIXEL_ID"></script>, keeps the id on the member's own site 30 days (localStorage + a first-party cookie), fills hidden form fields named lsclk, lsid or clickid and adds the id to links that stay on the same site; 2) the GOAL PIXEL on the thank-you page, an image cv.gif?px=PIXEL_ID&goal=NAME (optional &value=19.95) or the script version cv.js that reads what the tag kept; 3) Send a test conversion (recorded apart, never counted). MATCHING ORDER: the click id in the address, then the id the tag kept, then LinkSpin's own cookie, then a 24-hour match on network + browser (a hash, no IP stored); the method is shown per goal so members see how solid each count is. RULES: each goal counts once per 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 the pixel owner's own clicks, rate limited per pixel and per visitor. OWN CLICKS (2026-10-26): the goal owner's own click on ANY click type (ads, spin links, Banner Spins) is kept as a test and never counted: a click made while signed in as the owner, or a click or conversion from a browser (network + browser soft key) the owner has signed in from on LinkSpin or InstantAdPay; the Conversions screen says 'N from your own clicks, kept as tests and left out'. To test, use Send a test conversion and the &test=1 page check, never a sign-up of your own. REPORTS per goal: conversions and cost per goal (the campaign's credits spent / its conversions, in that site's ad credits) by ad campaign (LinkSpin and InstantAdPay), spin link, Banner Spin (banners straight to a page), destination page and traffic source, plus CSV export. POSTBACKS: a postback or traffic source set to the event 'goal' fires for every goal with {event} = the goal name. AUTORESPONDERS: when Aweber, GetResponse or another provider hosts the thank-you page, set its thank-you (success) redirect to the member's own page that carries the pixel; otherwise the pixel still counts through the cookie or the 24-hour match, less surely. The tag and pixel never break the page if LinkSpin cannot be reached and work inside traffic-exchange frames. SETUP GUIDE (public, 2026-10-24): ${SITE_URL}/conversion-tracking (InstantAdPay's copy: https://instantadpay.com/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, the last test time updates, then remove it), what to do without code on the thank-you page (image pixel = cookie or 24-hour match; LinkSpin.goal(pixelId, name) from the page's own code for a pop-up form; postbacks), how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest, a Banner Spin banner pointed straight at a page now carries its own click id and counts under By Banner Spin; the member's own clicks on ads, spin links and Banner Spins are all kept as tests). Send members there for any setup question.
- TOOL LIMITS BY TIER (2026-10-21): spin links and pages each: Free (no package) 3, Starter (any package of your own) 10, Builder (level 2 open, 2 qualifying buyers) 50, Leader (level 3 open, 5 qualifying buyers) unlimited (fair use). Each spin link rotates up to 25 destinations at every tier; clicks are unlimited. Nothing already made is ever removed when a cap applies; new ones wait for the upgrade. Banner Spin has its own ladder (Starter 2 x 5, Builder 5 x 15, Leader 10 x 25). Other limits, same for everyone: 50 zones, 20 audiences, 20 postbacks, 5 linked positions.
- BANNER SPIN (LIVE 2026-10-18, reports and health checks 2026-10-20): one image address (/i/<code>.gif on a link domain) and one click address (/c/<code>) that rotate up to 25 banners, each with its own target (any https page or one of the member's spin links), weights 1 to 100, random by weight on every view or one banner per visitor per day, the dayparting grid per Banner Spin and per banner, pause, a fallback page and an optional fallback banner image, and a traffic source so its conversions fire that network's postback. Built on the Links screen (${SITE_URL}/links#b). WHO GETS IT: a free add-on for members with their own package of $25 or more; tiers: Starter 2 Banner Spins x 5 banners, Builder (level 2 open, 2 qualifying buyers) 5 x 15, Leader (level 3 open, 5 qualifying buyers) 10 x 25; dropping below a tier keeps everything serving, it only stops new ones. One size per Banner Spin (468x60, 728x90, 300x250, 125x125, 160x600, 120x600, 336x280, 250x250, 320x50); JPG, PNG or GIF (animated is fine), 150 KB at most, uploads count toward the 10 files a day. EMBEDS: the image + click pair (traffic exchanges, safelists, downline builders), an HTML snippet (own sites, blogs, HTML email), a script tag (writes the banner and its own link, so every click matches exactly) and forum BBCode; every link domain answers every code. MATCHING: with the pair, the server remembers which banner a visitor saw on which page for 15 minutes and sends the click there; an unmatched click goes to the fallback. LIMITS: paid ad networks (Froggy, PropellerAds and the like) copy the image at upload, so it freezes on one banner there; Gmail and some mail apps fetch images through a caching proxy, so email readers mostly see one banner and clicks fall back: use a single-banner Banner Spin for email. REPORTS: per banner and per placement views, unique viewers (daily sample), clicks, CTR, match rate and conversions, by Central day, country and device, bots and server loads shown separately and never counted; a WINNER badge once two or more live banners have 1,000 views each and one leads on click rate (LinkSpin never changes weights by itself); a CACHED flag on a placement that copies banners to its own server; totals also on the Reports screen. HEALTH: every 30 minutes each live banner's image must load as an image of the right size and its target must pass the spin-link checks (dead, parked, slow); three failures in a row pause that banner, two clean passes resume it, the last live banner is never auto-paused, and the status shows on each banner row.
- PACKAGES (priced in dollars, settled in POL at the live rate, 1 credit = 1 cent of ad delivery): $10 door = 1,000 credits, for trying the ads, does NOT count toward qualification; $25 Starter = 2,500; $50 Builder = 5,000; $100 Growth = 10,000; $250 Leader = 25,000; $500 Network = 50,000. Any package of $25 or more makes the buyer a qualifying buyer for their sponsor.
+72 -18
View File
@@ -12,7 +12,9 @@
// 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.
// link's owner), per-pixel and per-IP rate limits. A test conversion is recorded apart and never counted. The goal
// owner's own click (any type: ad, spin link, Banner Spin) is kept as a test, never counted (2026-10-26).
// - Banner Spin clicks ('k' + 11 hex) that go straight to a page carry lsclk too since 2026-10-26 (bannerspin.js).
// Storage: DATA_DIR/convtrack.json (JSON in both modes, like rotator.json / postbacks.json), debounced writes.
'use strict';
const fs = require('fs');
@@ -21,19 +23,20 @@ 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;
let FILE = null, S = null, dirty = false, rotator = null, bannerspin = 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 || {};
S.own = S.own || {}; S.selfIds = S.selfIds || {}; // own-click tests (2026-10-26): soft key -> { owner email: last seen }, click id -> marked at
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;
FILE = path.join(opts.dataDir, 'convtrack.json'); rotator = opts.rotator || null; bannerspin = opts.bannerspin || null; if (opts.campaignOf) campaignOf = opts.campaignOf;
S = null; load();
if (!opts.noTimers) { setInterval(flush, 3000).unref(); setInterval(prune, 3600000).unref(); }
}
@@ -50,6 +53,34 @@ function ipOf(req) { return String(req.headers['x-forwarded-for'] || (req.socket
// 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); }
// ── own clicks are tests, on every click type (Marty approved 2026-10-26) ───────────────────────────────────────
// A member clicking their OWN ad, spin link or Banner Spin and converting is a test, never a count. Known by: the click
// was made while signed in as the owner (ads), or the clicking / converting browser's soft key is one the owner has been
// seen signed in from (LinkSpin sessions, noted by auth.js; InstantAdPay sessions, pushed with its clicks). Linked
// positions sit on the owner's own email, so they are the owner here too. Soft keys kept 31 days (the click window).
const OWN_MS = WINDOW_MS + DAY, ownNoted = new Map();
const isSk = sk => /^s:[a-f0-9]{20}$/.test(String(sk || ''));
function noteOwner(email, sk, ts) {
const e = norm(email); if (!e || e.length > 190 || !isSk(sk)) return false;
const at = Math.min(Number(ts) || Date.now(), Date.now()); const k = e + '|' + sk;
if ((ownNoted.get(k) || 0) > at - 600000) return false; ownNoted.set(k, at); if (ownNoted.size > 20000) ownNoted.clear();
const st = load(); const m = st.own[sk] = st.own[sk] || {};
if (!(m[e] >= at)) m[e] = at;
const keys = Object.keys(m); if (keys.length > 8) { keys.sort((a, b) => m[a] - m[b]); for (const x of keys.slice(0, keys.length - 8)) delete m[x]; }
save(); return true;
}
function noteSession(email, req) { try { return noteOwner(email, softKey(req)); } catch (e) { return false; } }
// InstantAdPay's pushed rows: [{ owner, sk, ts }] (its members' own sessions)
function importOwners(rows) { let n = 0; for (const r of (Array.isArray(rows) ? rows.slice(0, 2000) : [])) if (r && noteOwner(r.owner, r.sk, r.ts)) n++; return n; }
function isOwnerSk(owner, sk) { const m = isSk(sk) && load().own[sk]; const t = m && m[norm(owner)]; return !!(t && Date.now() - t <= OWN_MS); }
// spin-link and Banner Spin clicks: marked when the owner made them (signed in on this host, or from an owner soft key)
function markSelfClick(id, owner, req, sessionEmail) {
if (!isClickId(id) || !owner) return false;
const mine = (sessionEmail && norm(sessionEmail) === norm(owner)) || isOwnerSk(owner, softKey(req));
if (mine) { load().selfIds[id] = Date.now(); save(); }
return !!mine;
}
// ── 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); }
@@ -85,7 +116,7 @@ function recordAdClick(camp, req, extra) {
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) };
c: (extra && extra.country) || '', dv: /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop', pl, self: (extra && extra.self) || isOwnerSk(camp.owner, sk) ? 1 : undefined, target: String(camp.targetUrl || '').slice(0, 300) };
noteSoft(sk, id, camp.owner); trimClicks(); save();
return id;
}
@@ -99,7 +130,7 @@ function importClicks(rows) {
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) };
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 || isOwnerSk(owner, sk) ? 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++;
@@ -116,6 +147,8 @@ function prune() {
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];
for (const k in st.selfIds) if (now - st.selfIds[k] > OWN_MS) delete st.selfIds[k];
for (const k in st.own) { const m = st.own[k]; for (const e in m) if (now - m[e] > OWN_MS) delete m[e]; if (!Object.keys(m).length) delete st.own[k]; }
if (st.conv.length > MAX_CONV) st.conv = st.conv.slice(-Math.floor(MAX_CONV * 0.8));
save(); flush();
}
@@ -126,11 +159,16 @@ function lookup(id) {
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) {
if (rotator && rotator.hitById && id[0] !== 'k') { // spin-link ids are 10 hex, never 'k' (that is Banner Spin's)
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 };
}
// a Banner Spin click ('k' + 11 hex) that went straight to a page (2026-10-26: those now carry lsclk too)
if (bannerspin && bannerspin.clickById && id[0] === 'k') {
const b = bannerspin.clickById(id); if (!b || !b.click || b.click.bot) return null;
return { id, root: id, ts: b.click.ts, owners: [b.owner], bspin: b };
}
return null;
}
@@ -162,22 +200,26 @@ function record(q, req, cookies) {
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 ad = hit.ad, sp = hit.spin, bs = hit.bspin;
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
// the goal owner's own click, on ANY click type (ad, spin link, Banner Spin): kept as a test, never in the counts.
// Own = the ad click was flagged self for this owner, the spin / Banner Spin click was marked at click time, or the
// clicking or converting browser is one the owner has been seen signed in from (2026-10-26).
const self = (ad && ad.self && ad.owner === g.owner) || st.selfIds[hit.id] || st.selfIds[hit.root] || isOwnerSk(g.owner, sk) || (ad && ad.sk && isOwnerSk(g.owner, ad.sk)) ? 1 : undefined;
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,
k: ad ? ad.k : (bs ? 'bspin' : '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 };
bs: bs ? bs.spin.id : undefined, bcode: bs ? bs.spin.code : undefined, bname: bs ? bs.spin.name : undefined, bban: bs && bs.banner ? bs.banner.id : undefined,
dest: sp ? sp.destUrl : (bs ? bs.destUrl : (ad ? ad.target : undefined)), sr: sp ? (sp.hit.sr || undefined) : (bs ? (bs.click.sr || undefined) : undefined), src: sp ? sp.hit.s : (bs ? (bs.click.h || 'direct') : (ad ? ad.pl : undefined)),
c: (sp ? sp.hit.c : (bs ? bs.click.c : ad && ad.c)) || '', dv: (sp ? sp.hit.dv : (bs ? bs.click.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 };
const c = r.conv, sp = r.hit && r.hit.spin, bs = r.hit && r.hit.bspin;
return { q: sp ? (sp.hit.q || {}) : (bs ? (bs.click.q || {}) : {}), source: c.src || '', country: c.c || '', device: c.dv || '', lsid: c.click, code: c.rcode || c.bcode || '', 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) {
@@ -197,11 +239,12 @@ async function report(owner, days, opts) {
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: {} });
const at = (gname) => (byGoal[gname] = byGoal[gname] || { goal: gname, n: 0, value: 0, methods: { url: 0, stored: 0, cookie: 0, soft: 0 }, campaigns: {}, links: {}, banners: {}, 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.bs) { const x = G.banners[c.bs] = G.banners[c.bs] || { id: c.bs, code: c.bcode, name: c.bname || '', 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++; }
}
@@ -222,7 +265,7 @@ async function report(owner, days, opts) {
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 });
links: Object.values(G.links).sort((a, b) => b.n - a.n).slice(0, 15), banners: Object.values(G.banners).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 };
@@ -238,17 +281,28 @@ function partnerSummary(owner, days) {
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 };
const selfTests = st.conv.filter(c => c.owner === o && c.ts >= since && c.self).length; // own clicks, kept as tests (InstantAdPay shows "N from your own clicks")
return { ok: true, goals, byCampaign, methods, selfTests };
}
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(','));
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' : (c.k === 'bspin' ? 'Banner Spin' : 'Spin link')), c.camp || '', c.cname || '', c.rcode || (c.bcode ? 'c/' + c.bcode : ''), c.dest || '', c.src || '', c.c || '', c.dv || '', c.click].map(esc).join(','));
return lines.join('\n') + '\n';
}
// "Send a test conversion" from a screen (InstantAdPay's partner call, or the Control Room when it cannot load the image)
function testGoal(owner, px) { const g = goal(px); if (!g || g.owner !== norm(owner)) return { error: 'No such goal.' }; load().tests[g.px] = Date.now(); save(); flush(); return { ok: true, at: load().tests[g.px] }; }
function adminCounts() { const st = load(); return { goals: Object.keys(st.goals).length, clicks: Object.keys(st.clicks).length, conversions: st.conv.length }; }
module.exports = { countSince, init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS };
// append lsclk=<id> the way InstantAdPay's lsconv.withClickId does: string insert (every existing param keeps its exact
// encoding), before any #hash, an lsclk already there never replaced, a URL that does not parse goes out unchanged
function withClickId(target, id) {
const t = String(target || '');
let u; try { u = new URL(t); } catch (e) { return t; }
if (!/^https?:$/.test(u.protocol) || u.searchParams.has('lsclk') || !isClickId(id)) return t;
const hashAt = t.indexOf('#'); const base = hashAt >= 0 ? t.slice(0, hashAt) : t; const hash = hashAt >= 0 ? t.slice(hashAt) : '';
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 };
+2 -1
View File
@@ -28,7 +28,7 @@
snippets();
const m = D.methods || {}; const tot = METH.reduce((n, [k]) => n + (m[k] || 0), 0);
$('methRows').innerHTML = METH.map(([k, label]) => '<div class="m"><span class="k">' + label + '</span><span class="v">' + fmt(m[k] || 0) + '</span><span class="muted mono" style="font-size:11px">' + (tot ? Math.round((m[k] || 0) / tot * 100) + '%' : '·') + '</span></div>').join('');
$('totalNote').textContent = D.selfTests ? D.selfTests + ' from your own clicks, kept as tests and left out' : '';
$('totalNote').textContent = D.selfTests ? D.selfTests + ' from your own clicks (ads, spin links, Banner Spins), kept as tests and left out' : '';
$('goalReports').innerHTML = (D.byGoal || []).filter(G => G.n || !G.removed).map(G => {
const camp = G.campaigns.length ? G.campaigns.map(c => '<div class="rw"><span>' + esc(c.name || ('Campaign #' + c.id)) + '<span class="muted" style="display:block;font-size:11px">' + esc(c.site) + ' #' + c.id + (c.spentAsOf ? ' · spend as of ' + esc(ago(c.spentAsOf)) : '') + '</span></span><span class="r num">' + (c.spent != null ? fmt(c.spent) + ' cr' : '·') + '</span><span class="r num">' + fmt(c.clicks) + '</span><span class="r num">' + fmt(c.n) + '</span><span class="r num">' + (c.rate != null ? c.rate + '%' : '·') + '</span><span class="r num">' + (c.costPer != null ? fmt(c.costPer) + ' cr' : '·') + '</span></div>').join('') : '<div class="rw"><span class="muted">No ad campaign conversions for this goal yet.</span><span></span><span></span><span></span><span></span><span></span></div>';
const lst = (rows, f) => rows && rows.length ? rows.map(x => '<div class="rw"><span style="overflow-wrap:anywhere">' + f(x) + '</span><span class="r num">' + fmt(x.n) + '</span></div>').join('') : '<div class="rw"><span class="muted">nothing yet</span><span></span></div>';
@@ -37,6 +37,7 @@
+ '<div class="panel"><h2>By ad campaign</h2><div class="tbl camps"><div class="hd"><span>Campaign</span><span class="r">Spent</span><span class="r">Clicks</span><span class="r">Goals</span><span class="r">Rate</span><span class="r">Cost / goal</span></div>' + camp + '</div><div class="muted" style="margin-top:8px">Cost per goal = the credits the campaign has spent so far / its conversions of this goal, in that site\'s ad credits. Clicks and goals are for the range above; spend is the campaign\'s total.</div></div>'
+ '<div class="two"><div class="panel"><h2>By spin link</h2><div class="tbl lst"><div class="hd"><span>Link</span><span class="r">Goals</span></div>' + lst(G.links, x => esc(x.name || x.code) + ' <span class="pill">/r/' + esc(x.code) + '</span>') + '</div></div>'
+ '<div class="panel"><h2>By destination page</h2><div class="tbl lst"><div class="hd"><span>Page</span><span class="r">Goals</span></div>' + lst(G.dests, x => '<span class="mono">' + esc(x.k) + '</span>') + '</div></div></div>'
+ '<div class="panel"><h2>By Banner Spin</h2><div class="tbl lst"><div class="hd"><span>Banner Spin</span><span class="r">Goals</span></div>' + lst(G.banners, x => esc(x.name || x.code) + ' <span class="pill">/c/' + esc(x.code) + '</span>') + '</div><div class="muted" style="margin-top:8px">Banners that point straight at a page. A banner that points at a spin link is counted under that spin link.</div></div>'
+ '<div class="panel"><h2>By traffic source</h2><div class="tbl lst"><div class="hd"><span>Source</span><span class="r">Goals</span></div>' + lst(G.sources, x => esc(x.name)) + '</div><div class="muted" style="margin-top:8px">A named source is one you set up under <a href="/sources">Sources</a>; otherwise it is the referring site or the ad placement.</div></div>';
}).join('');
$('goalRows').querySelectorAll('[data-pick]').forEach(b => b.addEventListener('click', () => { PICK = b.dataset.pick; $('goalPick').value = PICK; snippets(); $('snTag').scrollIntoView({ behavior: 'smooth', block: 'center' }); }));
+7 -7
View File
@@ -130,7 +130,7 @@
<li><div>
<h3>Create a goal</h3>
<p>Open <b>Conversions</b> in your Control Room and press <b>Add a goal</b>. Name it with one word for what you count: <b>subscriber</b>, <b>sale</b>, <b>signup</b> (letters, numbers, - or _, up to 32). The default value is optional, in US dollars, used when the pixel carries none. Up to 20 goals per account.</p>
<p>Each goal gets its own pixel id: <b>px</b> plus 10 letters and numbers. It is public and safe to paste: it can only count clicks that are yours. Once you have a goal, your spin links add the click id to your destinations automatically.</p>
<p>Each goal gets its own pixel id: <b>px</b> plus 10 letters and numbers. It is public and safe to paste: it can only count clicks that are yours. Once you have a goal, your spin links and Banner Spins add the click id to your destinations automatically.</p>
<div class="rg-where"><span class="rg-chip">LinkSpin: Control Room, Conversions</span><span class="rg-chip iap">InstantAdPay: Campaigns, Conversion tracking</span></div>
</div></li>
<li><div>
@@ -150,7 +150,7 @@
<li><div>
<h3>Send a test conversion</h3>
<p>Press <b>Send a test conversion</b> next to the snippets. It loads your real pixel, is recorded apart and never counted, and the goal row shows when the last test arrived. That proves your pixel id works.</p>
<p>To check the pixel on your real thank-you page, add <code class="i">&amp;test=1</code> to the end of the pixel address, open your thank-you page once, then reload Conversions: the last test time updates. Take <code class="i">&amp;test=1</code> back out afterwards. Last, open your own spin link or ad and look at the address bar on your landing page: you should see <code class="i">lsclk=</code> in it.</p>
<p>To check the pixel on your real thank-you page, add <code class="i">&amp;test=1</code> to the end of the pixel address, open your thank-you page once, then reload Conversions: the last test time updates. Take <code class="i">&amp;test=1</code> back out afterwards. Last, open your own spin link, Banner Spin click link or ad and look at the address bar on your landing page: you should see <code class="i">lsclk=</code> in it. That click is yours, so anything you finish after it is kept as a test, never counted.</p>
</div></li>
</ol>
</div>
@@ -218,7 +218,7 @@
<table>
<thead><tr><th>You see</th><th>What it means</th></tr></thead>
<tbody>
<tr><td>Counted</td><td>Goals counted in the range you picked (7, 30 or 90 days), tests and your own ad clicks left out.</td></tr>
<tr><td>Counted</td><td>Goals counted in the range you picked (7, 30 or 90 days), tests and your own clicks (ads, spin links, Banner Spins) left out.</td></tr>
<tr><td>Cost / goal</td><td>The credits the ad campaign has spent so far, divided by its goals of this goal type, in that site's ad credits. Clicks and goals follow the range; spend is the campaign's total, so on an older campaign the figure reads high.</td></tr>
<tr><td>Rate</td><td>Goals divided by the campaign's tracked clicks in the range.</td></tr>
<tr><td>Address</td><td>Surest. The thank-you page's own address still carried the click id.</td></tr>
@@ -228,7 +228,7 @@
<tr><td>Test / last test</td><td>When your last test conversion arrived. Tests are recorded apart and never counted.</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 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 and links. Your own clicks on your own ads, made while signed in, are kept as tests: the note at the top of "How sure is each count" says how many.</p></div>
<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>
</div>
<div class="panel">
@@ -237,13 +237,13 @@
<ul class="cg-check">
<li><b>Is the pixel id right?</b> It is <code class="i">px</code> plus 10 letters and numbers, copied from Snippets. A removed goal's pixel stops counting.</li>
<li><b>Did the test arrive?</b> Press Send a test conversion. If the last test time updates, the goal is live. If the <code class="i">&amp;test=1</code> check on your real page does not update it, the pixel is not on that page or the page strips it.</li>
<li><b>Does the click id reach your page?</b> Open your own spin link or ad: your landing page's address should show <code class="i">lsclk=</code>. If it does not, something between the click and your page (another redirect or a link shortener) is dropping it. Point the link straight at the page with the landing tag.</li>
<li><b>Banner Spin straight to a page?</b> The goal pixel counts ad clicks and spin-link clicks. A Banner Spin banner that points straight at a page is not matched; point the banner at one of your spin links and the spin link carries the click id.</li>
<li><b>Does the click id reach your page?</b> Open your own spin link, Banner Spin or ad: your landing page's address should show <code class="i">lsclk=</code>. If it does not, something between the click and your page (another redirect or a link shortener) is dropping it. Point the link straight at the page with the landing tag.</li>
<li><b>Banner Spin straight to a page?</b> That works too. Once you have a goal, a Banner Spin banner that points straight at a page adds its own click id (<code class="i">lsclk=</code>) to the page address, and its goals show under By Banner Spin. A banner that points at one of your spin links is counted under that spin link.</li>
<li><b>Is the landing tag on the page the click lands on?</b> Exactly that address, not another page of your site.</li>
<li><b>Same domain for both pages?</b> The landing tag keeps the id on one domain. If the landing page is on <code class="i">www.yoursite.com</code> and the thank-you page on <code class="i">yoursite.com</code> (or another site), the script pixel cannot read it and only the cookie or 24-hour match is left.</li>
<li><b>Goal pixel only on the thank-you page?</b> Not in a site-wide footer, not on the landing page.</li>
<li><b>Scripts stripped?</b> Some builders and hosted blogs remove scripts. Use the image version of the goal pixel there.</li>
<li><b>Testing with your own clicks?</b> Your own ad clicks are kept as tests and never show in the counts. A sign-up you finish yourself through your own spin link counts like anyone's, so use the test steps above instead.</li>
<li><b>Testing with your own clicks?</b> Your own clicks on your own ads, spin links and Banner Spins are kept as tests and never show in the counts, whether you are signed in or not on that browser (LinkSpin knows the browsers you sign in from). Use Send a test conversion and the <code class="i">&amp;test=1</code> check above to test.</li>
<li><b>Older than 30 days, or the same click twice?</b> A sign-up more than 30 days after the click does not count, and each click counts once per goal.</li>
</ul>
</div>
+2 -2
View File
@@ -40,7 +40,7 @@
<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>
<li><b>Thank-you page:</b> paste the goal pixel for the goal (the image works anywhere; the script version is surer).</li>
<li><b>Test it:</b> press <b>Send a test conversion</b> below, then click one of your own ads or spin links and finish your own form once.</li>
<li><b>Test it:</b> press <b>Send a test conversion</b> below. To check your real thank-you page, add <span class="mono">&amp;test=1</span> to its pixel, open the page once, and the last test time updates (take it back out afterwards). Your own clicks on your ads, spin links and Banner Spins are kept as tests and never counted, so finishing your own form proves nothing in the counts.</li>
</ol>
<div class="gsel" style="margin-top:12px"><span class="muted">Snippets for</span><select class="field" id="goalPick" style="width:auto;min-width:160px"></select><button class="btn" type="button" id="testBtn">Send a test conversion</button><span class="muted" id="testNote"></span></div>
<div class="snip"><span class="sec">1. Landing tag</span><code class="code mono" id="snTag"></code><div><button class="btn sm" type="button" data-copy="snTag">Copy</button></div></div>
@@ -69,6 +69,6 @@
</div>
</div>
<script src="/assets/cr-shell.js?v=20261025ff"></script>
<script src="/assets/conversions.js?v=20261023a"></script>
<script src="/assets/conversions.js?v=20261026a"></script>
</body>
</html>
+1 -1
View File
@@ -110,7 +110,7 @@
<p style="margin:0;font-size:16px;color:var(--ink-2)">Traffic is what makes an offer work, and traffic stops the day your credits run out. A Banner Spin or spin link that runs for a week and then goes quiet gives people one look. Most people don't act on the first look. They act after they've seen your offer a few times, over days and weeks. Refueling every month keeps your offer in front of people the whole month, not just the week you bought.</p>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,400px),1fr));gap:12px">
<div class="tile" style="display:grid;gap:4px;padding:12px 14px;font-size:14.5px"><b>Steady beats bursts</b><span>One big push, then nothing, means every new visitor sees you once. A monthly refuel keeps your rotation running every day, so the people who saw you last week see you again this week. That repeat exposure is what turns a click into a sign-up.</span></div>
<div class="tile" style="display:grid;gap:4px;padding:12px 14px;font-size:14.5px"><b>Your numbers get useful</b><span>With traffic running all month, Banner Spin reports and conversion tracking collect enough clicks and goals to crown a winner. Next month's fuel goes behind the banner and the page that actually convert.</span></div>
<div class="tile" style="display:grid;gap:4px;padding:12px 14px;font-size:14.5px"><b>Your numbers get useful</b><span>With traffic running all month, Banner Spin reports and conversion tracking collect enough clicks and goals to crown a winner. Once you track a goal, every Banner Spin click carries a click id, banners that go straight to your page included, so goals on a page with your landing tag are counted per Banner Spin. Next month's fuel goes behind the banner and the page that actually convert.</span></div>
<div class="tile" style="display:grid;gap:4px;padding:12px 14px;font-size:14.5px"><b>Fresh creative every month</b><span>The Refuel Kit loads new banners with your name and QR code straight into your Banner Spin, so the same audience sees something new instead of tuning out.</span></div>
<div class="tile" style="display:grid;gap:4px;padding:12px 14px;font-size:14.5px"><b>Each month buys more</b><span>The bonus climbs the longer you keep the streak, so the same package delivers more in month four than in month one. Refuel InstantAdPay too and it climbs faster.</span></div>
</div>
+76 -8
View File
@@ -4,7 +4,9 @@
// campaigns.json): ad click -> click id on the target -> goal pixel counts once with method url / stored / cookie /
// soft; dedupe; owner mismatch refused; spin link reached through an ad inherits the ad; cost per goal; goal postback
// attempted (an .invalid host, nothing leaves the machine); InstantAdPay clicks + summary over the signed partner call;
// self click kept as a test; test conversion; CSV.
// self click kept as a test; test conversion; CSV. 2026-10-26: own clicks are tests on every click type (owner soft
// key from a session, signed-in clicks on spin links and Banner Spins, a goal finished in the owner's browser, InstantAdPay
// owners pushed with the clicks); Banner Spin straight to a page carries lsclk and reports By Banner Spin.
// 3) browser (Playwright, if present): the landing tag on another origin keeps the id, fills a hidden lsclk field and
// decorates same-site links; the script goal pixel on the thank-you page counts with method 'stored', also framed.
// node qa/convpixel.test.mjs (from the site dir; no internet needed) Env: PORT (default 8973), PW
@@ -58,6 +60,27 @@ const DAY = 86400000;
let limited = 0; for (let i = 0; i < 25; i++) if (C.record({ px, c: 'nosuchclick1' }, fake('192.0.2.99'), {}).result === 'limited') limited++;
check(limited === 5, 'per-visitor rate limit: 20 a minute, the rest refused', limited + ' limited');
check(C.record({ px: 'px0000000000', c: id }, fake('192.0.2.98'), {}).result === 'unknown', 'unknown pixel id ignored');
// fix 1 (2026-10-26): own clicks are tests on every click type. The owner is seen signed in from 192.0.2.7 + OwnerUA.
const ownReq = fake('192.0.2.7', 'OwnerUA');
check(C.noteSession('Own@U.test', ownReq) && C.isOwnerSk('own@u.test', C.softKey(ownReq)) && !C.isOwnerSk('else@u.test', C.softKey(ownReq)), 'owner soft key noted from a session (email lowercased), not shared with another owner');
const idOwnSk = C.recordAdClick({ id: 7, owner: 'own@u.test', name: 'Unit ad', type: 'banner', targetUrl: 'https://x.test/' }, ownReq, {});
check(C.lookup(idOwnSk).ad.self === 1, "an ad click from the owner's browser is flagged self even when not signed in");
r = C.record({ px, c: idOwnSk, m: 'url' }, fake('192.0.2.60'), {});
check(r.result === 'counted' && r.conv.self === 1, 'its conversion is kept as a test (self)', JSON.stringify(r.result));
const idStr = C.recordAdClick({ id: 7, owner: 'own@u.test', name: 'Unit ad', type: 'banner', targetUrl: 'https://x.test/' }, fake('192.0.2.61', 'StrangerUA'), {});
r = C.record({ px, c: idStr, m: 'url' }, ownReq, {});
check(r.result === 'counted' && r.conv.self === 1, "a stranger's click converted from the owner's own browser is a test too", JSON.stringify(r.result));
const idStr2 = C.recordAdClick({ id: 7, owner: 'own@u.test', name: 'Unit ad', type: 'banner', targetUrl: 'https://x.test/' }, fake('192.0.2.62', 'StrangerUA'), {});
r = C.record({ px, c: idStr2, m: 'url' }, fake('192.0.2.63', 'StrangerUA'), {});
check(r.result === 'counted' && !r.conv.self, "a stranger's click and conversion still count", JSON.stringify(r.conv && r.conv.self));
const skI = 's:' + 'b'.repeat(20);
check(C.importOwners([{ owner: 'Own@U.test', sk: skI, ts: Date.now() }, { owner: 'x@y.z', sk: 'nope' }]) === 1 && C.isOwnerSk('own@u.test', skI), 'InstantAdPay owner soft keys import (bad rows dropped)');
C.importClicks([{ id: 'i0123456789c', camp: 5, owner: 'own@u.test', ts: Date.now(), sk: skI, self: 0 }]);
check(C.lookup('i0123456789c').ad.self === 1, "an InstantAdPay click from the owner's InstantAdPay browser imports as self");
check(C.markSelfClick('abcdef0123', 'own@u.test', ownReq, '') && C.markSelfClick('abcdef0124', 'own@u.test', fake('192.0.2.64', 'Other'), 'OWN@u.test') && !C.markSelfClick('abcdef0125', 'own@u.test', fake('192.0.2.65', 'Other'), 'else@u.test'), 'spin / Banner Spin clicks marked self by owner soft key or owner session, not by someone else');
// withClickId: the string insert lsconv uses
check(C.withClickId('https://a.test/p?utm=x&q=a%2Cb#top', 'k0123456789a') === 'https://a.test/p?utm=x&q=a%2Cb&lsclk=k0123456789a#top' && C.withClickId('https://a.test/p?lsclk=keep', 'k0123456789a') === 'https://a.test/p?lsclk=keep'
&& C.withClickId('https://a.test', 'k0123456789a') === 'https://a.test?lsclk=k0123456789a' && C.withClickId('not a url', 'k0123456789a') === 'not a url', 'withClickId: params kept byte for byte, before the #hash, an lsclk never replaced, bad URL unchanged');
fs.rmSync(UD, { recursive: true, force: true });
}
@@ -176,26 +199,71 @@ try {
const own = await req('GET', '/api/ads/click/1', { ip: '10.77.0.1', cookie: cA });
const idSelf = lsclkOf(own.headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + idSelf + '&m=url', { ip: '198.18.0.11' });
check(res(r) === 'counted;url', "advertiser's own click still gets an id and is recorded (as a test)", res(r));
check(res(r) === 'counted;url;self', "advertiser's own click still gets an id and is recorded (as a test)", res(r));
// fix 1: the owner's own SPIN LINK click (from the browser they signed in with, no cookie on the link domain) is a test
const ownSpin = await req('GET', '/r/' + rot.code, { ip: '10.77.0.1' });
const idOwnSpin = lsclkOf(ownSpin.headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + idOwnSpin + '&m=url', { ip: '198.18.0.12' });
check(/^[a-f0-9]{10}$/.test(idOwnSpin) && res(r) === 'counted;url;self', "owner's own spin-link click (owner soft key): its conversion is a test, not counted", res(r));
const ownSpin2 = await req('GET', '/r/' + rot.code, { ip: '10.77.0.99', cookie: cA }); // signed in on this host, another network
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + lsclkOf(ownSpin2.headers.location) + '&m=url', { ip: '198.18.0.13' });
check(res(r) === 'counted;url;self', "owner's own spin-link click while signed in: a test", res(r));
// a stranger's spin click converted from the owner's own browser: a test too
const strangerSpin = await req('GET', '/r/' + rot.code, { ip: '203.0.113.28' });
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + lsclkOf(strangerSpin.headers.location) + '&m=url', { ip: '10.77.0.1' });
check(res(r) === 'counted;url;self', "a goal finished in the owner's own browser is a test", res(r));
// fix 3: Banner Spin straight to a page carries lsclk; a stranger's goal counts under By Banner Spin, the owner's own is a test
const AUTH = { Authorization: 'Bearer localtest-cv' };
const gr = await req('POST', '/api/admin/bannerspins', { headers: AUTH, body: { email: A, grant: 'starter' } });
const bsc = await req('POST', '/api/my/bannerspins', { cookie: cA, body: { name: 'Conv QA banners', size: '468x60', fallback: 'https://landing.qa.test/fallback' } });
const BS = bsc.json && bsc.json.spin;
const bb1 = BS && await req('POST', '/api/my/bannerspins/' + BS.id + '/banner', { cookie: cA, body: { image: 'https://img.qa.invalid/b1.png', target: 'https://landing.qa.test/bs?utm_source=bs&q=a%2Cb#form', label: 'Direct', weight: 10 } });
check(gr.status === 200 && BS && BS.code && bb1 && bb1.status === 200, 'Banner Spin set up for the member (starter grant, one banner straight to a page)', [gr.status, bsc.text.slice(0, 120), bb1 && bb1.text.slice(0, 120)].join(' | '));
const bid = bb1 && bb1.json && ((bb1.json.banner && bb1.json.banner.id) || (bb1.json.spin && bb1.json.spin.banners && bb1.json.spin.banners.slice(-1)[0].id)) || 1;
const bk = await req('GET', '/c/' + BS.code + '?x=' + bid, { ip: '203.0.113.50' });
const idBs = lsclkOf(bk.headers.location);
check(bk.status === 302 && /^k[a-f0-9]{11}$/.test(idBs) && bk.headers.location === 'https://landing.qa.test/bs?utm_source=bs&q=a%2Cb&lsclk=' + idBs + '#form', 'Banner Spin click straight to a page: lsclk added, params kept byte for byte, before the #hash', bk.headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + idBs + '&m=stored', { ip: '198.18.0.14' });
check(res(r) === 'counted;stored', 'a goal on the Banner Spin click counts', res(r));
const tagBs = await req('GET', '/t.gif?px=' + PX + '&c=' + idBs, { ip: '198.18.0.15' });
check(res(tagBs) === 'stored', 'the landing tag accepts the Banner Spin click id', res(tagBs));
const bkOwn = await req('GET', '/c/' + BS.code + '?x=' + bid, { ip: '10.77.0.1' });
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + lsclkOf(bkOwn.headers.location) + '&m=url', { ip: '198.18.0.16' });
check(res(r) === 'counted;url;self', "owner's own Banner Spin click: a test, not counted", res(r));
const bb2 = await req('POST', '/api/my/bannerspins/' + BS.id + '/banner', { cookie: cA, body: { image: 'https://img.qa.invalid/b2.png', link: rot.id, label: 'Via spin', weight: 10 } });
const bid2 = bb2.json && ((bb2.json.banner && bb2.json.banner.id) || (bb2.json.spin && bb2.json.spin.banners.slice(-1)[0].id));
const bkSpin = await req('GET', '/c/' + BS.code + '?x=' + bid2, { ip: '203.0.113.51' });
check(bkSpin.status === 302 && /\/r\/[a-z0-9]+$/.test(bkSpin.headers.location || ''), 'a banner pointed at a spin link gets no lsclk of its own (the spin link adds one)', bkSpin.headers.location);
const bkB = await req('GET', '/api/admin/bannerspins', { headers: AUTH });
check(bkB.status === 200, 'admin Banner Spin list still answers');
// the report: counts, methods, cost per goal (campaign 1: 300 credits spent / 4 subscribers = 75)
const rep = (await req('GET', '/api/my/conversions?days=30', { cookie: cA })).json;
const G = rep.byGoal.find(x => x.goal === 'subscriber');
const c1 = G.campaigns.find(c => c.key === 'ls:1'), c3 = G.campaigns.find(c => c.key === 'ls:3'), cI = G.campaigns.find(c => c.key === 'iap:77');
check(G.n === 6, 'report: 6 subscribers counted (4 on campaign 1, 1 via spin link, 1 IAP); self click left out', 'n=' + G.n);
check(G.n === 7, 'report: 7 subscribers counted (4 on campaign 1, 1 via spin link, 1 IAP, 1 Banner Spin); every own click left out (ad, spin link x3, Banner Spin)', 'n=' + G.n);
check(G.banners && G.banners.length === 1 && G.banners[0].code === BS.code && G.banners[0].n === 1, 'by Banner Spin: the straight-to-page banner shows its one goal', JSON.stringify(G.banners));
check(!G.links.some(x => x.n > 1), 'own spin-link clicks are not in the spin-link counts', JSON.stringify(G.links));
check(c1 && c1.n === 4 && c1.spent === 300 && c1.costPer === 75 && c1.clicks === 4, 'cost per goal: 300 credits / 4 = 75 credits, 4 clicks counted (own click left out)', JSON.stringify(c1));
check(c3 && c3.n === 1 && cI && cI.n === 1 && cI.costPer === 200 && cI.site === 'InstantAdPay', 'spin conversion credited to the ad campaign; IAP campaign shows its own cost per goal from the pushed spend', JSON.stringify([c3, cI]));
check(G.links.length === 1 && G.links[0].code === rot.code && G.links[0].n === 1, 'by spin link', JSON.stringify(G.links));
check(G.methods.url === 2 && G.methods.stored === 2 && G.methods.cookie === 1 && G.methods.soft === 1 && rep.selfTests === 1, 'match-method breakdown url 2 / stored 2 / cookie 1 / soft 1, one self test apart', JSON.stringify([G.methods, rep.selfTests]));
check(G.methods.url === 2 && G.methods.stored === 3 && G.methods.cookie === 1 && G.methods.soft === 1 && rep.selfTests === 5, 'match-method breakdown url 2 / stored 3 / cookie 1 / soft 1, five own-click tests apart (ad, spin x3, Banner Spin)', JSON.stringify([G.methods, rep.selfTests]));
check(G.dests.some(d => d.k === 'landing.qa.test/lp') && G.sources.length > 0, 'by destination page and traffic source', JSON.stringify([G.dests, G.sources]).slice(0, 200));
check(rep.goals.find(g => g.px === PX).lastTest > 0 && rep.goals.find(g => g.px === PX).conv === 6, 'goal row shows the last test and the 30-day count');
check(rep.goals.find(g => g.px === PX).lastTest > 0 && rep.goals.find(g => g.px === PX).conv === 7, 'goal row shows the last test and the 30-day count');
const sumSelf = await signed('/api/partner/conv', { op: 'summary', email: A, days: 30 });
check(sumSelf.json && sumSelf.json.selfTests === 5, 'IAP summary carries the own-click test count (selfTests) for the card', JSON.stringify(sumSelf.json && sumSelf.json.selfTests));
const ownI = 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11), skOwnI = 's:' + crypto.randomBytes(10).toString('hex');
const pcOwn = await signed('/api/partner/clicks', { owners: [{ owner: A, sk: skOwnI, ts: Date.now() }], clicks: [{ id: ownI, camp: 77, cname: 'IAP QA banner', type: 'banner', owner: A, ts: Date.now(), sk: skOwnI, self: 0, spent: 200 }] });
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + ownI + '&m=url', { ip: '198.18.0.17' });
check(pcOwn.json && pcOwn.json.owners === 1 && res(r) === 'counted;url;self', "an InstantAdPay click from the owner's InstantAdPay browser (owners pushed with the clicks) is a test", JSON.stringify(pcOwn.json) + ' ' + res(r));
const csv = await req('GET', '/api/my/conversions.csv?days=30', { cookie: cA });
check(csv.status === 200 && /text\/csv/.test(csv.headers['content-type']) && csv.text.trim().split('\n').length === 7, 'CSV export: header + 6 rows', String(csv.text.split('\n').length));
check(csv.status === 200 && /text\/csv/.test(csv.headers['content-type']) && csv.text.trim().split('\n').length === 8 && /,Banner Spin,/.test(csv.text), 'CSV export: header + 7 rows, one from a Banner Spin', String(csv.text.split('\n').length));
const csvB = await req('GET', '/api/my/conversions.csv?days=30', { cookie: await signIn(B, '10.77.0.2') });
check(csvB.text.trim().split('\n').length === 1, "another member's CSV has none of these rows");
// the goal postback was attempted with event = goal name
let plog = []; for (let i = 0; i < 30; i++) { await sleep(500); try { plog = JSON.parse(fs.readFileSync(path.join(DATA, 'postbacks.json'), 'utf8')).log.filter(l => l.event === 'subscriber'); } catch (e) {} if (plog.length >= 6) break; }
check(plog.length >= 6 && plog.every(l => /e=subscriber/.test(l.url)) && plog.some(l => l.lsid === id1), "goal postback fired for the counted conversions, {event} = the goal's name", plog.length + ' attempts ' + (plog[0] ? plog[0].url : ''));
let plog = []; for (let i = 0; i < 30; i++) { await sleep(500); try { plog = JSON.parse(fs.readFileSync(path.join(DATA, 'postbacks.json'), 'utf8')).log.filter(l => l.event === 'subscriber'); } catch (e) {} if (plog.length >= 7) break; }
check(plog.length >= 7 && plog.every(l => /e=subscriber/.test(l.url)) && plog.some(l => l.lsid === id1), "goal postback fired for the counted conversions, {event} = the goal's name", plog.length + ' attempts ' + (plog[0] ? plog[0].url : ''));
check(!plog.some(l => l.lsid === idSelf), "no postback for the advertiser's own click");
check(!plog.some(l => l.lsid === idOwnSpin || l.lsid === lsclkOf(bkOwn.headers.location)) && plog.some(l => l.lsid === idBs), 'no postback for own spin-link / Banner Spin clicks; the Banner Spin goal fired one');
const tjs = await req('GET', '/t.js'), cjs = await req('GET', '/cv.js');
let parses = true; try { new Function(tjs.text); new Function(cjs.text); } catch (e) { parses = false; }
check(tjs.status === 200 && /javascript/.test(tjs.headers['content-type']) && cjs.status === 200 && parses, 'the landing tag and script pixel are served and parse');
+17 -4
View File
@@ -687,14 +687,15 @@ async function boot() {
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 });
convtrack.init({ dataDir: DATA_DIR, rotator, campaignOf: id => ads.campaignById(id) });
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)
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);
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 });
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
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 });
@@ -847,6 +848,15 @@ function clickCookie(id) { return 'ls.clk=' + id + '; Path=/; Max-Age=2592000; '
// 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.
// Never blocks the click: on any failure the visitor goes to the target unchanged.
// a spin-link or Banner Spin click by its owner (signed in here, or from a browser the owner signs in from) is marked so
// a goal it leads to is kept as a test, never counted (2026-10-26). Only for owners who track goals; never blocks the click.
async function markOwnClick(id, owner, req) {
try {
if (!owner || !convtrack.goalsOf(owner).length) return;
let email = ''; if (/(?:^|;\s*)iap\.sid=/.test(req.headers.cookie || '')) { const s = await auth.fromRequest(req); email = (s && s.email) || ''; }
convtrack.markSelfClick(id, owner, req, email);
} catch (e) { console.error('own click mark', e.message); }
}
async function adClickTarget(campOrId, url, req, extra) {
try {
const camp = typeof campOrId === 'object' ? campOrId : await ads.campaignById(campOrId); if (!camp) return { url };
@@ -1234,6 +1244,7 @@ const server = http.createServer(async (req, res) => {
let rm = /^\/r\/([a-z0-9]{4,12})$/i.exec(p);
if (rm && (req.method === 'GET' || req.method === 'HEAD')) {
const hit = await rotator.resolve(rm[1], req);
if (hit && hit.lsid) await markOwnClick(hit.lsid, hit.rotation && hit.rotation.owner, req);
if (hit && hit.url) { res.writeHead(302, { Location: hit.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); }
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone'));
}
@@ -1258,6 +1269,7 @@ const server = http.createServer(async (req, res) => {
res.writeHead(200, Object.assign({}, fresh, { 'Content-Type': 'application/javascript; charset=utf-8' })); return res.end(req.method === 'HEAD' ? '' : js);
}
const ck = await bannerspin.click(bm[2], req, host);
if (ck && ck.lsid) await markOwnClick(ck.lsid, ck.owner, req);
if (ck && ck.url) { res.writeHead(302, { Location: ck.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade', 'X-Robots-Tag': 'noindex' }); return res.end(); }
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(host, 'gone'));
} }
@@ -1284,7 +1296,7 @@ const server = http.createServer(async (req, res) => {
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 : '');
h['X-LS-Result'] = r.result + (r.method ? ';' + r.method : '') + (r.conv && r.conv.self ? ';self' : ''); // ;self = the owner's own click, kept as a test
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'; }
@@ -2760,7 +2772,8 @@ const server = http.createServer(async (req, res) => {
// 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) });
const owners = convtrack.importOwners(sg.body.owners); // InstantAdPay members' own soft keys first, so their own clicks import as tests
return json(res, 200, { ok: true, n: convtrack.importClicks(sg.body.clicks), owners });
}
// -- the Engine Room, partner side: LinkSpin's facts for one member (InstantAdPay builds its panel from them)
if (p === '/api/partner/engine' && req.method === 'POST') {