// LinkSpin tracking on member text ads (Marty 2026-11-15, the DownlineHydra module generalized: LinkSpin /api/partner//links). // When a member saves their text ad, LinkSpin makes (or updates) a tracked link for it on that member's own LinkSpin account (every // hub member has one through join-all), tagged with the account's "ViralAdSource" source and the ad id as a sub-id (?s1=&placement=), // so LinkSpin Reports show the ad's clicks. The ad's public link (/go/) then sends to the tracked link, which lands on the member's // own link. Per ad the member can switch tracking off ("Track with LinkSpin", default on): then /go/ sends straight to their link. // Fail soft: if LinkSpin does not answer (or does not know the endpoint yet), the ad works exactly as before with its plain link, // and the sweep tries again later. A tracked link is used only while it points at the ad's current link (an edit never sends // traffic to an old destination). Links with {clickid} / {placement} macros are not tracked (they are filled here on every click). // Account: by network username (ViralAdSource never stores emails). The call: POST LS_URL/api/partner/vab/links, X-Net-Ts + X-Net-Sig = // hex HMAC-SHA256('net.v1.' + ts + newline + raw body) with NETWORK_SSO_SECRET (the Downline Banners Banner Spins pattern). // ensureAd(ad) -> updates ad.ls { code, link, url, at } or ad.lsErr / ad.lsTry; saves through the store // clicks(username) -> { : { hits, hits30, unique30 } } | null (cached 5 minutes per member) // dest(ad) -> the tracked link when it is current, else null // "Use one of my spin links" (Marty 2026-11-15): the same endpoint with { username, op: 'spins' } lists the member's own LinkSpin spin // links (never another account's, never the tracked links made for ads). An ad whose link is the member's own spin link (ad.spin = // its code) is already tracked on LinkSpin, so it never gets the tracked-link wrapper. A LinkSpin /r/ link is accepted as an // ad link ONLY when LinkSpin confirms it belongs to the signed-in member (checkSpin); the network's own fixed links stay allowed. // spins(username) -> { account, host, hosts, spins: [{ code, name, url, destinations, paused }] } | { error } // checkSpin(url, username) -> { spin: false } (not a LinkSpin spin link) | { spin: true, code } | { error } 'use strict'; const crypto = require('crypto'); let C = null, store = null; const st = { ensured: 0, failed: 0, noAccount: 0, lastError: null, lastOkAt: 0, sweeps: 0 }; const cache = new Map(); const MACRO = /\{(clickid|placement)\}|%7B(clickid|placement)%7D/i; const SITE = String(process.env.LS_PARTNER || 'vas').trim(); // LinkSpin partner path (/api/partner//links). 'vas' needs LinkSpin's PARTNER_LINKS entry first const NET_CODES = new Set(Object.values(require('./netsites').CODES)); // the network's fixed LinkSpin links (admin account), not member spin links const lsHosts = new Set(['linkspin.app']); // hosts a LinkSpin /r/ link answers on, learned from every spins answer function init(cfg, st0) { C = cfg; store = st0; } // learn LinkSpin's link hosts (public; sent even when no account matches) so a foreign spin link is spotted after a restart too let hostsAt = 0; async function warmHosts() { if (!base() || String(process.env.NETWORK_SSO_SECRET || '').trim().length < 32 || Date.now() - hostsAt < 3600000) return; hostsAt = Date.now(); const r = await post({ username: '', op: 'spins' }, 6000).catch(() => ({})); for (const h of Array.isArray(r.hosts) ? r.hosts : []) if (/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(String(h))) lsHosts.add(String(h).toLowerCase()); if (!Array.isArray(r.hosts)) hostsAt = Date.now() - 3000000; // no answer: try again in 10 minutes } const base = () => String(process.env.LS_TRACK_URL || (C && C.lsBase) || '').replace(/\/+$/, ''); const on = () => !!(C && process.env.LS_TRACK !== '0' && process.env.LS_TRACK !== undefined && String(process.env.NETWORK_SSO_SECRET || '').trim().length >= 32 && base()); async function post(body, ms) { const sec = String(process.env.NETWORK_SSO_SECRET || '').trim(); const raw = JSON.stringify(body); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex'); const ac = new AbortController(); const t = setTimeout(() => ac.abort(), ms || 8000); try { const r = await fetch(base() + '/api/partner/' + SITE + '/links', { method: 'POST', body: raw, signal: ac.signal, headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } }); const j = await r.json().catch(() => ({})); return r.ok ? j : { error: j.error || 'LinkSpin answered ' + r.status }; } catch (e) { return { error: 'LinkSpin did not answer.' }; } finally { clearTimeout(t); } } const ownerName = a => { const m = store.member(a.owner); return m && m.username ? String(m.username) : null; }; // what the member sees about tracking for their ad function state(a) { if (!a) return null; if (a.spin) return 'spin'; if (a.track === false) return 'off'; if (MACRO.test(String(a.link || ''))) return 'macros'; if (a.ls && a.ls.url === a.link && a.ls.link) return 'tracked'; if (!ownerName(a)) return 'no-username'; if (a.lsNoAccount && a.lsTry && Date.now() - a.lsTry < 86400000) return 'no-account'; return 'pending'; } const wants = a => a && !a.spin && a.status !== 'removed' && a.track !== false && !MACRO.test(String(a.link || '')) && !(a.ls && a.ls.url === a.link && a.ls.link) && !!ownerName(a); function dest(a) { return a && !a.spin && a.track !== false && a.ls && a.ls.link && a.ls.url === a.link && !MACRO.test(String(a.link || '')) ? a.ls.link : null; } async function ensureAd(a) { if (!on() || !wants(a)) return { skipped: true }; const username = ownerName(a); const r = await post({ username, op: 'ensure', links: [{ id: String(a.id), name: a.headline, url: a.link }] }); a.lsTry = Date.now(); if (r.error) { st.failed++; st.lastError = String(r.error).slice(0, 160); a.lsErr = st.lastError; store.saveAd(a); return r; } if (r.account === false) { st.noAccount++; a.lsNoAccount = true; delete a.lsErr; store.saveAd(a); return r; } const l = r.links && r.links[String(a.id)]; if (!l) { st.failed++; a.lsErr = String((r.errors && r.errors[String(a.id)]) || 'no link').slice(0, 160); store.saveAd(a); return r; } a.ls = { code: l.code, link: l.link, url: a.link, at: Date.now() }; delete a.lsErr; delete a.lsNoAccount; st.ensured++; st.lastOkAt = Date.now(); cache.delete(username.toLowerCase()); store.saveAd(a); return { ok: true, link: l.link }; } // the retry sweep: ads that want a tracked link and have not been tried lately (failures back off 10 minutes, no account a day) async function sweep(max) { warmHosts().catch(() => {}); if (!on()) return 0; st.sweeps++; let n = 0; const backoff = Number(process.env.LS_RETRY_MS || 600000); for (const a of store.liveAds()) { if (n >= (max || 25)) break; if (!wants(a)) continue; if (a.lsTry && Date.now() - a.lsTry < (a.lsNoAccount ? 86400000 : backoff)) continue; n++; const r = await ensureAd(a).catch(() => ({ error: 'x' })); if (r && r.error === 'LinkSpin did not answer.') break; // LinkSpin is down: stop this round } return n; } async function clicks(username) { if (!on() || !username) return null; const k = String(username).toLowerCase(); const hit = cache.get(k); if (hit && Date.now() - hit.at < Number(process.env.LS_CACHE_MS || 300000)) return hit.v; const r = await post({ username, op: 'stats' }, 3000); const v = r.error || r.account === false ? null : (r.stats || {}); cache.set(k, { at: Date.now(), v }); if (cache.size > 20000) cache.clear(); return v; } // the member's own spin links (read only) async function spins(username) { if (!base() || String(process.env.NETWORK_SSO_SECRET || '').trim().length < 32) return { error: 'The LinkSpin link is not set up yet.' }; if (!username) return { error: 'Sign in through InstantAdPay or LinkSpin once to link your LinkSpin account.' }; const r = await post({ username: String(username), op: 'spins' }, 6000); if (r.error) { st.lastError = String(r.error).slice(0, 160); return { error: 'LinkSpin did not answer just now. Try again in a minute.' }; } for (const h of (Array.isArray(r.hosts) ? r.hosts : []).concat(r.host ? [r.host] : [])) if (/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(String(h))) lsHosts.add(String(h).toLowerCase()); if (r.account === false) return { account: false, spins: [] }; const spins = (Array.isArray(r.spins) ? r.spins : []).filter(x => x && /^[a-z0-9]{4,12}$/i.test(String(x.code || '')) && /^https:\/\//.test(String(x.url || ''))) .map(x => ({ code: String(x.code).toLowerCase(), name: String(x.name || '').slice(0, 80), url: String(x.url), destinations: Number(x.destinations) || 0, paused: !!x.paused })); return { account: true, host: r.host || null, hosts: Array.from(lsHosts), spins }; } // is this ad link a LinkSpin spin link, and is it the member's own? (asked on every save of an ad link that looks like one) async function checkSpin(url, username) { let u; try { u = new URL(String(url || '')); } catch (e) { return { spin: false }; } const m = /^\/r\/([a-z0-9]{4,12})\/?$/i.exec(u.pathname); if (!m) return { spin: false }; const host = u.hostname.toLowerCase().replace(/^www\./, ''); const code = m[1].toLowerCase(); const mine = lsHosts.has(host) || (base() && (() => { try { return new URL(base()).hostname.toLowerCase() === host; } catch (e) { return false; } })()); const r = await spins(username); if (r.error) return mine ? { error: 'LinkSpin could not confirm that spin link is yours just now. ' + r.error } : { spin: false }; if (!lsHosts.has(host)) return { spin: false }; // a /r/ link on some other site: an ordinary link if (NET_CODES.has(code)) return { spin: false }; // the network's own fixed links stay allowed as before if (r.account === false) return { error: 'No LinkSpin account was found for your network username, so that spin link cannot be confirmed as yours.' }; const sp = r.spins.find(x => x.code === code); if (!sp) return { error: 'That spin link is not one of yours. Use one of your own LinkSpin spin links (pick it under "Use one of my spin links").' }; if (sp.paused) return { error: 'That spin link is paused on LinkSpin. Turn it back on there first, or pick another.' }; if (!sp.destinations) return { error: 'That spin link has no active pages on LinkSpin yet. Add a page to it there first.' }; return { spin: true, code }; } // a LinkSpin link (tracked link or the member's spin link) carries the branch: s2 = the resharer's network username, s3 = the share code, // so LinkSpin Reports show which branch brought each click and sign-up. Other links are left exactly as the member wrote them. function withBranch(url, share, resharerName) { if (!share || share.step === 0) return url; let u; try { u = new URL(String(url)); } catch (e) { return url; } const host = u.hostname.toLowerCase().replace(/^www\./, ''); if (!lsHosts.has(host)) return url; if (resharerName) u.searchParams.set('s2', String(resharerName).slice(0, 40)); u.searchParams.set('s3', share.id); return u.toString(); } function view() { return Object.assign({ on: on(), base: base(), partner: SITE }, st); } module.exports = { withBranch, init, ensureAd, sweep, clicks, dest, state, view, on, spins, checkSpin, _hosts: lsHosts, _reset: () => cache.clear() };