Compare commits

...

4 Commits

28 changed files with 908 additions and 32 deletions
+5 -1
View File
@@ -73,8 +73,11 @@ const CANNED = [
{ id: 'zones', title: 'Ad zones on your own site', q: ['What is an ad zone?', 'How do I put ads on my website?', 'What sizes are the zones?'], tags: ['zones', 'publisher', 'embed', 'website'],
re: /(what('s| is) (a |an )?(ad )?zone|zones?\b|embed|script tag|publisher|site owner|my (own )?(web)?site|ad slot|viewable)/i,
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?'], tags: ['conversion pixel', 'goal', 'cost per goal', 'landing tag', 'thank-you page', 'tracking'],
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.' },
{ 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|conversion (pixel|tracking))/i,
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.' },
{ id: 'spin-links', title: 'Spin links (the rotator)', q: ['What is a spin link?', 'How do weights and the fallback work?', 'How do I rotate my links?'], tags: ['spin link', 'rotator', 'short link', 'weights'],
re: /(spin ?link|rotat|short link|one link|weights?|fallback|split test|sub ?id|click ?id|daypart|health check|dead link|redirect)/i,
@@ -147,6 +150,7 @@ function systemPrompt(kbBlock) {
FACTS:
- 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.
- 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.
+252
View File
@@ -0,0 +1,252 @@
// Conversion pixel (Marty approved 2026-10-23, "Go with the conversion pixel"). LinkSpin is the single source of truth
// for goals and goal conversions, for its own members AND for InstantAdPay members (their LinkSpin shell account, same
// email, holds the goals; InstantAdPay reads and edits them over the signed partner call).
//
// - Goals: a member names a goal ("subscriber", "sale", optional default value). Each goal has a PUBLIC pixel id
// (px + 10 hex). It is not a secret: it can only ever count conversions for clicks its owner owns.
// - Ad clicks: every LinkSpin ad click (/api/ads/click, zone clicks) gets a click id 'a' + 11 hex; every InstantAdPay
// ad click is pushed here with its own id 'i' + 11 hex (/api/partner/clicks). Spin-link clicks keep the rotator's
// 10-hex lsid; a spin-link click that arrived through an ad carries that ad click as `ac` (rotator.js).
// - Landing tag (/t.js) stores the click id on the member's own site; the goal pixel (/cv.gif, /cv.js) reports it.
// Matching order: the click id in the URL > the landing tag's stored id > LinkSpin's cookie > the 24 h IP+UA soft key.
// The method that matched is kept on the conversion so Reports can say how solid each count is.
// - Rules: each goal counts once per click (per ROOT click: an ad click and the spin-link click it led to are one
// click), only within 30 days of a real click, only for clicks the pixel's owner owns (the ad's owner or the spin
// link's owner), per-pixel and per-IP rate limits. A test conversion is recorded apart and never counted.
// Storage: DATA_DIR/convtrack.json (JSON in both modes, like rotator.json / postbacks.json), debounced writes.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const DAY = 86400000, WINDOW_MS = 30 * DAY, SOFT_MS = 24 * 3600000, MAX_GOALS = 20;
const MAX_CLICKS = 300000, MAX_CONV = 100000;
let FILE = null, S = null, dirty = false, rotator = null, campaignOf = async () => null;
function load() {
if (S) return S;
try { S = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { S = null; }
if (!S || typeof S !== 'object') S = {};
S.v = 1; S.goals = S.goals || {}; S.clicks = S.clicks || {}; S.soft = S.soft || {}; S.conv = Array.isArray(S.conv) ? S.conv : []; S.camps = S.camps || {}; S.tests = S.tests || {};
return S;
}
function save() { dirty = true; }
function flush() { if (!dirty || !S || !FILE) return; dirty = false; try { fs.writeFileSync(FILE + '.tmp', JSON.stringify(S)); fs.renameSync(FILE + '.tmp', FILE); } catch (e) { console.error('convtrack save', e.message); } }
function init(opts) {
FILE = path.join(opts.dataDir, 'convtrack.json'); rotator = opts.rotator || null; if (opts.campaignOf) campaignOf = opts.campaignOf;
S = null; load();
if (!opts.noTimers) { setInterval(flush, 3000).unref(); setInterval(prune, 3600000).unref(); }
}
const norm = e => String(e || '').trim().toLowerCase();
const isPx = v => /^px[a-f0-9]{10}$/.test(String(v || ''));
const isClickId = v => /^[a-z0-9]{6,24}$/i.test(String(v || ''));
const isAdId = v => /^[ai][a-f0-9]{11}$/.test(String(v || ''));
const cleanName = v => { const s = String(v == null ? '' : v).trim().toLowerCase().replace(/\s+/g, '_'); return /^[a-z0-9_-]{1,32}$/.test(s) ? s : ''; };
const cleanValue = v => { if (v === '' || v == null) return 0; const n = Number(v); return Number.isFinite(n) && n >= 0 ? Math.min(Math.round(n * 100) / 100, 100000) : 0; };
const newPx = () => { for (;;) { const id = 'px' + crypto.randomBytes(5).toString('hex'); if (!load().goals[id]) return id; } };
const newAdClickId = () => 'a' + crypto.randomBytes(6).toString('hex').slice(0, 11);
function ipOf(req) { return String(req.headers['x-forwarded-for'] || (req.socket && req.socket.remoteAddress) || '').split(',')[0].trim(); }
// the soft key: InstantAdPay computes exactly the same thing for its ad clicks (contract 2026-10-23)
function softKey(req) { return 's:' + crypto.createHash('sha256').update(ipOf(req) + '|' + String(req.headers['user-agent'] || '')).digest('hex').slice(0, 20); }
// ── goals ───────────────────────────────────────────────────────────────────────────────────────────────────────
function pubGoal(g) { return { px: g.px, name: g.name, value: g.value || 0, created: g.created, lastTest: (load().tests[g.px] || 0) || null }; }
function goalsOf(owner) { const o = norm(owner); return Object.values(load().goals).filter(g => g.owner === o).sort((a, b) => a.created - b.created); }
function goal(px) { return load().goals[String(px || '')] || null; }
function createGoal(owner, body) {
const o = norm(owner); if (!o) return { error: 'Sign in first.' };
const name = cleanName(body && body.name); if (!name) return { error: 'Name the goal with letters, numbers, - or _ (for example subscriber or sale), up to 32.' };
const mine = goalsOf(o);
if (mine.length >= MAX_GOALS) return { error: 'Up to ' + MAX_GOALS + ' goals per account. Remove one first.' };
if (mine.some(g => g.name === name)) return { error: 'You already have a goal called ' + name + '.' };
const g = { px: newPx(), owner: o, name, value: cleanValue(body && body.value), created: Date.now() };
load().goals[g.px] = g; save(); flush(); return { ok: true, goal: pubGoal(g) };
}
function updateGoal(owner, px, body) {
const g = goal(px); if (!g || g.owner !== norm(owner)) return { error: 'No such goal.' };
if (body.remove) { delete load().goals[g.px]; delete load().tests[g.px]; save(); flush(); return { ok: true, removed: true }; } // its past conversions stay in the log (the reports show them under the name)
if (body.name != null) { const n = cleanName(body.name); if (!n) return { error: 'Name the goal with letters, numbers, - or _ , up to 32.' }; if (goalsOf(g.owner).some(x => x.px !== g.px && x.name === n)) return { error: 'You already have a goal called ' + n + '.' }; g.name = n; }
if (body.value != null) g.value = cleanValue(body.value);
save(); flush(); return { ok: true, goal: pubGoal(g) };
}
// ── clicks ──────────────────────────────────────────────────────────────────────────────────────────────────────
function noteSoft(sk, id, owner, ts) {
if (!sk || !/^s:[a-f0-9]{20}$/.test(sk) || !id) return;
const st = load(); const now = ts || Date.now();
const list = (st.soft[sk] || []).filter(x => now - x[1] <= SOFT_MS && x[0] !== id);
list.push([id, now, norm(owner)]); st.soft[sk] = list.slice(-6); save();
}
// a LinkSpin ad click (banner, text, zone). Returns the click id to append to the target.
function recordAdClick(camp, req, extra) {
if (!camp || !camp.id) return null;
const st = load(); const id = newAdClickId(); const ua = String(req.headers['user-agent'] || '');
const sk = softKey(req);
let pl = String((extra && extra.placement) || ''); if (!pl) { try { const r = new URL(String(req.headers.referer || '')); pl = (r.hostname.replace(/^www\./, '') + r.pathname).slice(0, 80); } catch (e) {} }
st.clicks[id] = { id, k: 'ad', camp: Number(camp.id), cname: String(camp.name || camp.title || '').slice(0, 80), type: camp.type || '', owner: norm(camp.owner), ts: Date.now(), sk,
c: (extra && extra.country) || '', dv: /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop', pl, self: extra && extra.self ? 1 : undefined, target: String(camp.targetUrl || '').slice(0, 300) };
noteSoft(sk, id, camp.owner); trimClicks(); save();
return id;
}
// InstantAdPay pushes its ad clicks (signed partner call); an upsert by id, so a row sent twice is harmless
function importClicks(rows) {
const st = load(); let n = 0;
for (const r of (Array.isArray(rows) ? rows.slice(0, 500) : [])) {
const id = String(r && r.id || ''); if (!/^i[a-f0-9]{11}$/.test(id)) continue;
const owner = norm(r.owner); if (!owner || owner.length > 190) continue;
const ts = Number(r.ts) || Date.now(); if (ts > Date.now() + 600000 || Date.now() - ts > WINDOW_MS) continue;
const sk = /^s:[a-f0-9]{20}$/.test(String(r.sk || '')) ? String(r.sk) : '';
const had = !!st.clicks[id];
st.clicks[id] = { id, k: 'iap', camp: Number(r.camp) || 0, cname: String(r.cname || '').slice(0, 80), type: String(r.type || '').slice(0, 12), owner, ts, sk,
c: String(r.c || '').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 2), dv: r.dv === 'mobile' ? 'mobile' : 'desktop', pl: String(r.pl || '').slice(0, 80), self: r.self ? 1 : undefined, target: String(r.target || '').slice(0, 300) };
if (r.camp) { const key = 'iap:' + Number(r.camp); const cur = st.camps[key] || {}; if (!cur.ts || ts >= cur.ts) st.camps[key] = { owner, name: String(r.cname || '').slice(0, 80), spent: Math.max(0, Number(r.spent) || 0), ts }; }
if (!had && sk) noteSoft(sk, id, owner, ts);
n++;
}
if (n) { trimClicks(); save(); }
return n;
}
function trimClicks() {
const st = load(); const keys = Object.keys(st.clicks); if (keys.length <= MAX_CLICKS) return;
keys.sort((a, b) => st.clicks[a].ts - st.clicks[b].ts); for (const k of keys.slice(0, keys.length - Math.floor(MAX_CLICKS * 0.8))) delete st.clicks[k];
}
function prune() {
const st = load(); const now = Date.now();
for (const k in st.clicks) if (now - st.clicks[k].ts > WINDOW_MS + DAY) delete st.clicks[k];
for (const k in st.soft) { const l = st.soft[k].filter(x => now - x[1] <= SOFT_MS); if (l.length) st.soft[k] = l; else delete st.soft[k]; }
for (const k in st.camps) if (now - st.camps[k].ts > 400 * DAY) delete st.camps[k];
if (st.conv.length > MAX_CONV) st.conv = st.conv.slice(-Math.floor(MAX_CONV * 0.8));
save(); flush();
}
// What a click id is, who owns it, where it came from. Spin-link clicks live in rotator.json.
function lookup(id) {
id = String(id || ''); if (!isClickId(id)) return null;
const st = load();
const ad = st.clicks[id];
if (ad) return { id, root: id, ts: ad.ts, owners: [ad.owner], ad };
if (rotator && rotator.hitById) {
const h = rotator.hitById(id); if (!h || !h.hit || h.hit.bot) return null;
const via = h.hit.ac && st.clicks[h.hit.ac] ? st.clicks[h.hit.ac] : null;
return { id, root: via ? via.id : id, ts: via ? Math.min(via.ts, h.hit.ts) : h.hit.ts, owners: [h.owner].concat(via ? [via.owner] : []), ad: via, spin: h };
}
return null;
}
// ── the goal pixel ─────────────────────────────────────────────────────────────────────────────────────────────
const RL = { px: new Map(), ip: new Map() };
function rateOk(map, key, max, ms) { const now = Date.now(); const a = (map.get(key) || []).filter(t => now - t < ms); if (a.length >= max) { map.set(key, a); return false; } a.push(now); map.set(key, a); if (map.size > 50000) map.clear(); return true; }
setInterval(() => { const now = Date.now(); for (const m of [RL.px, RL.ip]) for (const [k, a] of m) if (!a.some(t => now - t < 3600000)) m.delete(k); }, 600000).unref();
const LIMITS = { pxPerMin: 60, pxPerHour: 1000, ipPerMin: 20 };
// q: { px, goal, value, c (click id from the page), m ('url'|'stored', who found it), test }
// cookies: { 'ls.clk', 'ls.click' }. Returns { result, method?, conv? } where result is counted | dup | nomatch | unknown | limited | test | refused
function record(q, req, cookies) {
const g = goal(q.px); if (!g) return { result: 'unknown' };
const sk = softKey(req); const ip = sk; // the soft key doubles as the per-visitor rate key (no raw IP held)
if (!rateOk(RL.ip, ip, LIMITS.ipPerMin, 60000)) return { result: 'limited' };
if (!rateOk(RL.px, g.px + ':m', LIMITS.pxPerMin, 60000) || !rateOk(RL.px, g.px + ':h', LIMITS.pxPerHour, 3600000)) return { result: 'limited' };
if (q.test) { load().tests[g.px] = Date.now(); save(); return { result: 'test', at: load().tests[g.px] }; }
const now = Date.now(); let refused = 0;
const tryId = (id, method) => {
const L = lookup(id); if (!L) return null;
if (!L.owners.includes(g.owner)) { refused++; return null; } // someone else's click: never counted for this pixel
if (now - L.ts > WINDOW_MS) return null;
return Object.assign(L, { method });
};
let hit = null;
if (isClickId(q.c)) hit = tryId(q.c, q.m === 'stored' ? 'stored' : 'url');
if (!hit) for (const ck of ['ls.clk', 'ls.click']) { const v = cookies && cookies[ck]; if (!hit && isClickId(v)) hit = tryId(v, 'cookie'); }
if (!hit) { const list = (load().soft[sk] || []).filter(x => x[2] === g.owner && now - x[1] <= SOFT_MS).sort((a, b) => b[1] - a[1]); for (const x of list) { hit = tryId(x[0], 'soft'); if (hit) break; } }
if (!hit) return { result: refused ? 'refused' : 'nomatch' };
const st = load();
if (st.conv.some(c => c.px === g.px && (c.root === hit.root || c.click === hit.id || c.root === hit.id))) return { result: 'dup', method: hit.method };
const ad = hit.ad, sp = hit.spin;
const value = q.value != null && q.value !== '' ? cleanValue(q.value) : (g.value || 0);
const self = ad && ad.self ? 1 : undefined; // the advertiser's own click: kept as a test, never in the counts
const conv = { id: crypto.randomBytes(6).toString('hex'), ts: now, px: g.px, goal: g.name, owner: g.owner, click: hit.id, root: hit.root, method: hit.method, value,
k: ad ? ad.k : 'spin', camp: ad ? ad.camp : undefined, cname: ad ? ad.cname : undefined, ctype: ad ? ad.type : undefined,
rot: sp ? sp.rotation.id : undefined, rcode: sp ? sp.rotation.code : undefined, rname: sp ? sp.rotation.name : undefined,
dest: sp ? sp.destUrl : (ad ? ad.target : undefined), sr: sp ? (sp.hit.sr || undefined) : undefined, src: sp ? sp.hit.s : (ad ? ad.pl : undefined),
c: (sp ? sp.hit.c : ad && ad.c) || '', dv: (sp ? sp.hit.dv : ad && ad.dv) || '', self };
for (const k of Object.keys(conv)) if (conv[k] === undefined) delete conv[k];
st.conv.push(conv); save();
return { result: 'counted', method: hit.method, conv, hit };
}
// the postback context for a counted conversion (postbacks.fire)
function postbackCtx(r) {
const c = r.conv, sp = r.hit && r.hit.spin;
return { q: sp ? (sp.hit.q || {}) : {}, source: c.src || '', country: c.c || '', device: c.dv || '', lsid: c.click, code: c.rcode || '', sourceId: c.sr || '', payout: c.value || 0, currency: 'USD', label: c.goal };
}
// the landing tag's beacon: it saw a click id on the member's page. Returns the id when it is a real click of the pixel's owner.
function landing(px, id, req) {
const g = goal(px); if (!g || !isClickId(id)) return null;
if (!rateOk(RL.ip, softKey(req) + ':t', 60, 60000)) return null;
const L = lookup(id); if (!L || !L.owners.includes(g.owner) || Date.now() - L.ts > WINDOW_MS) return null;
noteSoft(softKey(req), id, g.owner); return id;
}
// ── reports ─────────────────────────────────────────────────────────────────────────────────────────────────────
// per goal: totals, match methods, and breakdowns by ad campaign (LinkSpin + InstantAdPay), spin link, destination
// and traffic source. Cost per goal on ad campaigns = the campaign's credits spent / its conversions of that goal.
async function report(owner, days, opts) {
const o = norm(owner); const since = Date.now() - (Math.max(1, Math.min(400, Number(days) || 30))) * DAY;
const goals = goalsOf(o); const st = load();
const conv = st.conv.filter(c => c.owner === o && c.ts >= since && !c.self);
const selfTests = st.conv.filter(c => c.owner === o && c.ts >= since && c.self).length;
const methods = { url: 0, stored: 0, cookie: 0, soft: 0 };
const byGoal = {};
const at = (gname) => (byGoal[gname] = byGoal[gname] || { goal: gname, n: 0, value: 0, methods: { url: 0, stored: 0, cookie: 0, soft: 0 }, campaigns: {}, links: {}, dests: {}, sources: {} });
for (const c of conv) {
const G = at(c.goal); G.n++; G.value += c.value || 0; G.methods[c.method] = (G.methods[c.method] || 0) + 1; methods[c.method] = (methods[c.method] || 0) + 1;
if (c.camp) { const key = (c.k === 'iap' ? 'iap:' : 'ls:') + c.camp; const x = G.campaigns[key] = G.campaigns[key] || { key, site: c.k === 'iap' ? 'InstantAdPay' : 'LinkSpin', id: c.camp, name: c.cname || '', n: 0, value: 0 }; x.n++; x.value += c.value || 0; }
if (c.rot) { const x = G.links[c.rot] = G.links[c.rot] || { id: c.rot, code: c.rcode, name: c.rname || '', n: 0, value: 0 }; x.n++; x.value += c.value || 0; }
if (c.dest) { let d = c.dest; try { const u = new URL(c.dest); d = u.hostname.replace(/^www\./, '') + u.pathname.replace(/\/$/, ''); } catch (e) {} const x = G.dests[d] = G.dests[d] || { k: d, n: 0 }; x.n++; }
{ const key = c.sr ? 'src:' + c.sr : (c.src || '(direct)'); const x = G.sources[key] = G.sources[key] || { k: key, sourceId: c.sr || '', n: 0 }; x.n++; }
}
// clicks per ad campaign in the same window, and the cost basis
const clicksBy = {}; for (const k in st.clicks) { const a = st.clicks[k]; if (a.owner !== o || a.ts < since || a.self) continue; const key = (a.k === 'iap' ? 'iap:' : 'ls:') + a.camp; clicksBy[key] = (clicksBy[key] || 0) + 1; }
const meta = (opts && opts.sourceMeta) || {};
const out = [];
for (const gname of new Set(goals.map(g => g.name).concat(Object.keys(byGoal)))) {
const G = byGoal[gname] || at(gname);
const campaigns = [];
for (const x of Object.values(G.campaigns)) {
let spent = null, asOf = null;
if (x.site === 'LinkSpin') { try { const cp = await campaignOf(x.id); if (cp && norm(cp.owner) === o) { spent = Number(cp.spent || 0) + Number(cp.accrued || 0); if (!x.name) x.name = cp.name || ''; } } catch (e) {} }
else { const cm = st.camps['iap:' + x.id]; if (cm && cm.owner === o) { spent = cm.spent; asOf = cm.ts; if (!x.name) x.name = cm.name; } }
campaigns.push(Object.assign(x, { clicks: clicksBy[x.key] || 0, spent, spentAsOf: asOf, costPer: spent != null && x.n ? Math.round(spent / x.n * 100) / 100 : null, rate: clicksBy[x.key] ? Math.round(x.n / clicksBy[x.key] * 1000) / 10 : null }));
}
campaigns.sort((a, b) => b.n - a.n);
const sources = Object.values(G.sources).map(x => Object.assign(x, { name: x.sourceId ? ((meta[x.sourceId] || {}).name || 'Deleted source') : x.k })).sort((a, b) => b.n - a.n).slice(0, 15);
const g = goals.find(y => y.name === gname);
out.push({ goal: gname, px: g ? g.px : null, removed: !g, n: G.n, value: Math.round(G.value * 100) / 100, methods: G.methods, campaigns,
links: Object.values(G.links).sort((a, b) => b.n - a.n).slice(0, 15), dests: Object.values(G.dests).sort((a, b) => b.n - a.n).slice(0, 15), sources });
}
return { days: Number(days) || 30, goals: goals.map(g => Object.assign(pubGoal(g), { conv: conv.filter(c => c.px === g.px).length, lastAt: (conv.filter(c => c.px === g.px).pop() || {}).ts || null })),
byGoal: out, methods, total: conv.length, selfTests };
}
// InstantAdPay's view: goals + per IAP campaign conversions (and clicks) for this owner
function partnerSummary(owner, days) {
const o = norm(owner); const since = Date.now() - (Math.max(1, Math.min(90, Number(days) || 30))) * DAY; const st = load();
const conv = st.conv.filter(c => c.owner === o && c.ts >= since && !c.self);
const byCampaign = {};
for (const k in st.clicks) { const a = st.clicks[k]; if (a.k !== 'iap' || a.owner !== o || a.ts < since || a.self) continue; const b = byCampaign[a.camp] = byCampaign[a.camp] || { clicks: 0, conv: {}, value: {} }; b.clicks++; }
for (const c of conv) if (c.k === 'iap' && c.camp) { const b = byCampaign[c.camp] = byCampaign[c.camp] || { clicks: 0, conv: {}, value: {} }; b.conv[c.px] = (b.conv[c.px] || 0) + 1; b.value[c.px] = Math.round(((b.value[c.px] || 0) + (c.value || 0)) * 100) / 100; }
const methods = { url: 0, stored: 0, cookie: 0, soft: 0 }; for (const c of conv) methods[c.method] = (methods[c.method] || 0) + 1;
const goals = goalsOf(o).map(g => { const mine = conv.filter(c => c.px === g.px); return Object.assign(pubGoal(g), { conv: mine.length, convDays: Number(days) || 30, lastAt: mine.length ? mine[mine.length - 1].ts : null }); });
return { ok: true, goals, byCampaign, methods };
}
function csv(owner, days) {
const o = norm(owner); const since = Date.now() - (Math.max(1, Math.min(400, Number(days) || 30))) * DAY;
const esc = v => { const s = v == null ? '' : String(v); return /[",\n]/.test(s) || /^[=+\-@]/.test(s) ? '"' + (/^[=+\-@]/.test(s) ? "'" : '') + s.replace(/"/g, '""') + '"' : s; };
const ctFmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
const lines = ['time_central,goal,value,match_method,site,campaign_id,campaign,spin_link,destination,source,country,device,click_id'];
for (const c of load().conv) if (c.owner === o && c.ts >= since && !c.self) lines.push([ctFmt.format(new Date(c.ts)).replace(',', ''), c.goal, c.value || 0, c.method, c.k === 'iap' ? 'InstantAdPay' : (c.k === 'ad' ? 'LinkSpin ad' : 'Spin link'), c.camp || '', c.cname || '', c.rcode || '', c.dest || '', c.src || '', c.c || '', c.dv || '', c.click].map(esc).join(','));
return lines.join('\n') + '\n';
}
// "Send a test conversion" from a screen (InstantAdPay's partner call, or the Control Room when it cannot load the image)
function testGoal(owner, px) { const g = goal(px); if (!g || g.owner !== norm(owner)) return { error: 'No such goal.' }; load().tests[g.px] = Date.now(); save(); flush(); return { ok: true, at: load().tests[g.px] }; }
function adminCounts() { const st = load(); return { goals: Object.keys(st.goals).length, clicks: Object.keys(st.clicks).length, conversions: st.conv.length }; }
module.exports = { init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS };
+4
View File
@@ -13,6 +13,10 @@ const FAQ = [
questions: ['I am already on InstantAdPay, do I start over?', 'Will my InstantAdPay sponsor be my sponsor here?', 'Can I sign in with my InstantAdPay email?'],
tags: ['instantadpay', 'sponsor', 'carry-over', 'team', 'network'],
answer: 'Sign in with the email you use on InstantAdPay and your sponsor is placed for you before you buy anything: the same people above you, the same people below you, the same wallet. LinkSpin is a second property to build on, with tools you will use every day.' },
{ id: 'f-conversion-pixel', title: 'How do I count sign-ups and sales from my ads?', source: 'faq',
questions: ['How do I count sign-ups from my ads?', 'How do I see cost per lead?', 'Where do I put the conversion pixel?', 'My autoresponder has its own thank-you page, can I still track?'],
tags: ['conversion pixel', 'goal', 'cost per goal', 'thank-you page', 'aweber', 'getresponse'],
answer: 'Open Conversions in your Control Room (' + SITE_URL + '/conversions) and add a goal, for example subscriber. Paste the landing tag once on your landing page and the goal pixel on your thank-you page, then press Send a test conversion. From then on each click on your ads and spin links that reaches the goal counts once, within 30 days of the click, with its cost per goal by campaign. If Aweber, GetResponse or another provider shows its own thank-you page, set its thank-you redirect to a page on your own site that carries the pixel. InstantAdPay members find the same goals under Campaigns > Conversion tracking.' },
{ id: 'f-new-here', title: 'New here: where to start', source: 'faq',
questions: ['I am new, where do I start?', 'What should I do first?', 'How do I get started?'],
tags: ['getting started', 'new member', 'first steps'],
+4 -3
View File
@@ -17,7 +17,7 @@ const J = { db: null, FILE: () => path.join(DATA_DIR, 'postbacks.json'),
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } };
function init(opts) { DATA_DIR = opts.dataDir; ownHosts = opts.ownHosts || (() => []); rotator = opts.rotator; SOURCES = opts.sources || null; J.load(); }
const norm = e => String(e || '').trim().toLowerCase();
const EVENTS = ['join', 'lead', 'wallet', 'purchase', 'external'];
const EVENTS = ['join', 'lead', 'wallet', 'purchase', 'external', 'goal']; // 'goal' = any conversion-pixel goal (2026-10-23); {event} carries the goal's name
const MACRO = /\{([a-z0-9_]{1,24})\}/gi;
function isPrivateIp(ip) {
@@ -102,7 +102,8 @@ async function fire(owner, event, ctx) {
const q = (ctx.q || {});
const vals = { clickid: q.clickid || q.cid || q.click_id || q.external_id || q.visitor_id || '', subid: q.subid || q.sub_id || q.s1 || '', s1: q.s1 || q.sub1 || '', s2: q.s2 || q.sub2 || '', s3: q.s3 || q.sub3 || '', s4: q.s4 || q.sub4 || '', s5: q.s5 || q.sub5 || '', source: ctx.source || '', event, payout: ctx.payout != null ? ctx.payout : '', currency: ctx.currency || 'USD', txid: ctx.txid || '', lsid: ctx.lsid || '', code: ctx.code || '', country: ctx.country || '', device: ctx.device || '' };
for (const [k, v] of Object.entries(q)) if (/^(utm_[a-z]+|sub\d|s\d|aff_sub\d?|t\d|cost|zone|placement|site|campaign|creative|banner|keyword|geo|os|browser|carrier|format)$/.test(k) && vals[k] == null) vals[k] = v;
for (const p of J.db.items.filter(x => x.owner === o && x.enabled && x.events.includes(event))) {
const listens = evs => (evs || []).includes(event) || (!!ctx.goal && (evs || []).includes('goal'));
for (const p of J.db.items.filter(x => x.owner === o && x.enabled && listens(x.events))) {
if (!rateOk(o)) break;
const url = fill(p.url, vals);
let r = await deliver(p, url, Object.assign({}, ctx, { event }));
@@ -112,7 +113,7 @@ async function fire(owner, event, ctx) {
// the traffic source that sent this click (and only that one) hears about it through its own postback
if (ctx.sourceId && SOURCES) {
const s = SOURCES.forFire(o, ctx.sourceId);
if (s && (s.events || []).includes(event) && rateOk(o)) {
if (s && listens(s.events) && rateOk(o)) {
const url = fill(s.postbackUrl, vals);
let r = await deliver(s, url, Object.assign({}, ctx, { event, viaSource: s.id }));
if (!r.ok && !ctx.test) { await new Promise(res => setTimeout(res, 4000)); r = await deliver(s, url, Object.assign({}, ctx, { event, viaSource: s.id })); }
+1 -1
View File
@@ -71,7 +71,7 @@
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/ads-screen.js?v=20261023q"></script>
</body>
</html>
+70
View File
@@ -0,0 +1,70 @@
// LinkSpin Conversions (conversion pixel, 2026-10-23): goals + pixel ids, the two snippets, a test button, and per goal the
// conversions and cost per goal by ad campaign (LinkSpin and InstantAdPay), spin link, destination and traffic source.
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt;
let RANGE = 30, D = null, PICK = '';
CR.mount({ active: 'conversions', title: 'Conversions', sub: 'loading', actions: '<span style="display:inline-flex;gap:8px;align-items:center"><div class="range" id="range"><button type="button" data-d="7">7d</button><button type="button" data-d="30" class="on">30d</button><button type="button" data-d="90">90d</button></div> <a class="btn" id="csvBtn" href="/api/my/conversions.csv?days=30">CSV</a></span>' });
$('range').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { RANGE = Number(b.dataset.d); $('range').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); $('csvBtn').href = '/api/my/conversions.csv?days=' + RANGE; load(); }));
const ago = ts => { if (!ts) return 'never'; const m = Math.round((Date.now() - ts) / 60000); return m < 1 ? 'just now' : m < 60 ? m + ' min ago' : m < 1440 ? Math.round(m / 60) + ' h ago' : Math.round(m / 1440) + ' d ago'; };
const money = v => v ? '$' + Number(v).toFixed(2) : '';
const METH = [['url', 'Address'], ['stored', 'Kept'], ['cookie', 'Cookie'], ['soft', '24 h match']];
function snippets() {
const g = (D.goals || []).find(x => x.px === PICK) || (D.goals || [])[0];
const base = D.base || ('https://' + (D.host || 'linkspin.app'));
if (!g) { ['snTag', 'snImg', 'snJs'].forEach(k => { $(k).textContent = 'Add a goal first. Its snippets show here.'; }); $('testBtn').disabled = true; $('testNote').textContent = ''; return; }
$('testBtn').disabled = false;
$('snTag').textContent = '<script async src="' + base + '/t.js?px=' + g.px + '"></script>';
$('snImg').textContent = '<img src="' + base + '/cv.gif?px=' + g.px + '&goal=' + g.name + '" width="1" height="1" alt="" style="display:none">';
$('snJs').textContent = '<script async src="' + base + '/cv.js?px=' + g.px + '&goal=' + g.name + '"></script>';
$('testNote').textContent = g.lastTest ? 'Last test received ' + ago(g.lastTest) : 'No test received yet';
}
function paint() {
const goals = D.goals || [];
CR.sub(RANGE + ' days · ' + goals.length + ' goal' + (goals.length === 1 ? '' : 's') + ' · ' + fmt(D.total || 0) + ' counted');
$('goalRows').innerHTML = goals.length ? goals.map(g => '<div class="rw"><span><b>' + esc(g.name) + '</b><span class="muted" style="display:block;font-size:11px">last ' + esc(ago(g.lastAt)) + (g.lastTest ? ' · test ' + esc(ago(g.lastTest)) : '') + '</span></span><span class="mono">' + esc(g.px) + '</span><span class="r num">' + (g.value ? esc(money(g.value)) : '<span class="muted">none</span>') + '</span><span class="r num">' + fmt(g.conv) + '</span><span class="r"><button class="btn sm" type="button" data-pick="' + g.px + '">Snippets</button> <button class="btn sm" type="button" data-edit="' + g.px + '">Edit</button> <button class="btn sm" type="button" data-del="' + g.px + '">Remove</button></span></div>').join('')
: '<div class="rw"><span class="muted">No goals yet. Add one, for example <b>subscriber</b> or <b>sale</b>.</span><span></span><span></span><span></span><span></span></div>';
if (!goals.some(g => g.px === PICK)) PICK = goals.length ? goals[0].px : '';
$('goalPick').innerHTML = goals.map(g => '<option value="' + g.px + '"' + (g.px === PICK ? ' selected' : '') + '>' + esc(g.name) + '</option>').join('');
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' : '';
$('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>';
const gm = G.methods || {};
return '<div class="sec">Goal: ' + esc(G.goal) + (G.removed ? ' (removed)' : '') + ' · ' + fmt(G.n) + ' counted' + (G.value ? ' · ' + esc(money(G.value)) : '') + ' · ' + METH.map(([k, l]) => l + ' ' + fmt(gm[k] || 0)).join(', ') + '</div>'
+ '<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 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' }); }));
$('goalRows').querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => goalForm(goals.find(g => g.px === b.dataset.edit))));
$('goalRows').querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async () => {
if (!await CR.dialog({ title: 'Remove this goal?', text: 'Its pixel stops counting at once. Conversions already counted stay in your reports.', ok: 'Remove', danger: true })) return;
try { await CR.api('/api/my/conversions/goals/' + b.dataset.del, { remove: true }); CR.toast('Goal removed'); load(); } catch (e) { CR.toast(e.message, true); }
}));
}
async function goalForm(g) {
const v = await CR.dialog({ title: g ? 'Edit goal' : 'Add a goal', text: 'One word for what you count, like subscriber or sale. The default value is optional, in US dollars, used when the pixel carries none.',
fields: [{ k: 'name', label: 'Goal name', value: g ? g.name : '', placeholder: 'subscriber', max: 32 }, { k: 'value', label: 'Default value (optional)', value: g && g.value ? String(g.value) : '', placeholder: '0.00', max: 10 }], ok: g ? 'Save' : 'Add goal' });
if (!v) return;
try { const r = g ? await CR.api('/api/my/conversions/goals/' + g.px, v) : await CR.api('/api/my/conversions/goals', v); if (r.goal) PICK = r.goal.px; CR.toast(g ? 'Saved' : 'Goal added. Its snippets are ready below.'); load(); } catch (e) { CR.toast(e.message, true); }
}
$('addGoal').addEventListener('click', () => goalForm(null));
$('goalPick').addEventListener('change', () => { PICK = $('goalPick').value; snippets(); });
document.querySelectorAll('[data-copy]').forEach(b => b.addEventListener('click', () => CR.copy($(b.dataset.copy).textContent)));
// the test loads the real image pixel, the same request a thank-you page makes; it is recorded apart and never counted
$('testBtn').addEventListener('click', async () => {
const px = PICK; if (!px) return; $('testBtn').disabled = true; $('testNote').textContent = 'Sending...';
let ok = false; try { const r = await fetch('/cv.gif?px=' + px + '&test=1&r=' + Date.now(), { cache: 'no-store' }); ok = r.ok && /^test/.test(r.headers.get('X-LS-Result') || ''); } catch (e) {}
if (!ok) { try { await CR.api('/api/my/conversions/goals/' + px, { test: true }); ok = true; } catch (e) {} }
CR.toast(ok ? 'Test received. Your pixel id works.' : 'The test did not arrive. Try again in a minute.', !ok); $('testBtn').disabled = false; load();
});
async function load() {
try { D = await CR.get('/api/my/conversions?days=' + RANGE); } catch (e) { CR.sub('could not load'); return; }
paint();
}
CR.requireSession(load);
})();
+2 -1
View File
@@ -14,6 +14,7 @@ window.CR = (function () {
['ads', 'Ads', '/ads', '<path d="M3 11l14-5v12L3 13v-2z"/><path d="M17 8a4 4 0 0 1 0 8"/>'],
['credits', 'Credits', '/credits', '<circle cx="12" cy="12" r="8"/><path d="M12 8v8M9.5 10.5h3.5a1.5 1.5 0 0 1 0 3H10a1.5 1.5 0 0 0 0 3h4.5"/>'],
['reports', 'Reports', '/reports', '<path d="M4 19V9M10 19V5M16 19v-8M22 19H2"/>'],
['conversions', 'Conversions', '/conversions', '<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="4"/><circle cx="12" cy="12" r="0.8"/>'], // conversion pixel goals (2026-10-23)
['team', 'Team', '/team', '<circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.5"/><path d="M3 19c0-3 3-5 6-5s6 2 6 5M15 15c3 0 6 1.5 6 4"/>'],
['wallet', 'Wallet', '/wallet', '<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M16 12h3"/>'],
['promo', 'Promo tools', '/tools#promo', '<path d="M7 10s5-1 9-5v14c-4-4-9-5-9-5H5a2 2 0 0 1-2-2v0a2 2 0 0 1 2-2h2z"/><path d="M8 15l1 5h2l-1-5"/>'],
@@ -25,7 +26,7 @@ window.CR = (function () {
];
// screens not built yet fall back to the classic dashboard pane so nothing is a dead end
const FALLBACK = {}; // the classic /my dashboard is retired (2026-10-08); its leftover panes live at /tools
const BUILT = new Set(['links', 'sources', 'pages', 'zones', 'ads', 'credits', 'reports', 'team', 'wallet', 'tools', 'promo', 'training', 'pipeline', 'profile', 'help']); // Training, Pipeline and Profile on the rail, not behind More (Marty 2026-10-11); Help = support tickets (2026-10-16)
const BUILT = new Set(['links', 'sources', 'pages', 'zones', 'ads', 'credits', 'reports', 'conversions', 'team', 'wallet', 'tools', 'promo', 'training', 'pipeline', 'profile', 'help']); // Training, Pipeline and Profile on the rail, not behind More (Marty 2026-10-11); Help = support tickets (2026-10-16)
let ME = null, toastT;
// Expired session (Marty 2026-10-23: "told me to sign in but never redirected me"): sessions last 24 h, and a screen
// left open past that got 'Sign in first.' errors with no way forward. Any 401 from our API, or coming back to a tab
+1 -1
View File
@@ -9,7 +9,7 @@
const ago = ts => { if (!ts) return 'never'; const s = Math.max(0, Math.round((Date.now() - ts) / 1000)); return s < 60 ? 'just now' : s < 3600 ? Math.round(s / 60) + ' min ago' : s < 86400 ? Math.round(s / 3600) + ' h ago' : Math.round(s / 86400) + ' d ago'; };
const netOf = s => CAT.find(c => c.key === s.template) || null;
const netName = s => { const n = netOf(s); return n ? n.name : (s.template === 'custom' ? 'Custom' : s.template); };
const EV_LABEL = { join: 'Join', lead: 'Lead', wallet: 'Wallet', purchase: 'Purchase', external: 'Partner-reported' };
const EV_LABEL = { join: 'Join', lead: 'Lead', wallet: 'Wallet', purchase: 'Purchase', external: 'Partner-reported', goal: 'Any goal (pixel)' };
async function load(keep) {
let r; try { r = await CR.get('/api/my/sources'); } catch (e) { CR.sub('could not load'); return; }
+73
View File
@@ -0,0 +1,73 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="robots" content="noindex, nofollow">
<title>Conversions · LinkSpin</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700&family=JetBrains+Mono:wght@500;700&display=swap">
<link rel="stylesheet" href="/assets/cr.css?v=20261020s">
<style>
.body{padding:16px 24px;display:grid;gap:16px}
.two{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:16px;align-items:start}
.panel{align-content:start}
.range{display:flex;border:1px solid var(--line-strong);border-radius:var(--r);overflow:hidden;background:var(--panel-2)} .range button{background:transparent;border:0;color:var(--muted);font-family:var(--mono);font-size:12px;padding:5px 10px;cursor:pointer} .range button.on{background:var(--ink);color:#fff}
.goals .hd,.goals .rw{grid-template-columns:minmax(0,1fr) 120px 70px 90px 150px;gap:8px;align-items:center}
.camps .hd,.camps .rw{grid-template-columns:minmax(0,1fr) 92px 60px 56px 60px 90px;gap:8px}
.lst .hd,.lst .rw{grid-template-columns:minmax(0,1fr) 60px;gap:8px}
.meth{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}
.meth .m{background:var(--panel-2);border:1px solid var(--line);border-radius:6px;padding:8px 10px;display:grid;gap:2px}
.meth .m .k{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)} .meth .m .v{font-family:var(--display);font-weight:700;font-size:20px}
.snip{display:grid;gap:6px;margin-top:10px} .snip .code{display:block;font-size:12px;line-height:1.6;padding:10px 12px;overflow-wrap:anywhere;white-space:pre-wrap}
.steps{margin:6px 0 0;padding-left:20px;display:grid;gap:6px}
.gsel{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.pill{font-family:var(--mono);font-size:11px;padding:1px 7px;border-radius:3px;background:var(--panel-2);border:1px solid var(--line)}
@media (max-width:900px){.two{grid-template-columns:1fr}.body{padding:12px 16px}.goals .hd{display:none}.goals .rw{grid-template-columns:minmax(0,1fr) auto;row-gap:4px}.camps .hd,.camps .rw{grid-template-columns:minmax(0,1fr) 60px 44px 44px 64px;font-size:12px}.camps .hd span:nth-child(2),.camps .rw span:nth-child(2){display:none}.meth{grid-template-columns:repeat(2,minmax(0,1fr))}}
</style>
</head>
<body>
<div id="page">
<div class="body">
<div class="panel">
<div class="ph" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px"><h2>Your goals</h2><button class="btn pri" type="button" id="addGoal">Add a goal</button></div>
<div class="muted" style="margin:4px 0 10px">A goal is something you want counted: a subscriber, a sale, a sign-up. Each goal has its own pixel id. The id is public and safe to paste: it can only count clicks that are yours.</div>
<div class="tbl goals"><div class="hd"><span>Goal</span><span>Pixel id</span><span class="r">Value</span><span class="r">Counted</span><span></span></div><div id="goalRows"></div></div>
</div>
<div class="two">
<div class="panel">
<h2>Set it up in 3 steps</h2>
<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>
</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>
<div class="snip"><span class="sec">2. Goal pixel (image)</span><code class="code mono" id="snImg"></code><div><button class="btn sm" type="button" data-copy="snImg">Copy</button></div></div>
<div class="snip"><span class="sec">2b. Goal pixel (script, reads what the landing tag kept)</span><code class="code mono" id="snJs"></code><div><button class="btn sm" type="button" data-copy="snJs">Copy</button></div></div>
<div class="muted" style="margin-top:8px">Add <span class="mono">&amp;value=19.95</span> to the pixel to record what the sale was worth. Without it, the goal's default value is used.</div>
</div>
<div class="panel">
<h2>Autoresponders and hosted thank-you pages</h2>
<div class="ink2" style="display:grid;gap:8px">
<p style="margin:0">If your list provider shows its own thank-you page, you cannot paste the pixel there. Point the provider at a page on <b>your</b> site instead, and put the pixel on that page.</p>
<p style="margin:0"><b>Aweber:</b> open your sign-up form, go to its settings, set <b>Thank You Page</b> to a custom page and paste your page's address.</p>
<p style="margin:0"><b>GetResponse:</b> in the form or landing page settings, set the <b>thank-you page</b> to a custom URL and paste your page's address.</p>
<p style="margin:0">If you cannot change it, the pixel can still count through LinkSpin's cookie or the 24-hour match, just less surely.</p>
<p style="margin:0"><b>Forms on your own page:</b> add a hidden field named <span class="mono">lsclk</span> and the landing tag fills it with the click id, so your own system can pass it on.</p>
<p style="margin:0"><b>Postbacks:</b> a postback set to the event <span class="mono">goal</span> (on <a href="/links">Links</a> or a <a href="/sources">traffic source</a>) fires for every goal, with <span class="mono">{event}</span> = the goal's name.</p>
</div>
</div>
</div>
<div class="panel">
<div class="ph" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px"><h2>How sure is each count</h2><span class="muted" id="totalNote"></span></div>
<div class="meth" id="methRows"></div>
<div class="muted" style="margin-top:8px"><b>Address</b>: the click id was on the thank-you page's address. <b>Kept</b>: the landing tag kept it on your site. Both are exact. <b>Cookie</b>: LinkSpin's own cookie, exact but some browsers block it. <b>24 h match</b>: same network and browser within a day of the click, a good guess, not proof. Each goal counts once per click, only within 30 days of the click, and only for clicks on your own ads and links.</div>
</div>
<div id="goalReports"></div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/conversions.js?v=20261023a"></script>
</body>
</html>
+1 -1
View File
@@ -82,7 +82,7 @@
</div>
<script src="/assets/common.js?v=20261023ov"></script>
<script src="/assets/wallet.js?v=20261021a"></script>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/credits-screen.js?v=20261019pos"></script>
</body>
</html>
+34
View File
@@ -0,0 +1,34 @@
/* LinkSpin goal pixel, script version (conversion pixel, 2026-10-23). Paste on your thank-you page:
* <script async src="https://linkspin.app/cv.js?px=YOUR_PIXEL_ID&goal=subscriber"></script> (optional &value=19.95)
* It sends the click id from this page's address, or the one the landing tag (t.js) kept on your site, to LinkSpin.
* The image version (cv.gif) works without scripts; this one is surer because it can read what the landing tag kept.
* It never throws and never blocks your page.
*/
(function () {
try {
var RX = /^[a-z0-9]{6,24}$/i, W = window;
function stored() {
var v = '';
try { var j = JSON.parse(W.localStorage.getItem('ls_clk') || 'null'); if (j && RX.test(j.id || '') && Date.now() - (j.ts || 0) < 30 * 864e5) v = j.id; } catch (e) {}
if (!v) { try { var m = /(?:^|;\s*)ls_clk=([a-z0-9]{6,24})/i.exec(document.cookie || ''); if (m) v = m[1]; } catch (e) {} }
return v;
}
var q = new URLSearchParams(location.search);
var inUrl = q.get('lsclk') || q.get('lsid') || q.get('clickid') || '';
var c = '', m = '';
if (RX.test(inUrl)) { c = inUrl; m = 'url'; } else { c = stored(); m = c ? 'stored' : ''; }
var list = document.getElementsByTagName('script');
for (var i = 0; i < list.length; i++) {
var s = list[i];
try {
if (!/\/cv\.js(\?|$)/.test(s.src || '') || s.getAttribute('data-ls-done')) continue;
s.setAttribute('data-ls-done', '1');
var u = new URL(s.src, location.href), px = u.searchParams.get('px') || '';
if (!/^px[a-f0-9]{10}$/.test(px)) continue;
var goal = u.searchParams.get('goal') || '', value = u.searchParams.get('value');
var out = u.origin + '/cv.gif?px=' + px + (goal ? '&goal=' + encodeURIComponent(goal) : '') + (value != null && value !== '' ? '&value=' + encodeURIComponent(value) : '') + (c ? '&c=' + encodeURIComponent(c) + '&m=' + m : '') + (u.searchParams.get('test') === '1' ? '&test=1' : '') + '&r=' + Math.random().toString(36).slice(2, 8);
var im = new Image(1, 1); im.src = out;
} catch (e) {}
}
} catch (e) { /* never break the member's page */ }
})();
+1 -1
View File
@@ -29,7 +29,7 @@
<div id="page">
<div class="body" id="helpBody"><div class="panel"><span class="muted">loading</span></div></div>
</div>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/help-screen.js?v=20261016a"></script>
</body>
</html>
+1 -1
View File
@@ -252,7 +252,7 @@
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/links.js?v=20261021t"></script>
<script src="/assets/banner-spin.js?v=20261020bs3"></script>
</body>
+1 -1
View File
@@ -1008,7 +1008,7 @@
</div>
</div>
<script src="/assets/common.js?v=20261023ov"></script>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/tools.js?v=20261011a"></script>
<script src="/assets/wallet.js?v=20261021a"></script>
<script src="/assets/promo.js?v=20261020bs3"></script>
+1 -1
View File
@@ -72,7 +72,7 @@
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/pages-screen.js?v=20261021t"></script>
</body>
</html>
+4 -1
View File
@@ -27,6 +27,9 @@
<p>A minimal set: the email you sign up with, a username and any profile details you choose to add (avatar, bio, social links), and, only if you link one, your public wallet address. The links you rotate, the pages you publish, the zones you register, campaign content you create and reports you submit are stored to run the service. We also read on-chain activity that is already public on the blockchain.</p>
<h2 class="disp">Click and impression records</h2>
<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>
<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>
@@ -34,7 +37,7 @@
<h2 class="disp">How we use it</h2>
<p>To run your account, serve and measure links, pages and ads, attribute referrals, send service and notification emails (payouts, messages, onboarding), and keep the Platform secure. You can set your email and chat notification preferences in your dashboard.</p>
<h2 class="disp">Cookies</h2>
<p>We use a session cookie to keep you signed in, a referral cookie to credit the sponsor whose link you arrived through, a click cookie that ties a sign-up back to the spin link that brought you, and a demo cookie that holds a spin link you made before signing in. That is it. No third-party ad-tracking cookies.</p>
<p>We use a session cookie to keep you signed in, a referral cookie to credit the sponsor whose link you arrived through, a click cookie that ties a sign-up back to the spin link that brought you, a demo cookie that holds a spin link you made before signing in, a visitor cookie (<code>ls.vid</code>) that lets members show or hide their own ads to people who visited their pages, and the conversion click cookie (<code>ls.clk</code>) described above. The last two can be read when our audience or goal pixel loads on a member's own site. We do not use any other company's tracking cookies, and we do not sell or share these records.</p>
<h2 class="disp">Sharing</h2>
<p>Your username and public profile are visible to others by design, and on-chain transactions are public by nature. We share data with infrastructure providers (hosting, email delivery) only as needed to operate the service, with the partner ad network only as impression counts, and when required by law.</p>
<h2 class="disp">Your choices</h2>
+2 -2
View File
@@ -41,7 +41,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.</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>
</div>
<!-- Pages: views, uniques, clicks through and leads on the member's bridge / review / squeeze pages (2026-10-10) -->
@@ -89,7 +89,7 @@
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/reports.js?v=20261020bs3"></script>
</body>
</html>
+2 -2
View File
@@ -123,7 +123,7 @@
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/sources-screen.js?v=20261012a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/sources-screen.js?v=20261023a"></script>
</body>
</html>
+72
View File
@@ -0,0 +1,72 @@
/* LinkSpin landing tag (conversion pixel, 2026-10-23). Paste once on your landing page:
* <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.
* It never throws and never blocks your page: every step is wrapped, and it only runs after the page has its scripts.
*/
(function () {
try {
var KEY = 'ls_clk', RX = /^[a-z0-9]{6,24}$/i, DAYS = 30, W = window;
var me = document.currentScript;
if (!me) { var all = document.getElementsByTagName('script'); for (var i = all.length - 1; i >= 0; i--) { if (/\/t\.js(\?|$)/.test(all[i].src || '')) { me = all[i]; break; } } }
if (!me || !me.src) return;
var src = new URL(me.src, location.href), base = src.origin, px = src.searchParams.get('px') || '';
var framed = true; try { framed = W.top !== W.self; } catch (e) { framed = true; }
var https = location.protocol === 'https:';
function setCookie(v) {
try { document.cookie = KEY + '=' + v + '; path=/; max-age=' + (DAYS * 86400) + (https ? (framed ? '; SameSite=None; Secure' : '; SameSite=Lax; Secure') : '; SameSite=Lax'); } catch (e) {}
}
function stored() {
var v = '';
try { var j = JSON.parse(W.localStorage.getItem(KEY) || 'null'); if (j && RX.test(j.id || '') && Date.now() - (j.ts || 0) < DAYS * 864e5) v = j.id; } catch (e) {}
if (!v) { try { var m = /(?:^|;\s*)ls_clk=([a-z0-9]{6,24})/i.exec(document.cookie || ''); if (m) v = m[1]; } catch (e) {} }
return v;
}
function keep(v) { try { W.localStorage.setItem(KEY, JSON.stringify({ id: v, ts: Date.now() })); } catch (e) {} setCookie(v); }
var q = new URLSearchParams(location.search);
var fresh = q.get('lsclk') || q.get('lsid') || '';
var id = '';
if (RX.test(fresh)) { id = fresh; keep(id); }
else {
id = stored();
// a generic clickid only when we hold nothing better (it may be another network's id)
var g = q.get('clickid') || ''; if (!id && RX.test(g)) { id = g; keep(id); fresh = g; }
}
// tell LinkSpin the landing happened (sets its own 30-day cookie and the 24 h match); only for a fresh id
if (fresh && RX.test(fresh) && /^px[a-f0-9]{10}$/.test(px)) { try { var im = new Image(1, 1); im.src = base + '/t.gif?px=' + px + '&c=' + encodeURIComponent(fresh) + '&r=' + Math.random().toString(36).slice(2, 8); } catch (e) {} }
var LS = W.LinkSpin = W.LinkSpin || {};
LS.clickId = function () { return id || stored(); };
LS.goal = function (pixelId, name, value) {
try {
var c = id || stored(); var u = base + '/cv.gif?px=' + encodeURIComponent(pixelId) + (name ? '&goal=' + encodeURIComponent(name) : '') + (value != null && value !== '' ? '&value=' + encodeURIComponent(value) : '') + (c ? '&c=' + encodeURIComponent(c) + '&m=stored' : '') + '&r=' + Math.random().toString(36).slice(2, 8);
var im2 = new Image(1, 1); im2.src = u;
} catch (e) {}
};
if (!id) return;
var NAMES = ['lsclk', 'lsid', 'clickid'];
function fillForms(root) {
try {
var f = (root || document).querySelectorAll('input[name="lsclk"],input[name="lsid"],input[name="clickid"]');
for (var i = 0; i < f.length; i++) if (!f[i].value) f[i].value = id;
} catch (e) {}
}
fillForms();
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', function () { fillForms(); });
document.addEventListener('submit', function (e) { fillForms(e.target); }, true);
var host = location.hostname.replace(/^www\./, '');
function decorate(a) {
try {
if (!a || !a.href || a.getAttribute('data-ls-skip') != null) return;
var u = new URL(a.href, location.href);
if (!/^https?:$/.test(u.protocol) || u.hostname.replace(/^www\./, '') !== host) return;
if (u.pathname === location.pathname && u.search === location.search && u.hash) return; // an anchor on this page
for (var i = 0; i < NAMES.length; i++) if (u.searchParams.has(NAMES[i])) return;
u.searchParams.set('lsclk', id); a.href = u.toString();
} catch (e) {}
}
function onClick(e) { try { var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; if (a) decorate(a); } catch (er) {} }
document.addEventListener('click', onClick, true);
document.addEventListener('auxclick', onClick, true);
} catch (e) { /* never break the member's page */ }
})();
+1 -1
View File
@@ -37,7 +37,7 @@
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/team.js?v=20261020s"></script>
</body>
</html>
+1 -1
View File
@@ -31,7 +31,7 @@
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/wallet-screen.js?v=20261023ov"></script>
</body>
</html>
+1 -1
View File
@@ -41,7 +41,7 @@
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261023a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/zones-screen.js?v=20261010a"></script>
</body>
</html>
+255
View File
@@ -0,0 +1,255 @@
// Conversion pixel (2026-10-23, Marty approved). Three parts, all on throwaway data (no production data, no real members):
// 1) unit: convtrack.js on a temp dir: 30-day window, per-IP rate limit, owner check, InstantAdPay click import rules.
// 2) end to end on a local server.js (JSON store, no DB, no mail key, devCode sign-in, test LS_SYNC_SECRET, seeded
// 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.
// 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
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import crypto from 'node:crypto';
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
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 || 8973), PORT2 = PORT + 1;
const SECRET = 'qa-secret-' + crypto.randomBytes(16).toString('hex');
const results = []; let failed = 0;
const check = (ok, what, detail) => { results.push((ok ? 'PASS ' : 'FAIL ') + what + (detail ? ' :: ' + detail : '')); if (!ok) failed++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const DAY = 86400000;
// ---------- 1) unit ----------
{
const UD = fs.mkdtempSync(path.join(os.tmpdir(), 'cv-unit-'));
const C = require(path.join(site, 'convtrack.js'));
C.init({ dataDir: UD, noTimers: true, rotator: null });
const fake = (ip, ua) => ({ headers: { 'user-agent': ua || 'UnitUA', 'x-forwarded-for': ip }, socket: {} });
const g = C.createGoal('own@u.test', { name: 'Sale', value: '12.5' });
check(g.ok && /^px[a-f0-9]{10}$/.test(g.goal.px) && g.goal.name === 'sale' && g.goal.value === 12.5, 'goal created: pixel id, name lowercased, value kept', JSON.stringify(g));
check(!!C.createGoal('own@u.test', { name: 'sale' }).error && !!C.createGoal('own@u.test', { name: 'bad name!' }).error, 'duplicate and bad goal names refused');
const px = g.goal.px;
const id = C.recordAdClick({ id: 7, owner: 'own@u.test', name: 'Unit ad', type: 'banner', targetUrl: 'https://x.test/' }, fake('192.0.2.1'), { country: 'US' });
check(/^a[a-f0-9]{11}$/.test(id), 'LinkSpin ad click id format a + 11 hex', id);
// 30-day window: age the click to 31 days
C.lookup(id).ad.ts = Date.now() - 31 * DAY;
let r = C.record({ px, c: id, m: 'url' }, fake('192.0.2.50'), {});
check(r.result === 'nomatch', 'a click older than 30 days does not count', JSON.stringify(r));
C.lookup(id).ad.ts = Date.now() - 29 * DAY;
r = C.record({ px, c: id, m: 'url' }, fake('192.0.2.50'), {});
check(r.result === 'counted' && r.method === 'url', 'the same click at 29 days counts', JSON.stringify(r.result));
check(C.record({ px, c: id, m: 'url' }, fake('192.0.2.50'), {}).result === 'dup', 'counted once per click');
// owner check: someone else's click never counts for this pixel
const other = C.recordAdClick({ id: 8, owner: 'else@u.test', name: 'Other', type: 'banner', targetUrl: 'https://y.test/' }, fake('192.0.2.2'), {});
check(C.record({ px, c: other, m: 'url' }, fake('192.0.2.51'), {}).result === 'refused', "someone else's click is refused");
// InstantAdPay import rules
const now = Date.now();
const n = C.importClicks([{ id: 'i0123456789a', camp: 5, owner: 'Own@U.test', ts: now, sk: 's:' + 'a'.repeat(20), spent: 90 }, { id: 'bad', owner: 'x@y.z', ts: now }, { id: 'i0123456789b', camp: 5, owner: 'own@u.test', ts: now - 40 * DAY }]);
check(n === 1 && C.lookup('i0123456789a') && C.lookup('i0123456789a').owners[0] === 'own@u.test', 'IAP clicks import: good row in (owner lowercased), bad id and >30-day rows dropped', String(n));
check(C.importClicks([{ id: 'i0123456789a', camp: 5, owner: 'own@u.test', ts: now, spent: 120 }]) === 1 && Object.keys(C.lookup('i0123456789a') ? { a: 1 } : {}).length === 1, 'the same IAP click sent twice is an upsert, not a second click');
// per-IP rate limit (20 a minute)
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');
fs.rmSync(UD, { recursive: true, force: true });
}
// ---------- 2) end to end ----------
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'cv-qa-'));
fs.mkdirSync(path.join(DATA, 'uploads'));
const A = 'convmember@lp.test', B = 'someoneelse@lp.test';
const camp = (id, owner, name, targetUrl, spent) => ({ id, owner, memberId: 0, type: 'banner', name, targetUrl, imageUrl: 'https://img.qa.invalid/b.png', title: null, body: null, width: 728, height: 90, budget: 1000, spent, accrued: 0, imps: 0, clicks: 0, batchImps: 0, status: 'active', created: Date.now() });
fs.writeFileSync(path.join(DATA, 'campaigns.json'), JSON.stringify({ v: 1, nextId: 4, burnsPending: [], campaigns: [
camp(1, A, 'QA banner', 'https://landing.qa.test/page?x=1', 300), camp(2, B, 'Other banner', 'https://other.qa.test/', 50), camp(3, A, 'QA to spin', 'https://landing.qa.test/spin-placeholder', 40)] }));
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'localtest-cv', ADMIN_EMAIL: 'admin@cv.test', SITE_HOST: 'linkspin.test', LS_SYNC_SECRET: SECRET, IAP_URL: 'http://127.0.0.1:9/' });
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']) delete env[k];
const logFile = path.join(DATA, 'server.log'); const log = fs.createWriteStream(logFile);
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'pipe', 'pipe'] });
srv.stdout.pipe(log); srv.stderr.pipe(log);
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ConvQA';
function req(method, p, o) {
o = o || {};
return new Promise((resolve, reject) => {
const headers = Object.assign({ 'User-Agent': o.ua || UA }, o.headers || {});
if (o.cookie) headers.Cookie = o.cookie; if (o.ip) headers['X-Forwarded-For'] = o.ip;
let body = o.raw != null ? Buffer.from(o.raw) : o.body; if (body && !Buffer.isBuffer(body)) { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; } else if (body) headers['Content-Type'] = headers['Content-Type'] || 'application/json';
if (body) headers['Content-Length'] = body.length;
const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, text: buf.toString(), json: j }); }); });
r.on('error', reject); if (body) r.write(body); r.end();
});
}
const signed = (p, obj, secret) => { const raw = JSON.stringify(obj); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', secret || SECRET).update(ts + '\n' + raw).digest('hex'); return req('POST', p, { raw, headers: { 'X-LS-Ts': ts, 'X-LS-Sig': sig, 'Content-Type': 'application/json' } }); };
const softKey = (ip, ua) => 's:' + crypto.createHash('sha256').update(ip + '|' + ua).digest('hex').slice(0, 20);
const res = r => String(r.headers['x-ls-result'] || '');
const lsclkOf = loc => (/[?&]lsclk=([a-z0-9]+)/i.exec(String(loc || '')) || [])[1] || '';
let browserPart = null;
async function signIn(email, ip) {
const st = await req('POST', '/api/auth/email/start', { ip, body: { email, fts: Date.now() - 8000, hp_field_x9: '', pick: null } });
if (!st.json || !st.json.devCode) throw new Error('no devCode: ' + st.text.slice(0, 200));
const v = await req('POST', '/api/auth/email/verify', { ip, body: { email, code: st.json.devCode } });
return [].concat(v.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; ');
}
try {
let up = false; for (let i = 0; i < 60; i++) { try { const r = await req('GET', '/api/config'); if (r.status === 200) { up = true; break; } } catch (e) {} await sleep(500); }
if (!up) throw new Error('server did not come up');
const cA = await signIn(A, '10.77.0.1');
check(!!cA, 'member signed in on the local copy');
const g1 = await req('POST', '/api/my/conversions/goals', { cookie: cA, body: { name: 'subscriber', value: '5' } });
check(g1.status === 200 && g1.json.goal && /^px[a-f0-9]{10}$/.test(g1.json.goal.px), 'goal "subscriber" created in the Control Room API', g1.text.slice(0, 160));
const PX = g1.json.goal.px;
const pb = await req('POST', '/api/my/postbacks', { cookie: cA, body: { name: 'QA goal tracker', url: 'https://tracker.qa.invalid/pb?cid={clickid}&e={event}&ls={lsid}&v={payout}', events: ['goal'] } });
check(pb.status === 200, "postback listening to 'goal' created (an .invalid host)", pb.text.slice(0, 160));
// method url: an ad click, then the pixel with the id from the thank-you page's address
const k1 = await req('GET', '/api/ads/click/1', { ip: '203.0.113.21' });
const id1 = lsclkOf(k1.headers.location);
check(k1.status === 302 && /^a[a-f0-9]{11}$/.test(id1) && /[?&]x=1/.test(k1.headers.location) && /^https:\/\/landing\.qa\.test\/page\?/.test(k1.headers.location), 'ad click: 302 to the target with lsclk added and its own params kept', k1.headers.location);
check(/ls\.clk=/.test(String(k1.headers['set-cookie'] || '')), 'ad click sets the ls.clk cookie');
let r = await req('GET', '/cv.gif?px=' + PX + '&goal=subscriber&c=' + id1 + '&m=url', { ip: '198.18.0.1', headers: { Referer: 'https://landing.qa.test/thanks' } });
check(r.status === 200 && r.headers['content-type'] === 'image/gif' && res(r) === 'counted;url', "goal pixel from the member's own domain counts with method 'url'", res(r));
r = await req('GET', '/cv.gif?px=' + PX + '&goal=subscriber&c=' + id1 + '&m=url', { ip: '198.18.0.1' });
check(res(r) === 'dup;url', 'the same click and goal again: not counted twice', res(r));
// method stored
const id2 = lsclkOf((await req('GET', '/api/ads/click/1', { ip: '203.0.113.22' })).headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + id2 + '&m=stored', { ip: '198.18.0.2' });
check(res(r) === 'counted;stored', "id the landing tag kept counts with method 'stored'", res(r));
// method cookie: no id on the pixel, LinkSpin's own cookie carries it
const id3 = lsclkOf((await req('GET', '/api/ads/click/1', { ip: '203.0.113.23' })).headers.location);
r = await req('GET', '/cv.gif?px=' + PX, { ip: '198.18.0.3', cookie: 'ls.clk=' + id3 });
check(res(r) === 'counted;cookie', "no id on the page, LinkSpin cookie: method 'cookie'", res(r));
// method soft: same IP + browser within 24 h, nothing else
const ip4 = '203.0.113.24', ua4 = 'Mozilla/5.0 SoftMatch QA';
const id4 = lsclkOf((await req('GET', '/api/ads/click/1', { ip: ip4, ua: ua4 })).headers.location);
r = await req('GET', '/cv.gif?px=' + PX, { ip: ip4, ua: 'Mozilla/5.0 Different browser' });
check(res(r) === 'nomatch', 'a different browser on that network does not match', res(r));
r = await req('GET', '/cv.gif?px=' + PX, { ip: ip4, ua: ua4 });
check(res(r) === 'counted;soft' && !!id4, "same IP + browser within 24 h: method 'soft'", res(r));
// owner mismatch: B's ad click, A's pixel
const idB = lsclkOf((await req('GET', '/api/ads/click/2', { ip: '203.0.113.25' })).headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + idB + '&m=url', { ip: '198.18.0.5' });
check(res(r) === 'refused', "a click on someone else's ad is refused by this pixel", res(r));
r = await req('GET', '/cv.gif?px=px0123456789&c=' + id1, { ip: '198.18.0.6' });
check(res(r) === 'unknown' && r.status === 200, 'unknown pixel id: still a gif, nothing recorded', res(r));
// a spin link reached through an ad: the rotator passes a click id on and the conversion credits both
const rc = await req('POST', '/api/my/rotations', { cookie: cA, body: { name: 'Conv QA spin' } });
const rot = rc.json.rotation;
await req('POST', '/api/my/rotations/' + rot.id + '/dest', { cookie: cA, body: { url: 'https://landing.qa.test/lp?y=2', weight: 1 } });
const id5 = lsclkOf((await req('GET', '/api/ads/click/3', { ip: '203.0.113.26' })).headers.location);
const sp = await req('GET', '/r/' + rot.code + '?lsclk=' + id5, { ip: '203.0.113.26' });
const sid = lsclkOf(sp.headers.location);
check(sp.status === 302 && /^[a-f0-9]{10}$/.test(sid) && sid !== id5 && /[?&]y=2/.test(sp.headers.location), 'spin link reached through an ad: destination gets the spin click id (lsclk), its params kept', sp.headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + sid + '&m=stored', { ip: '198.18.0.7' });
check(res(r) === 'counted;stored', 'conversion on the spin click counts', res(r));
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + id5 + '&m=url', { ip: '198.18.0.8' });
check(res(r) === 'dup;url', 'the ad click behind it is the same click: not counted again', res(r));
const spPlain = await req('GET', '/r/' + rot.code, { ip: '203.0.113.27' });
check(/^[a-f0-9]{10}$/.test(lsclkOf(spPlain.headers.location)), 'an owner with a goal: plain spin-link clicks carry lsclk too');
// InstantAdPay: signed click push, then a conversion on it, then the summary
const ipI = '203.0.113.30';
const bad = await signed('/api/partner/clicks', { clicks: [] }, 'wrong-secret-wrong-secret-wrong-secret');
check(bad.status === 401, 'partner call with a bad signature refused', String(bad.status));
const iid = 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11);
const pc = await signed('/api/partner/clicks', { clicks: [{ id: iid, camp: 77, cname: 'IAP QA banner', type: 'banner', owner: A, ts: Date.now(), sk: softKey(ipI, UA), c: 'US', dv: 'desktop', pl: 'instantadpay.com/my', target: 'https://landing.qa.test/iap', spent: 200, self: 0 }] });
check(pc.status === 200 && pc.json.n === 1, 'IAP ad click pushed over the signed partner call', pc.text.slice(0, 120));
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + iid + '&m=url', { ip: '198.18.0.9' });
check(res(r) === 'counted;url', 'conversion on an InstantAdPay ad click counts', res(r));
const sum = await signed('/api/partner/conv', { op: 'summary', email: A, days: 30 });
const bc = sum.json && sum.json.byCampaign && sum.json.byCampaign['77'];
check(sum.status === 200 && bc && bc.clicks === 1 && bc.conv[PX] === 1 && (sum.json.goals || []).some(g => g.px === PX), 'IAP summary: goals + campaign 77 shows 1 click, 1 subscriber', JSON.stringify(bc));
const gI = await signed('/api/partner/conv', { op: 'create', email: A, name: 'sale', value: 20 });
check(gI.status === 200 && gI.json.goal && gI.json.goal.name === 'sale', 'IAP can add a goal to the member (LinkSpin holds it)', gI.text.slice(0, 120));
const tI = await signed('/api/partner/conv', { op: 'test', email: A, px: gI.json.goal.px });
const tX = await signed('/api/partner/conv', { op: 'test', email: B, px: gI.json.goal.px });
check(tI.status === 200 && tI.json.ok && tX.status === 400, "IAP test conversion works for the owner, refused for someone else's goal", tX.text.slice(0, 80));
// a test conversion through the real pixel, and the advertiser's own click
r = await req('GET', '/cv.gif?px=' + PX + '&test=1', { ip: '198.18.0.10' });
check(res(r) === 'test', 'test conversion received', res(r));
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));
// 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(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.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');
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));
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 : ''));
check(!plog.some(l => l.lsid === idSelf), "no postback for the advertiser's own click");
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');
// ---------- 3) browser: landing tag + script pixel on another origin, also framed ----------
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
if (fs.existsSync(PW + '/index.js')) {
const LS = 'http://127.0.0.1:' + PORT;
const pagesSrv = http.createServer((q, s) => {
const u = new URL(q.url, 'http://x');
const html = u.pathname === '/lp' ? '<!doctype html><title>lp</title><form id="f" action="/thanks"><input type="hidden" name="lsclk" value=""><input name="email" value="a@b.c"></form><a id="in" href="/thanks?step=2">Next</a><a id="out" href="https://elsewhere.qa.invalid/">Out</a><script async src="' + LS + '/t.js?px=' + PX + '"></script>'
: u.pathname === '/thanks' ? '<!doctype html><title>thanks</title><p>Thanks</p><script async src="' + LS + '/cv.js?px=' + PX + '&goal=subscriber"></script>'
: u.pathname === '/frame' ? '<!doctype html><title>frame</title><iframe id="fr" src="http://localhost:' + PORT2 + '/lp?lsclk=' + u.searchParams.get('id') + '" width="600" height="400"></iframe>' : '';
s.writeHead(html ? 200 : 404, { 'Content-Type': 'text/html' }); s.end(html);
}).listen(PORT2);
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
const browser = await chromium.launch();
try {
const ctx = await browser.newContext(); const page = await ctx.newPage();
const results2 = [];
page.on('response', rr => { if (/\/cv\.gif\?/.test(rr.url())) results2.push(rr.headers()['x-ls-result'] || ''); });
const idW = lsclkOf((await req('GET', '/api/ads/click/1', { ip: '203.0.113.40' })).headers.location);
await page.goto('http://localhost:' + PORT2 + '/lp?lsclk=' + idW); await page.waitForTimeout(800);
const stored = await page.evaluate(() => { try { return JSON.parse(localStorage.getItem('ls_clk')).id; } catch (e) { return null; } });
const hid = await page.evaluate(() => document.querySelector('input[name=lsclk]').value);
await page.evaluate(() => { document.addEventListener('click', e => e.preventDefault()); document.getElementById('in').dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); });
const inHref = await page.evaluate(() => document.getElementById('in').href), outHref = await page.evaluate(() => document.getElementById('out').href);
check(stored === idW && hid === idW, 'landing tag on another origin keeps the id (localStorage) and fills the hidden lsclk field', stored + ' / ' + hid);
check(/lsclk=/.test(inHref) && !/lsclk=/.test(outHref), 'same-site links get lsclk, links to other sites are left alone', inHref + ' | ' + outHref);
await page.goto('http://localhost:' + PORT2 + '/thanks'); await page.waitForTimeout(1200);
check(results2.includes('counted;stored'), "script goal pixel on the thank-you page (no id in its address) counts with method 'stored'", JSON.stringify(results2));
// framed (a traffic exchange): the member's page inside another site's frame
const idF = lsclkOf((await req('GET', '/api/ads/click/1', { ip: '203.0.113.41' })).headers.location);
const ctx2 = await browser.newContext(); const p2 = await ctx2.newPage(); const res3 = [];
p2.on('response', rr => { if (/\/cv\.gif\?/.test(rr.url())) res3.push(rr.headers()['x-ls-result'] || ''); });
const errs = []; p2.on('pageerror', e => errs.push(String(e)));
await p2.goto('http://127.0.0.1:' + PORT2 + '/frame?id=' + idF); await p2.waitForTimeout(1000);
const fr = p2.frames().find(f => /\/lp/.test(f.url()));
await fr.evaluate(() => { location.href = '/thanks'; }); await p2.waitForTimeout(1500);
check(res3.includes('counted;stored') && !errs.length, 'framed in another site: the tag keeps the id and the thank-you pixel counts, no page errors', JSON.stringify(res3) + ' ' + errs.join('; '));
// a broken LinkSpin host never breaks the member's page
const p3 = await ctx.newPage(); const errs3 = []; p3.on('pageerror', e => errs3.push(String(e)));
await p3.setContent('<p id="ok">fine</p><script async src="http://127.0.0.1:1/t.js?px=' + PX + '"></script><script async src="http://127.0.0.1:1/cv.js?px=' + PX + '"></script>'); await p3.waitForTimeout(500);
check(!errs3.length && await p3.evaluate(() => document.getElementById('ok').textContent) === 'fine', "unreachable tag host: the member's page still works, no errors");
} finally { await browser.close(); pagesSrv.close(); }
browserPart = true;
} else { results.push('SKIP browser part (no Playwright at ' + PW + ')'); }
} catch (e) {
check(false, 'run', e && e.stack || String(e));
} finally {
srv.kill(); await sleep(500);
const fails = results.filter(r => r.startsWith('FAIL'));
console.log(results.join('\n'));
console.log('\n' + (results.length - fails.length) + ' passed, ' + fails.length + ' failed' + (fails.length ? ' (server log: ' + logFile + ')' : ''));
if (!fails.length) try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
process.exit(failed ? 1 : 0);
}
+3
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
# 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 loginqueue # prepaid login-slot queue: ads.js unit test (two app copies promoting at once) + HTTP/Ads-screen e2e on a local copy
# bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, throwaway data)
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
@@ -42,6 +43,8 @@ elif [ "$MODE" = "sponsorfollow" ]; then
elif [ "$MODE" = "loginqueue" ]; then
node qa/loginqueue.test.cjs || status=1
node qa/loginqueue.e2e.mjs || status=1
elif [ "$MODE" = "convpixel" ]; then
node qa/convpixel.test.mjs || status=1
elif [ "$MODE" = "lsid" ]; then
node qa/lsid-pixel.test.mjs || status=1
elif [ "$MODE" = "kb" ]; then
+1 -1
View File
@@ -101,7 +101,7 @@ if (MODE === 'member' || MODE === 'all') {
flush(bag, L + 'sign-in');
const username = async () => { if (await page.$('#dlg-username')) { await page.fill('#dlg-username', 'qawalker'); await page.click('#dlgOk'); await page.waitForTimeout(1200); } };
// every Control Room screen on the rail
for (const sc of ['links', 'sources', 'pages', 'zones', 'ads', 'credits', 'reports', 'team', 'wallet', 'help']) {
for (const sc of ['links', 'sources', 'pages', 'zones', 'ads', 'credits', 'reports', 'conversions', 'team', 'wallet', 'help']) {
const label = L + '/' + sc;
await page.goto(LOCAL + '/' + sc, { waitUntil: 'networkidle' }); await page.waitForTimeout(800); await username(); await hide(page);
if (await page.$('#siEmail')) note('bug', label, 'asked to sign in again');
+25 -4
View File
@@ -12,6 +12,7 @@ const path = require('path');
const crypto = require('crypto');
let DATA_DIR = null, geo = null, OWN_HOSTS = () => [], SOURCES = null; // SOURCES = sources.js (traffic sources, 2026-10-12)
let WANTS_CLICK_ID = () => false; // conversion pixel (2026-10-23): owner -> true when they have a goal, so their destinations get ?lsclk=
const DAY = 86400000;
const J = {
db: null,
@@ -19,7 +20,7 @@ const J = {
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, rotations: [], hits: [], conv: [] }; } if (!this.db.conv) this.db.conv = []; },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }
};
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; J.load(); }
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; J.load(); }
const norm = e => String(e || '').trim().toLowerCase();
const newCode = () => { const a = 'abcdefghjkmnpqrstuvwxyz23456789'; let s = ''; for (let i = 0; i < 6; i++) s += a[crypto.randomInt(a.length)]; return s; };
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
@@ -168,13 +169,18 @@ async function resolve(code, req) {
const d = (r.paused || off) ? null : pick(r, cell);
const url = d ? d.url : (r.fallback || null);
const ref = String(req.headers.referer || ''); let src = 'direct'; try { if (ref) src = new URL(ref).hostname.replace(/^www\./, ''); } catch (e) {}
// an ad click that led here (conversion pixel, 2026-10-23): InstantAdPay and LinkSpin ad clicks append ?lsclk=<i|a + 11 hex>.
// The spin-link click inherits the ad as its source; the goal pixel credits the ad campaign AND this link.
let ac = ''; try { const v = String(new URL(req.url, 'http://x').searchParams.get('lsclk') || ''); if (/^[ai][a-f0-9]{11}$/.test(v)) ac = v; } catch (e) {}
if (ac) src = ac[0] === 'i' ? 'InstantAdPay ad' : 'LinkSpin ad';
const device = /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop';
// click ids and sub ids that rode in on the link (tracker / traffic-network params), kept per click
const q = {}; try { const sp = new URL(req.url, 'http://x').searchParams; let n = 0; for (const [k, val] of sp) { const key = String(k).toLowerCase(); if (n >= 20) break; if (/^(clickid|click_id|cid|subid|sub_id|s[1-5]|sub[1-5]|t[1-5]|aff_sub[1-5]?|utm_(source|medium|campaign|term|content)|src|source|campaign|zone|placement|cost|creative|site|banner|keyword|geo|os|browser|device|carrier|format|external_id|visitor_id)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } } catch (e) {}
const id = crypto.randomBytes(6).toString('hex').slice(0, 10);
// sr = the traffic source attached to the link at click time, so the network that sent this click is the one told about its conversion
J.db.hits.push({ id, r: r.id, d: d ? d.id : 0, ts: Date.now(), v, c: country, s: src, dv: device, bot: bot ? 1 : 0, oh: off ? 1 : undefined, q: Object.keys(q).length ? q : undefined, sr: r.sourceId || undefined });
if (J.db.hits.length > 200000) J.db.hits = J.db.hits.slice(-150000);
J.db.hits.push({ id, r: r.id, d: d ? d.id : 0, ts: Date.now(), v, c: country, s: src, dv: device, bot: bot ? 1 : 0, oh: off ? 1 : undefined, q: Object.keys(q).length ? q : undefined, sr: r.sourceId || undefined, ac: ac || undefined });
if (HIT_IX) HIT_IX.set(id, J.db.hits.length - 1);
if (J.db.hits.length > 200000) { J.db.hits = J.db.hits.slice(-150000); HIT_IX = null; }
J.save();
let out = url;
if (out) {
@@ -183,6 +189,9 @@ async function resolve(code, req) {
out = out.replace(/\{([a-z0-9_]{1,24})\}/gi, (m, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()]));
// our own pages get the click id automatically, so a join can be matched back to this click without any macro
try { const t = new URL(out); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid')) { t.searchParams.set('lsid', id); out = t.toString(); } } catch (e) {}
// conversion pixel (2026-10-23): when the owner tracks goals, or the click came from an ad, the destination also gets
// ?lsclk=<this click id> for the landing tag (/t.js) to keep. Existing params stay; an lsclk already there is left alone.
if (!bot && (ac || WANTS_CLICK_ID(r.owner))) { try { const t = new URL(out); if (!t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {} }
}
return { url: out, dest: d, rotation: r, lsid: id };
}
@@ -244,6 +253,18 @@ async function stats(owner, id) {
return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length, best: bestHours(r), offHours: hits.filter(h => h.oh).length,
subs: Object.entries(subs).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
}
// conversion pixel (2026-10-23): a click by id, with its link and destination. An index over the hits array, rebuilt lazily
// after new hits (the pixel asks rarely; a rebuild over 200k hits is a few ms).
let HIT_IX = null;
function hitById(id, again) {
if (!HIT_IX) { HIT_IX = new Map(); for (let i = 0; i < J.db.hits.length; i++) HIT_IX.set(J.db.hits[i].id, i); }
let i = HIT_IX.get(String(id)); let h = i == null ? null : J.db.hits[i];
if (i != null && (!h || h.id !== String(id))) { HIT_IX = null; return again ? null : hitById(id, true); } // the array moved under the index (trim, demo sweep): rebuild once
if (!h) return null;
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
const d = (r.destinations || []).find(x => x.id === h.d);
return { hit: h, owner: r.owner, rotation: { id: r.id, code: r.code, name: r.name }, destUrl: d ? d.url : (r.fallback || '') };
}
function totals() { return { rotations: J.db.rotations.length, hits: J.db.hits.length }; }
// ── demo spins (home page, 2026-10-07) ─────────────────────────────────────────────────────────────────────
@@ -294,5 +315,5 @@ function adminAll() {
destinations: (r.destinations || []).map(d => ({ id: d.id, url: d.url, label: d.label || '', weight: d.weight, active: !!d.active, autoPaused: d.autoPaused || 0, health: d.health ? { state: d.health.state, note: d.health.note || '', checkedAt: d.health.checkedAt || 0 } : null })),
hits: o.hits, hits7: o.hits7, bots: o.bots, conversions: cv[r.id] || 0 }; });
}
module.exports = { init, adminAll, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday,
module.exports = { init, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday,
pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource };
+88 -5
View File
@@ -63,6 +63,7 @@ const carry = require('./carry'); // sponsor carry-over: engine acti
const rotator = require('./rotator');
const health = require('./health'); // destination health checks + auto-pause (2026-10-10)
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29)
const convtrack = require('./convtrack'); // conversion pixel: goals, ad click ids, landing tag + goal pixel, per-goal reports (2026-10-23)
const bannerspin = require('./bannerspin'); // Banner Spin: one image URL + one click URL rotating up to 25 banners (2026-10-18)
const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12)
const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/<slug> (2026-09-29)
@@ -657,7 +658,8 @@ async function boot() {
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources });
rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources, wantsClickId: owner => convtrack.goalsOf(owner).length > 0 });
convtrack.init({ dataDir: DATA_DIR, rotator, campaignOf: id => ads.campaignById(id) });
// destination health: every 30 min, first pass 2 min after boot; a pause lands in the owner's on-site inbox (same path as the payment notices)
health.init({ rotator, bannerspin, dataDir: DATA_DIR, notify: (email, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, html) });
setTimeout(() => health.tick().catch(e => console.error('health', e.message)), 2 * 60 * 1000);
@@ -799,6 +801,23 @@ function readRaw(req, maxBytes) {
req.on('error', reject);
});
}
// conversion pixel (2026-10-23): the click-id cookie on our own host. SameSite=None so the goal pixel (a third-party image
// on the member's thank-you page) can still send it where the browser allows third-party cookies; 30 days like the window.
// the image pixel cannot read the thank-you page's address, but a browser that sends the full referrer hands it to us
function refClickId(req) { try { const r = new URL(String(req.headers.referer || '')); const v = r.searchParams.get('lsclk') || r.searchParams.get('lsid') || ''; return /^[a-z0-9]{6,24}$/i.test(v) ? v : ''; } catch (e) { return ''; } }
function clickCookie(id) { return 'ls.clk=' + id + '; Path=/; Max-Age=2592000; ' + (IS_PROD ? 'SameSite=None; Secure' : 'SameSite=Lax'); }
// an ad click: record a click id for the campaign and append ?lsclk=<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.
async function adClickTarget(campOrId, url, req, extra) {
try {
const camp = typeof campOrId === 'object' ? campOrId : await ads.campaignById(campOrId); if (!camp) return { url };
let self = false; try { const s = await auth.fromRequest(req); self = !!(s && s.email && String(s.email).toLowerCase() === String(camp.owner || '').toLowerCase()); } catch (e) {}
const id = convtrack.recordAdClick(camp, req, Object.assign({ country: viewerGeo(req).cc || '', self }, extra || {})); if (!id) return { url };
let out = url; try { const t = new URL(url); if (!t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {}
return { url: out, cookie: clickCookie(id), id };
} catch (e) { console.error('ad click id', e.message); return { url }; }
}
function readBody(req) {
return new Promise((resolve, reject) => {
let d = ''; let n = 0;
@@ -1115,7 +1134,7 @@ function linkSitePage(host, page) {
home: '<h1>' + H + '</h1><p>This domain is a link forwarding service operated by ' + brand + ', a member advertising network. Links on this domain forward visitors in one step to pages published by our members and their partners.</p><p>We do not host the pages you land on, and we do not collect payment information here. If a link forwarded you somewhere you did not expect, or to content that looks unsafe, tell us on the <a href="/abuse">report page</a> and we will pull the link.</p><h2>What we record</h2><p>When a link is followed we record the day, the country, the referring site, the device type and a one-day anonymous visitor token. We do not store your IP address or any personal data. Details are in the <a href="/privacy">privacy policy</a>.</p>',
disclosure: '<h1>Affiliate and advertising disclosure</h1><p>Links forwarded through ' + H + ' may be affiliate links or paid advertisements. The member who published a link may earn a commission or advertising credit if you buy something or sign up on the page you land on. This never changes the price you pay.</p><p>' + brand + ' itself is an advertising platform. Members buy ad packages and earn commissions when people they referred buy ad packages. No income is guaranteed to anyone; results depend on effort, and any earnings examples on member pages are illustrations, not promises.</p><p>The pages you are forwarded to belong to their publishers. We are not responsible for their claims, and we remove links that are reported and found to violate our <a href="/terms">terms</a>.</p>',
terms: '<h1>Terms of use</h1><p>By following a link on ' + H + ' you agree to these terms.</p><h2>The service</h2><p>' + H + ' forwards visitors to destinations chosen by ' + brand + ' members. We provide the forwarding only. We do not endorse, verify or control the destination pages, and we are not a party to any transaction you make there.</p><h2>Acceptable use</h2><p>Members may not forward visitors to content that is illegal, deceptive, malicious, adult, or that impersonates another business. Links that violate this are removed and the member\'s account is closed. Automated access to this domain is not permitted except by search engines.</p><h2>No warranty</h2><p>The service is provided as is. We do not guarantee that any link will be available, and we are not liable for the content, availability or conduct of destination sites.</p><h2>Contact</h2><p>Questions about these terms: <a href="https://linkspin.co">linkspin.co</a>.</p>',
privacy: '<h1>Privacy policy</h1><p>This policy covers ' + H + ' and the link forwarding service on it.</p><h2>What we collect</h2><p>When you follow a link we record the date, your country (derived from your network address and then discarded), the site that referred you, whether you are on a phone or a computer, and an anonymous visitor token that changes every day and cannot be traced back to you. We do not store your IP address, your name, your email address or any account information on this domain.</p><h2>Cookies</h2><p>This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.</p><h2>Why we collect it</h2><p>So members can see how many people followed their links and from where. Counts are shown to the member who published the link, in aggregate, and to nobody else.</p><h2>Retention</h2><p>Link statistics are kept for up to thirteen months and then deleted.</p><h2>Your rights</h2><p>Because we hold no personal data on this domain there is nothing to access or delete here. For anything involving a ' + brand + ' member account, contact us through <a href="https://linkspin.co">linkspin.co</a>.</p>',
privacy: '<h1>Privacy policy</h1><p>This policy covers ' + H + ' and the link forwarding service on it.</p><h2>What we collect</h2><p>When you follow a link we record the date, your country (derived from your network address and then discarded), the site that referred you, whether you are on a phone or a computer, and an anonymous visitor token that changes every day and cannot be traced back to you. We do not store your IP address, your name, your email address or any account information on this domain.</p><h2>Click ids</h2><p>If the member who owns the link tracks goals, or you arrived from an ad, the page you are forwarded to gets a random click id in its address (<code>lsclk</code>). The site you land on may keep it for 30 days to count whether the visit led to a sign-up or a sale. It identifies the click, not you.</p><h2>Cookies</h2><p>This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.</p><h2>Why we collect it</h2><p>So members can see how many people followed their links and from where. Counts are shown to the member who published the link, in aggregate, and to nobody else.</p><h2>Retention</h2><p>Link statistics are kept for up to thirteen months and then deleted.</p><h2>Your rights</h2><p>Because we hold no personal data on this domain there is nothing to access or delete here. For anything involving a ' + brand + ' member account, contact us through <a href="https://linkspin.co">linkspin.co</a>.</p>',
abuse: '<h1>Report a link</h1><p>If a link on ' + H + ' forwarded you to a page that is deceptive, unsafe, adult, or impersonates a business, tell us. We review every report and pull the link first, then ask questions.</p><p>Send the full link you clicked (it starts with https://' + H + '/r/ or https://' + H + '/c/) and what you saw, or the address of a banner image you want reviewed, to the support contact on <a href="https://linkspin.co">linkspin.co</a>. Reports are usually handled the same day.</p>',
gone: '<h1>That link is not active</h1><p>The link you followed has been removed or has expired. Nothing was recorded. If you were expecting a specific page, ask the person who shared the link for a fresh one.</p>'
};
@@ -1169,7 +1188,7 @@ const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://x');
const p = u.pathname;
// zone endpoints run on other people's sites and show only ad creatives, so they pass the curtain
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18)
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p === '/t.js' || p === '/t.gif' || p === '/cv.gif' || p === '/cv.js' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18)
// support must reach everyone, invited or not (2026-10-16): someone locked out or not yet let in is exactly who needs it
if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
@@ -1213,6 +1232,26 @@ const server = http.createServer(async (req, res) => {
if (!am.vid) h['Set-Cookie'] = audiences.cookieHeader(audiences.newVid(), IS_PROD);
res.writeHead(200, h); return res.end(JSON.stringify({ ad }));
}
// -- conversion pixel (2026-10-23): /t.js the landing tag, /t.gif its beacon, /cv.gif + /cv.js the goal pixel. Any origin,
// never cached, always a 1x1 gif (the member's page never sees an error). X-LS-Result says what happened (tests, debugging).
if ((p === '/t.js' || p === '/cv.js') && (req.method === 'GET' || req.method === 'HEAD')) {
try { const body = fs.readFileSync(path.join(PUBLIC_DIR, p.slice(1))); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff' }); return res.end(req.method === 'HEAD' ? '' : body); } catch (e) { res.writeHead(404); return res.end(); }
}
if ((p === '/t.gif' || p === '/cv.gif') && req.method === 'GET') {
const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length), 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'X-LS-Result', 'X-Robots-Tag': 'noindex' };
const px = String(u.searchParams.get('px') || '');
try {
if (p === '/t.gif') {
const id = convtrack.isPx(px) ? convtrack.landing(px, String(u.searchParams.get('c') || ''), req) : null;
if (id) h['Set-Cookie'] = clickCookie(id); h['X-LS-Result'] = id ? 'stored' : 'ignored';
} else if (convtrack.isPx(px)) {
const r = convtrack.record({ px, goal: u.searchParams.get('goal'), value: u.searchParams.get('value'), c: String(u.searchParams.get('c') || u.searchParams.get('lsclk') || u.searchParams.get('lsid') || u.searchParams.get('clickid') || refClickId(req) || ''), m: u.searchParams.get('m'), test: u.searchParams.get('test') === '1' }, req, parseCookies(req));
h['X-LS-Result'] = r.result + (r.method ? ';' + r.method : '');
if (r.result === 'counted' && !r.conv.self) postbacks.fire(r.conv.owner, r.conv.goal, Object.assign(convtrack.postbackCtx(r), { goal: true })).catch(e => console.error('goal postback', e.message));
} else h['X-LS-Result'] = 'unknown';
} catch (e) { console.error('conversion pixel', e.message); h['X-LS-Result'] = 'error'; }
res.writeHead(200, h); return res.end(PIXEL_GIF);
}
// audience pixel: 1x1 gif, sets/refreshes the visitor cookie, records the hit (30-day membership)
if (p === '/p.gif' && req.method === 'GET') {
const a = String(u.searchParams.get('a') || ''); const vid = audiences.cookieVid(req); const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length) };
@@ -1229,7 +1268,7 @@ const server = http.createServer(async (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src https://www.networkadspace.com https://networkadspace.com 'unsafe-inline'; img-src https: http: data:; style-src 'unsafe-inline'; frame-src https: http:; frame-ancestors *; base-uri 'none'", 'Referrer-Policy': 'no-referrer' }); return res.end(html);
}
if (p === '/api/zone/seen' && (req.method === 'GET' || req.method === 'POST')) { await zones.seen(u.searchParams.get('i'), req); res.writeHead(204, corsCreds(req)); return res.end(); }
{ const zm = /^\/api\/zone\/click\/([a-f0-9]{12})$/.exec(p); if (zm && req.method === 'GET') { const target = await zones.click(zm[1]); res.writeHead(302, { Location: target || '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); } }
{ const zm = /^\/api\/zone\/click\/([a-f0-9]{12})$/.exec(p); if (zm && req.method === 'GET') { let ck = null; const target = await zones.click(zm[1], async (camp, url) => { const t = await adClickTarget(camp, url, req, { placement: 'zone' }); ck = t.cookie; return t.url; }); const zh = { Location: target || '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }; if (ck) zh['Set-Cookie'] = ck; res.writeHead(302, zh); return res.end(); } }
// -- publisher program (2026-10-10): the public offer for site owners who carry zones, and its live "Network right now"
// strip (7-day totals from zones.js, cached a minute). App host only; the link and pages domains stay single-purpose.
// Today's POL price in US dollars for the member pages (Marty, 2026-10-22, same as InstantAdPay): the contract's own package
@@ -2556,6 +2595,29 @@ const server = http.createServer(async (req, res) => {
let bsum = null; try { bsum = await bannerspin.summary(s.email, days); } catch (e) { console.error('bannerspin summary', e.message); }
return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, bannerSpins: bsum, days: spins.days, range: days }), { 'Cache-Control': 'no-store' });
}
// -- conversion pixel (2026-10-23): goals, per-goal reports, CSV, test. GET and POST (the shell's api() always POSTs).
if (p === '/api/my/conversions' && (req.method === 'GET' || req.method === 'POST')) {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = req.method === 'POST' ? await readBody(req).catch(() => ({})) : {};
const days = Math.max(1, Math.min(365, Number(b.days || u.searchParams.get('days')) || 30));
const r = await convtrack.report(s.email, days, { sourceMeta: sources.meta ? sources.meta(s.email) : {} });
return json(res, 200, Object.assign(r, { host: SITE_HOST, base: (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, limits: convtrack.LIMITS, windowDays: 30, softHours: 24 }), { 'Cache-Control': 'no-store' });
}
if (p === '/api/my/conversions/goals' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req).catch(() => ({})); const r = convtrack.createGoal(s.email, b); return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/conversions\/goals\/(px[a-f0-9]{10})$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req).catch(() => ({})); const r = b.test ? convtrack.testGoal(s.email, m[1]) : convtrack.updateGoal(s.email, m[1], b); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/conversions.csv' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const days = Math.max(1, Math.min(365, Number(u.searchParams.get('days')) || 30));
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="linkspin-conversions-' + days + 'd.csv"', 'Cache-Control': 'no-store' }));
return res.end(convtrack.csv(s.email, days));
}
// -- traffic sources (2026-10-12). Every route takes GET and POST: the shell's api() helper always POSTs.
if (p === '/api/sources/catalog' && (req.method === 'GET' || req.method === 'POST')) return json(res, 200, { catalog: sources.catalog(), keys: sources.KEYS }, { 'Cache-Control': 'public, max-age=300' });
if (p === '/api/my/sources' && (req.method === 'GET' || req.method === 'POST')) {
@@ -2655,6 +2717,25 @@ const server = http.createServer(async (req, res) => {
return json(res, 200, { ok: true, proto: SF.PROTO, rows: rows.length, imported: n, shells, updated, followed, followKept: kept, registry: await registry.count() });
} finally { carry.unhold(held); }
}
// -- conversion pixel, InstantAdPay side (2026-10-23): its ad clicks arrive here (signed, upsert by id), and its members'
// goals live on their LinkSpin account (same email): summary for the Campaigns rows, create / update / remove / test.
if (p === '/api/partner/clicks' && req.method === 'POST') {
const sg = await readPartnerSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
return json(res, 200, { ok: true, n: convtrack.importClicks(sg.body.clicks) });
}
if (p === '/api/partner/conv' && req.method === 'POST') {
const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
const b = sg.body; const email = String(b.email || '').trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) || email.length > 190) return json(res, 400, { error: 'Which member?' });
let r;
if (b.op === 'summary') r = Object.assign(convtrack.partnerSummary(email, b.days), { host: SITE_HOST });
else if (b.op === 'create') r = convtrack.createGoal(email, { name: b.name, value: b.value });
else if (b.op === 'update') r = convtrack.updateGoal(email, b.px, { name: b.name, value: b.value === null ? 0 : b.value }); // null = clear the default (InstantAdPay sends it for an empty box)
else if (b.op === 'remove') r = convtrack.updateGoal(email, b.px, { remove: true });
else if (b.op === 'test') r = convtrack.testGoal(email, b.px);
else return json(res, 400, { error: 'op must be summary, create, update, remove or test' });
return json(res, r.error ? 400 : 200, r);
}
// -- sponsor check between LinkSpin and InstantAdPay (2026-10-22, sponsorfollow.js). Partner side: InstantAdPay reads our
// facts and, on an admin's pick in ITS Sponsor check, asks us to apply a sponsor (refused when the member is bound here).
if (p === '/api/partner/sponsor-facts' && req.method === 'POST') {
@@ -3388,7 +3469,8 @@ const server = http.createServer(async (req, res) => {
const target = await ads.click(m[1]);
if (!target) { res.writeHead(404, baseHeaders()); return res.end(); }
coach.recordClick(m[1], req.headers.referer); // where the click happened
res.writeHead(302, baseHeaders({ Location: target }));
const t = await adClickTarget(m[1], target, req); // conversion pixel: click id recorded + ?lsclk= on the target (2026-10-23)
res.writeHead(302, baseHeaders(Object.assign({ Location: t.url }, t.cookie ? { 'Set-Cookie': t.cookie } : {})));
return res.end();
}
if (p === '/api/my/audiences' && req.method === 'GET') {
@@ -3779,6 +3861,7 @@ const server = http.createServer(async (req, res) => {
}
if (p === '/links') return sendFile(res, path.join(PUBLIC_DIR, 'links.html')); // Control Room: the links workspace, first screen of the new front end (2026-09-29)
if (p === '/reports') return sendFile(res, path.join(PUBLIC_DIR, 'reports.html'));
if (p === '/conversions') return sendFile(res, path.join(PUBLIC_DIR, 'conversions.html')); // Control Room: conversion pixel goals + per-goal reports (2026-10-23)
if (p === '/pages') return sendFile(res, path.join(PUBLIC_DIR, 'pages.html'));
if (p === '/zones') return sendFile(res, path.join(PUBLIC_DIR, 'zones.html'));
if (p === '/sources') return sendFile(res, path.join(PUBLIC_DIR, 'sources.html')); // Control Room: traffic sources, network macros + postbacks (2026-10-12)
+2 -2
View File
@@ -116,11 +116,11 @@ async function seen(impId, req) {
}
J.save(); return { ok: true };
}
async function click(impId) {
async function click(impId, decorate) { // decorate(campaignId, url) -> url: the conversion pixel's click id (2026-10-23)
const imp = J.db.imps.find(i => i.id === String(impId)); if (!imp) return null;
imp.k = 1; J.save();
if (imp.house || !imp.camp) return 'https://' + siteHost + '/';
try { return (await ads.click(imp.camp)) || ('https://' + siteHost + '/'); } catch (e) { return 'https://' + siteHost + '/'; }
try { const url = await ads.click(imp.camp); if (!url) return 'https://' + siteHost + '/'; return decorate ? ((await decorate(imp.camp, url).catch(() => url)) || url) : url; } catch (e) { return 'https://' + siteHost + '/'; }
}
// -- admin: every zone with its owner, site, mix and status; pause/resume
async function adminList() { return J.db.zones.map(z => Object.assign(pubZone(z), { owner: z.owner, note: z.adminNote || '' })).sort((a, b) => b.views30 - a.views30); }