Conversion tracking, click side: every /api/ads/click gets a click id (i + 11 hex) appended as lsclk=<id> (existing params and hash kept, an existing lsclk never replaced, unparsable targets unchanged), the owner's own click flagged self. Rows in ad_clicks (MySQL) or a capped JSON file, pushed signed to LinkSpin /api/partner/clicks every 3 s (500 per request, retry with backoff, marked pushed only on ok). Member proxies /api/my/conversions (summary, 60 s cache), /goal (create/update/remove), /test. Admin lssync view shows push stats.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
// Conversion tracking, InstantAdPay half (Marty approved 2026-10-23). LinkSpin owns goals and conversions;
|
||||
// this module does three things:
|
||||
// record(click) every click through /api/ads/click/:id gets an id ('i' + 11 hex) that rides on the target URL as
|
||||
// ?lsclk=<id>, and the click row is stored here (MySQL ad_clicks, or a capped JSON file locally)
|
||||
// flush loop unpushed rows go to LinkSpin POST /api/partner/clicks every ~3 s, 500 per request, signed exactly
|
||||
// like lssync.js (HMAC-SHA256 of ts + newline + raw body, LS_SYNC_SECRET). A row is marked pushed only
|
||||
// after LinkSpin answers ok, so a failure keeps it for the next try (backoff up to 5 minutes).
|
||||
// LinkSpin upserts by id, so two app copies pushing the same rows during a deploy is harmless.
|
||||
// conv(email,..) the member's goals and summary through POST /api/partner/conv (op summary/create/update/remove/test),
|
||||
// summary cached 60 s per email.
|
||||
// No LS_SYNC_SECRET (or shorter than 32 chars): clicks still get ids and rows, nothing is sent.
|
||||
// The raw IP is never stored: only the soft key 's:' + sha256(ip + '|' + ua) first 20 hex, same on both sites.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let R = null, timer = null, flushing = false, fails = 0, nextAt = 0, jstate = null, saveT = null;
|
||||
const stats = { pushed: 0, lastAt: null, lastError: null, errors: 0 };
|
||||
const cache = new Map(); // email -> { at, data }
|
||||
const URL_ = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
|
||||
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
||||
const on = () => SECRET().length >= 32;
|
||||
const useDb = () => !!(R && R.db && R.db.enabled());
|
||||
const JCAP = 5000;
|
||||
const JFILE = () => path.join(R.dataDir, 'adclicks.json');
|
||||
|
||||
function init(deps) {
|
||||
R = deps;
|
||||
if (useDb()) ensureTable().catch(e => console.error('lsconv table', e.message));
|
||||
if (!timer) { timer = setInterval(() => { flush().catch(() => {}); }, 3000); if (timer.unref) timer.unref(); }
|
||||
setInterval(() => prune().catch(() => {}), 6 * 3600 * 1000).unref();
|
||||
}
|
||||
// column names checked against MySQL 8 reserved words (none of id, campaign_id, owner_email, cname, ctype, sk, country,
|
||||
// device, placement, target, spent, is_self, ts, pushed is reserved)
|
||||
async function ensureTable() {
|
||||
await R.db.q(`CREATE TABLE IF NOT EXISTS ad_clicks (
|
||||
id VARCHAR(16) PRIMARY KEY,
|
||||
campaign_id INT NOT NULL,
|
||||
owner_email VARCHAR(190) NOT NULL,
|
||||
cname VARCHAR(80) NULL,
|
||||
ctype VARCHAR(12) NULL,
|
||||
sk VARCHAR(24) NULL,
|
||||
country VARCHAR(4) NULL,
|
||||
device VARCHAR(8) NULL,
|
||||
placement VARCHAR(80) NULL,
|
||||
target VARCHAR(500) NULL,
|
||||
spent INT NOT NULL DEFAULT 0,
|
||||
is_self TINYINT NOT NULL DEFAULT 0,
|
||||
ts BIGINT NOT NULL,
|
||||
pushed TINYINT NOT NULL DEFAULT 0,
|
||||
INDEX (pushed, ts),
|
||||
INDEX (campaign_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
}
|
||||
|
||||
// ---- helpers (pure) ----
|
||||
const newId = () => 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11);
|
||||
const softKey = (ip, ua) => 's:' + crypto.createHash('sha256').update(String(ip || '') + '|' + String(ua || '')).digest('hex').slice(0, 20);
|
||||
const deviceOf = ua => /Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/i.test(String(ua || '')) ? 'mobile' : 'desktop';
|
||||
function placementOf(referer) {
|
||||
try { const u = new URL(String(referer || '')); if (!/^https?:$/.test(u.protocol)) return null; return (u.host.replace(/^www\./, '') + u.pathname.replace(/\/+$/, '')).replace(/[^\w.\-\/:]/g, '').slice(0, 80) || null; }
|
||||
catch (e) { return null; }
|
||||
}
|
||||
// append lsclk=<id> without touching anything already in the URL (string insert keeps the original encoding of every
|
||||
// existing param); an existing lsclk is never replaced; a URL that does not parse goes out unchanged
|
||||
function withClickId(target, id) {
|
||||
const t = String(target || '');
|
||||
let u; try { u = new URL(t); } catch (e) { return t; }
|
||||
if (!/^https?:$/.test(u.protocol) || u.searchParams.has('lsclk')) return t;
|
||||
const hashAt = t.indexOf('#'); const base = hashAt >= 0 ? t.slice(0, hashAt) : t; const hash = hashAt >= 0 ? t.slice(hashAt) : '';
|
||||
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
|
||||
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
|
||||
}
|
||||
|
||||
// ---- storage ----
|
||||
function jload() { if (jstate) return jstate; try { jstate = JSON.parse(fs.readFileSync(JFILE(), 'utf8')); if (!Array.isArray(jstate.rows)) throw 0; } catch (e) { jstate = { rows: [] }; } return jstate; }
|
||||
function jsave() { if (saveT) return; saveT = setTimeout(() => { saveT = null; try { fs.writeFileSync(JFILE(), JSON.stringify(jload())); } catch (e) {} }, 500); }
|
||||
function jcap() { const st = jload(); if (st.rows.length <= JCAP) return; let drop = st.rows.length - JCAP; st.rows = st.rows.filter(r => !(drop > 0 && r.pushed && drop--)); if (st.rows.length > JCAP) st.rows = st.rows.slice(-JCAP); }
|
||||
|
||||
// c = the campaign (ads.campaignById shape); returns the stored row
|
||||
async function record(c, req, opts) {
|
||||
const o = opts || {};
|
||||
const ip = o.ip || String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
|
||||
const ua = String(req.headers['user-agent'] || '');
|
||||
const row = { id: newId(), camp: Number(c.id), cname: String(c.name || c.title || '').slice(0, 80) || null, type: String(c.type || '').slice(0, 12) || null,
|
||||
owner: String(c.owner || '').toLowerCase(), ts: Date.now(), sk: softKey(ip, ua), c: o.country ? String(o.country).slice(0, 4) : null, dv: deviceOf(ua),
|
||||
pl: placementOf(req.headers.referer), target: String(o.target || c.targetUrl || '').slice(0, 500), spent: Math.max(0, Math.round(Number(c.spent || 0) + Number(c.accrued || 0))), self: o.self ? 1 : 0 };
|
||||
if (useDb()) {
|
||||
await R.db.q('INSERT INTO ad_clicks (id, campaign_id, owner_email, cname, ctype, sk, country, device, placement, target, spent, is_self, ts, pushed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0)',
|
||||
[row.id, row.camp, row.owner, row.cname, row.type, row.sk, row.c, row.dv, row.pl, row.target, row.spent, row.self, row.ts]);
|
||||
} else { const st = jload(); st.rows.push(Object.assign({ pushed: 0 }, row)); jcap(); jsave(); }
|
||||
return row;
|
||||
}
|
||||
const fromDb = r => ({ id: r.id, camp: Number(r.campaign_id), cname: r.cname, type: r.ctype, owner: r.owner_email, ts: Number(r.ts), sk: r.sk, c: r.country, dv: r.device, pl: r.placement, target: r.target, spent: Number(r.spent) || 0, self: Number(r.is_self) ? 1 : 0 });
|
||||
async function unpushed(n) {
|
||||
if (useDb()) return (await R.db.q('SELECT * FROM ad_clicks WHERE pushed=0 ORDER BY ts LIMIT ?', [n])).map(fromDb);
|
||||
return jload().rows.filter(r => !r.pushed).slice(0, n).map(r => { const x = Object.assign({}, r); delete x.pushed; return x; });
|
||||
}
|
||||
async function markPushed(ids) {
|
||||
if (!ids.length) return;
|
||||
if (useDb()) { await R.db.q('UPDATE ad_clicks SET pushed=1 WHERE id IN (?)', [ids]); return; }
|
||||
const set = new Set(ids); for (const r of jload().rows) if (set.has(r.id)) r.pushed = 1; jsave();
|
||||
}
|
||||
async function prune() { // click rows only matter for the 30-day window; keep 120 days for questions
|
||||
const cut = Date.now() - 120 * 86400e3;
|
||||
if (useDb()) await R.db.q('DELETE FROM ad_clicks WHERE pushed=1 AND ts<?', [cut]);
|
||||
else { const st = jload(); const n = st.rows.length; st.rows = st.rows.filter(r => !(r.pushed && r.ts < cut)); if (st.rows.length !== n) jsave(); }
|
||||
}
|
||||
|
||||
// ---- LinkSpin calls ----
|
||||
async function signedPost(pth, body, timeoutMs) {
|
||||
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(URL_() + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 15000) });
|
||||
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
|
||||
if (!r.ok) { const e = new Error((j && j.error) || ('linkspin ' + r.status)); e.status = r.status; e.plain = !!(j && j.error); throw e; }
|
||||
return j || {};
|
||||
}
|
||||
async function flush() {
|
||||
if (!on() || flushing || Date.now() < nextAt) return { skipped: true };
|
||||
flushing = true; let sent = 0;
|
||||
try {
|
||||
for (let round = 0; round < 20; round++) { // drain a backlog, 500 at a time
|
||||
const rows = await unpushed(500); if (!rows.length) break;
|
||||
const res = await signedPost('/api/partner/clicks', { clicks: rows }, 20000);
|
||||
if (!res || res.ok !== true) throw new Error('linkspin answered without ok');
|
||||
await markPushed(rows.map(r => r.id)); sent += rows.length; stats.pushed += rows.length; stats.lastAt = Date.now();
|
||||
if (rows.length < 500) break;
|
||||
}
|
||||
fails = 0; nextAt = 0; return { sent };
|
||||
} catch (e) {
|
||||
fails++; stats.errors++; stats.lastError = e.message; nextAt = Date.now() + Math.min(300000, 3000 * Math.pow(2, Math.min(fails, 7)));
|
||||
if (fails <= 3 || fails % 20 === 0) console.error('lsconv push', e.message);
|
||||
return { error: e.message, sent };
|
||||
} finally { flushing = false; }
|
||||
}
|
||||
// op summary is cached 60 s per email; any write clears that email's cache
|
||||
async function summary(email, fresh) {
|
||||
const e = String(email || '').toLowerCase();
|
||||
const hit = cache.get(e); if (!fresh && hit && Date.now() - hit.at < 60000) return hit.data;
|
||||
const data = await signedPost('/api/partner/conv', { op: 'summary', email: e, days: 30 }, 8000);
|
||||
cache.set(e, { at: Date.now(), data }); if (cache.size > 2000) cache.delete(cache.keys().next().value);
|
||||
return data;
|
||||
}
|
||||
async function goalOp(email, op, fields) {
|
||||
const e = String(email || '').toLowerCase();
|
||||
if (!['create', 'update', 'remove', 'test'].includes(op)) throw new Error('Unknown action.');
|
||||
const body = Object.assign({ op, email: e }, fields || {});
|
||||
const out = await signedPost('/api/partner/conv', body, 10000);
|
||||
cache.delete(e); return out;
|
||||
}
|
||||
function adminView() { return { on: on(), url: URL_(), pushed: stats.pushed, lastAt: stats.lastAt, errors: stats.errors, lastError: stats.lastError, fails, nextAt: nextAt || null }; }
|
||||
module.exports = { init, record, flush, summary, goalOp, withClickId, softKey, placementOf, deviceOf, newId, adminView, on };
|
||||
@@ -48,6 +48,7 @@ const videosweep = require('./videosweep');
|
||||
const sbcheck = require('./sbcheck');
|
||||
const reach = require('./reach');
|
||||
const lssync = require('./lssync');
|
||||
const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23)
|
||||
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
|
||||
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22)
|
||||
let follow = null, followStore = null;
|
||||
@@ -517,6 +518,7 @@ async function boot() {
|
||||
await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode)
|
||||
marks.init({ db });
|
||||
marks.ensureTable().catch(e => console.error('marks table', e.message));
|
||||
lsconv.init({ db, dataDir: DATA_DIR });
|
||||
setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref();
|
||||
chain.init({ onEvent: ev => {
|
||||
// the in-memory feed is per instance and always runs
|
||||
@@ -3176,7 +3178,7 @@ const server = http.createServer(async (req, res) => {
|
||||
if (p === '/api/admin/walletnudge' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, walletnudge.adminView()); }
|
||||
if (p === '/api/admin/reach' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, reach.adminView()); }
|
||||
if (p === '/api/admin/reach/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await reach.run({ dry: !!(b && b.dry) })); }
|
||||
if (p === '/api/admin/lssync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, Object.assign(lssync.adminView(), { inbound: lsinbound.adminView() })); }
|
||||
if (p === '/api/admin/lssync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, Object.assign(lssync.adminView(), { inbound: lsinbound.adminView(), conv: lsconv.adminView() })); }
|
||||
if (p === '/api/admin/lsinbound' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, lsinbound.adminView()); }
|
||||
// -- reverse registry sync from LinkSpin (2026-10-15): the same signed rows LinkSpin accepts from us (HMAC LS_SYNC_SECRET
|
||||
// over ts + newline + raw body, 10-minute window). New people become waiting accounts with their LinkSpin line; existing
|
||||
@@ -4680,14 +4682,45 @@ const server = http.createServer(async (req, res) => {
|
||||
m = /^\/api\/ads\/click\/(\d+)$/.exec(p);
|
||||
if (m && req.method === 'GET') {
|
||||
// an advertiser opening their own ad's link (from Campaigns, a preview, a test) is not a click: relay it uncounted (Marty, 2026-09-30)
|
||||
let own = false;
|
||||
try { const s = await auth.fromRequest(req); if (s && s.email) { const cm = await ads.campaignById(m[1]); own = !!(cm && cm.owner && String(cm.owner).toLowerCase() === String(s.email).toLowerCase()); } } catch (e) {}
|
||||
let own = false, cm = null;
|
||||
try { cm = await ads.campaignById(m[1]); } catch (e) {}
|
||||
try { const s = cm && await auth.fromRequest(req); if (s && s.email) own = !!(cm.owner && String(cm.owner).toLowerCase() === String(s.email).toLowerCase()); } catch (e) {}
|
||||
const target = own ? await ads.targetOf(m[1]) : await ads.click(m[1]);
|
||||
if (!target) { res.writeHead(404, baseHeaders()); return res.end(); }
|
||||
if (!own) coach.recordClick(m[1], req.headers.referer); // where the click happened
|
||||
res.writeHead(302, baseHeaders({ Location: target }));
|
||||
// conversion tracking (2026-10-23): every click, the owner's own too (flagged self, so they can test), gets a click id
|
||||
// on the target URL as lsclk=<id>; the row goes to LinkSpin, which matches the advertiser's goal pixel to it
|
||||
let loc = target;
|
||||
if (cm) { try { const ip = clientIp(req); const row = await lsconv.record(cm, req, { self: own, target, ip, country: geo.countryOf(ip) || null }); loc = lsconv.withClickId(target, row.id); } catch (e) { console.error('lsconv record', e.message); } }
|
||||
res.writeHead(302, baseHeaders({ Location: loc }));
|
||||
return res.end();
|
||||
}
|
||||
// Campaigns > Conversion tracking: the member's goals and counts live on LinkSpin; these proxy the signed calls
|
||||
if (p === '/api/my/conversions' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
if (!lsconv.on()) return json(res, 200, { ok: false, reason: 'off', error: 'Conversion tracking is not switched on yet. Your ads and clicks work as usual.' });
|
||||
try { return json(res, 200, Object.assign({}, await lsconv.summary(s.email, u.searchParams.get('fresh') === '1'), { ok: true })); }
|
||||
catch (e) { return json(res, 200, { ok: false, reason: 'down', error: 'LinkSpin, the service that counts your conversions, did not answer just now. Your ads and clicks are fine. Try again in a minute.' }); }
|
||||
}
|
||||
if ((p === '/api/my/conversions/goal' || p === '/api/my/conversions/test') && req.method === 'POST') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
if (!lsconv.on()) return json(res, 503, { error: 'Conversion tracking is not switched on yet.' });
|
||||
const b = await readBody(req) || {};
|
||||
const op = p.endsWith('/test') ? 'test' : String(b.op || '');
|
||||
if (!['create', 'update', 'remove', 'test'].includes(op)) return json(res, 400, { error: 'Unknown action.' });
|
||||
const f = {};
|
||||
if (op !== 'create') { const px = String(b.px || '').trim().toLowerCase(); if (!/^px[0-9a-f]{10}$/.test(px)) return json(res, 400, { error: 'That pixel id does not look right.' }); f.px = px; }
|
||||
if (op === 'create' || op === 'update') {
|
||||
if (b.name != null) { const nm = String(b.name).trim().toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9_-]/g, '').slice(0, 32); if (!nm) return json(res, 400, { error: 'Give the goal a short name, like subscriber or sale (letters, numbers, dashes).' }); f.name = nm; }
|
||||
else if (op === 'create') return json(res, 400, { error: 'Give the goal a short name, like subscriber or sale.' });
|
||||
if (b.value != null && String(b.value).trim() !== '') { const v = Number(b.value); if (!isFinite(v) || v < 0 || v > 1e6) return json(res, 400, { error: 'The value should be a number, like 19.95, or left empty.' }); f.value = Math.round(v * 100) / 100; }
|
||||
else if (op === 'update' && b.value != null) f.value = null;
|
||||
}
|
||||
try { return json(res, 200, Object.assign({ ok: true }, await lsconv.goalOp(s.email, op, f))); }
|
||||
catch (e) { return json(res, e.plain && e.status && e.status < 500 ? 400 : 502, { error: e.plain ? e.message : 'LinkSpin did not answer just now. Nothing was changed. Try again in a minute.' }); }
|
||||
}
|
||||
if (p === '/api/my/trace' && req.method === 'GET') { // payment trace for yourself or anyone within 3 levels of you, either direction
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
|
||||
Reference in New Issue
Block a user