Files
instantadpay/lsconv.js
T
martbost 03284aa281 Conversion linkage, InstantAdPay side (Marty 2026-11-07, "Yes ship these"): a LinkSpin click stays with the account, and its sign-up, wallet link and each package purchase are reported to LinkSpin. Reporting only: no sponsor, payout, credit or chain path changes; accounts.js only gains a notification after a wallet is linked.
lsreport.js. A click id (lsclk or lsid) arriving on any page is kept in a first-party cookie iap.lsclk, 30 days, last click wins, like the sponsor cookie. The join page also sends its own copy with the code request and verify (the cookie is refused in traffic-exchange frames and never crosses browsers, the 2026-09-29 lesson) and it is remembered per email. It is stored in its own table ls_account_clicks when the account is created or a waiting LinkSpin shell is claimed, on /api/signup, email sign-in and in-game sign-in (a game may pass lsclk; none does yet).

Reports queue in ls_events, whose primary key is the idempotency key (join:<hash>, wallet:<hash>, purchase:<tx>:<log index>), so two app copies in a deploy cannot double a row, and LinkSpin dedupes on the same key. A background loop sends them signed, retrying up to every 5 minutes; a sign-up or a purchase never waits on LinkSpin. The purchase hook runs after the existing ev: claim and its value is the USD price on the chain event. A first purchase finds its buyer through the contract's wallet for that member id, since member_id may not be stored yet. Linked positions count as the account's purchases. Past 30 days from the sign-up nothing is queued (LinkSpin's window is from the click).

Campaigns > Conversion tracking lists everything the member's clicks led to, and joins, wallets and purchases on each campaign row. Guide, privacy page and chatbot (CANNED + FACTS) updated; common.js, join.js and my.js tags bumped.

QA: bash qa/run.sh netconv (54 checks: local InstantAdPay + local LinkSpin + a mock Polygon RPC, a real Purchase log through the real event fan-out, LinkSpin down, two copies racing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 07:48:36 -06:00

177 lines
12 KiB
JavaScript

// 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.
// owners (2026-10-26) the soft keys members sign in from ride on the click push, so LinkSpin keeps a member's own
// clicks (ads here, spin links and Banner Spins there) as tests, never counted
// 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;
}
// ---- own-click tests (Marty approved 2026-10-26) ----
// A member's own click is a test on LinkSpin, on every click type. LinkSpin knows the soft keys its members sign in from;
// InstantAdPay members may never sign in there, so the soft keys of their InstantAdPay sessions ride along with the click
// push as owners: [{ owner, sk, ts }] (no raw IP, same hash as the click rows). Queued at most once per 6 h per
// email + soft key; a failed push puts them back. Also checked here so an own click is flagged self=1 at the source.
const OWN_MS = 31 * 86400e3, ownSeen = new Map(); let ownQueue = new Map();
function noteSession(email, ip, ua) {
const e = String(email || '').trim().toLowerCase(); if (!e || e.length > 190) return false;
const sk = softKey(ip, ua); const k = e + '|' + sk; const now = Date.now();
if (now - (ownSeen.get(k) || 0) < 6 * 3600e3) return false;
ownSeen.set(k, now); if (ownSeen.size > 50000) ownSeen.delete(ownSeen.keys().next().value);
if (on()) { ownQueue.set(k, { owner: e, sk, ts: now }); if (ownQueue.size > 5000) ownQueue.delete(ownQueue.keys().next().value); }
return true;
}
function isOwnerSk(owner, sk) { const t = ownSeen.get(String(owner || '').toLowerCase() + '|' + sk); return !!(t && Date.now() - t <= OWN_MS); }
function takeOwners() { const out = [...ownQueue.values()].slice(0, 2000); for (const o of out) ownQueue.delete(o.owner + '|' + o.sk); return out; }
function requeueOwners(list) { for (const o of list || []) if (!ownQueue.has(o.owner + '|' + o.sk)) ownQueue.set(o.owner + '|' + o.sk, o); }
// ---- 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; owners (own soft keys) ride on the first request
const rows = await unpushed(500); const owners = round === 0 ? takeOwners() : [];
if (!rows.length && !owners.length) break;
let res; try { res = await signedPost('/api/partner/clicks', { clicks: rows, owners }, 20000); } catch (e) { requeueOwners(owners); throw e; }
if (!res || res.ok !== true) { requeueOwners(owners); throw new Error('linkspin answered without ok'); }
if (rows.length) { await markPushed(rows.map(r => r.id)); sent += rows.length; stats.pushed += rows.length; stats.lastAt = Date.now(); }
if (owners.length) stats.owners = (stats.owners || 0) + owners.length;
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 = { signedPost, init, record, flush, summary, goalOp, withClickId, softKey, placementOf, deviceOf, newId, adminView, on, noteSession, isOwnerSk };