// Conversion linkage, InstantAdPay half (Marty 2026-11-07, "Yes ship these"). REPORTING ONLY: this module never reads or changes a // sponsor, a payout, credits or anything on chain. LinkSpin owns the counting; this keeps the click and tells it what happened. // the click arrives as ?lsclk= or ?lsid= on any page: a first-party cookie iap.lsclk, 30 days, last click wins (the same life // and last-touch rule as the sponsor cookie), plus the page's own copy sent with the code request, because the // cookie is refused inside a traffic-exchange frame and never crosses browsers (the 2026-09-29 sponsor lesson) // the account kept in its own table, ls_account_clicks, keyed by email: remembered when the code is requested, bound when the // account is created (or a waiting LinkSpin shell is claimed). Its own table on purpose: accounts is not touched // the events sign-up, wallet link, each package Purchase on the chain, by an account with a bound click. One row each in // ls_events; its primary key is the idempotency key (join:, wallet:, purchase::), so two // app copies during a deploy can both try and only one row exists // the delivery a loop in the background posts unsent rows to LinkSpin (POST /api/partner/conv op events, signed like lsconv), 100 // at a time, every ~5 s with backoff to 5 minutes. A row is marked sent only after LinkSpin answers, and LinkSpin // dedupes by the same key, so a row sent by both copies, or twice, counts once // Nothing here runs in the chain event handler's path or in a sign-up's path beyond one local write: LinkSpin down, slow or // blocked changes nothing except that rows wait. No LS_SYNC_SECRET: rows wait too. 'use strict'; const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const lsconv = require('./lsconv'); let R = null, timer = null, flushing = false, fails = 0, nextAt = 0, jstate = null, saveT = null; const stats = { sent: 0, lastAt: null, lastError: null, errors: 0 }; const DAY = 86400000, WINDOW = 30 * DAY; const useDb = () => !!(R && R.db && R.db.enabled()); const JFILE = () => path.join(R.dataDir, 'lsreport.json'); const norm = e => String(e || '').trim().toLowerCase(); const isId = v => /^(?:[a-f0-9]{10}|[aik][a-f0-9]{11})$/.test(String(v || '')); const hash = email => crypto.createHash('sha256').update(norm(email)).digest('hex').slice(0, 24); // the id in a page address, or '' (lsclk first: it is the id the landing tag and ad clicks carry) const fromUrl = u => { const v = u.searchParams.get('lsclk') || u.searchParams.get('lsid') || ''; return isId(v) ? v : ''; }; const pick = (...vals) => { for (const v of vals) if (isId(v)) return String(v); return ''; }; const COOKIE = 'iap.lsclk'; const cookieHeader = (id, isProd) => COOKIE + '=' + id + '; Path=/; Max-Age=' + (30 * 86400) + '; ' + (isProd ? 'SameSite=None; Secure' : 'SameSite=Lax'); function init(deps) { R = deps; if (useDb()) ensureTables().catch(e => console.error('lsreport tables', e.message)); if (!deps.noTimers) { if (!timer) { timer = setInterval(() => { flush().catch(() => {}); }, 5000); if (timer.unref) timer.unref(); } setInterval(() => prune().catch(() => {}), 6 * 3600 * 1000).unref(); } } // column names checked against MySQL 8 reserved words (none of email, click_id, ts, bound, k, ev, cents, ev_ts, tx, sk, pushed, outcome is reserved) async function ensureTables() { await R.db.q(`CREATE TABLE IF NOT EXISTS ls_account_clicks ( email VARCHAR(190) PRIMARY KEY, click_id VARCHAR(16) NOT NULL, ts BIGINT NOT NULL, bound TINYINT NOT NULL DEFAULT 0 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); await R.db.q(`CREATE TABLE IF NOT EXISTS ls_events ( k VARCHAR(120) PRIMARY KEY, ev VARCHAR(10) NOT NULL, email VARCHAR(190) NOT NULL, click_id VARCHAR(16) NOT NULL, cents INT NOT NULL DEFAULT 0, ev_ts BIGINT NOT NULL, tx VARCHAR(80) NULL, sk VARCHAR(24) NULL, pushed TINYINT NOT NULL DEFAULT 0, outcome VARCHAR(12) NULL, INDEX (pushed, ev_ts) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); } // ---- JSON store (local runs) ---- function jload() { if (jstate) return jstate; try { jstate = JSON.parse(fs.readFileSync(JFILE(), 'utf8')); if (!jstate.clicks || !Array.isArray(jstate.events)) throw 0; } catch (e) { jstate = { clicks: {}, events: [] }; } return jstate; } function jsave() { if (saveT) return; saveT = setTimeout(() => { saveT = null; try { fs.writeFileSync(JFILE(), JSON.stringify(jload())); } catch (e) {} }, 300); if (saveT.unref) saveT.unref(); } // ---- the click on the account ---- async function clickOf(email) { const e = norm(email); if (useDb()) { const r = (await R.db.q('SELECT click_id, ts, bound FROM ls_account_clicks WHERE email=?', [e]))[0]; return r ? { click: r.click_id, ts: Number(r.ts), bound: Number(r.bound) ? 1 : 0 } : null; } return jload().clicks[e] || null; } // at the code request: the click travels with the email, so verifying in another browser still finds it. Last click wins until bound. async function remember(email, click) { const e = norm(email); if (!e || e.length > 190 || !isId(click)) return false; const now = Date.now(); if (useDb()) { await R.db.q('INSERT INTO ls_account_clicks (email, click_id, ts, bound) VALUES (?,?,?,0) ON DUPLICATE KEY UPDATE click_id=IF(bound=0,VALUES(click_id),click_id), ts=IF(bound=0,VALUES(ts),ts)', [e, click, now]); return true; } const st = jload(); if (st.clicks[e] && st.clicks[e].bound) return false; st.clicks[e] = { click, ts: now, bound: 0 }; jsave(); return true; } // the account now exists: bind the click (this request's, else the remembered one), once, and queue the join async function signup(email, click, sk) { const e = norm(email); if (!e || e.length > 190) return false; const row = await clickOf(e); if (row && row.bound) return false; const c = isId(click) ? click : (row && Date.now() - row.ts <= WINDOW ? row.click : ''); if (!c) return false; const now = Date.now(); if (useDb()) { await R.db.q('INSERT IGNORE INTO ls_account_clicks (email, click_id, ts, bound) VALUES (?,?,?,0)', [e, c, now]); const u = await R.db.q('UPDATE ls_account_clicks SET click_id=?, ts=?, bound=1 WHERE email=? AND bound=0', [c, now, e]); if (!(u && u.affectedRows === 1)) return false; } else { const st = jload(); st.clicks[e] = { click: c, ts: now, bound: 1 }; jsave(); } await enqueue({ k: 'join:' + hash(e), ev: 'join', email: e, click: c, cents: 0, ts: now, sk: /^s:[a-f0-9]{20}$/.test(String(sk || '')) ? sk : null }); return true; } async function wallet(email) { const e = norm(email); const row = await clickOf(e); if (!row || !row.bound) return false; return enqueue({ k: 'wallet:' + hash(e), ev: 'wallet', email: e, click: row.click, cents: 0, ts: Date.now() }); } // a Purchase chain event, already resolved to its account. Value = the USD price on the event. Linked positions sit on the same // account, so they count as that account's purchases. Past the click window nothing is queued: LinkSpin would refuse it anyway // (the bind is never earlier than the click, so more than 30 days after the bind is more than 30 days after the click). async function purchase(ev, email) { const e = norm(email); const cents = Number(ev && ev.priceCents) || 0; if (!e || cents <= 0 || !ev.tx) return false; const row = await clickOf(e); if (!row || !row.bound) return false; const ts = Number(ev.ts) || Date.now(); if (ts < row.ts - 60000 || ts - row.ts > WINDOW) return false; // before the sign-up, or past the window return enqueue({ k: ('purchase:' + ev.tx + ':' + ev.li).slice(0, 120), ev: 'purchase', email: e, click: row.click, cents, ts, tx: String(ev.tx).slice(0, 80) }); } async function enqueue(x) { if (useDb()) { const r = await R.db.q('INSERT IGNORE INTO ls_events (k, ev, email, click_id, cents, ev_ts, tx, sk, pushed) VALUES (?,?,?,?,?,?,?,?,0)', [x.k, x.ev, x.email, x.click, x.cents, x.ts, x.tx || null, x.sk || null]); return !!(r && r.affectedRows === 1); } const st = jload(); if (st.events.some(r => r.k === x.k)) return false; st.events.push(Object.assign({ pushed: 0 }, x)); if (st.events.length > 5000) st.events = st.events.slice(-4000); jsave(); return true; } // ---- delivery ---- async function unsent(n) { if (useDb()) return (await R.db.q('SELECT k, ev, email, click_id, cents, ev_ts, tx, sk FROM ls_events WHERE pushed=0 ORDER BY ev_ts LIMIT ?', [n])).map(r => ({ k: r.k, ev: r.ev, email: r.email, click: r.click_id, cents: Number(r.cents) || 0, ts: Number(r.ev_ts), tx: r.tx, sk: r.sk })); return jload().events.filter(r => !r.pushed).slice(0, n); } async function markSent(k, outcome) { if (useDb()) { await R.db.q('UPDATE ls_events SET pushed=1, outcome=? WHERE k=?', [String(outcome || '').slice(0, 12) || null, k]); return; } const r = jload().events.find(x => x.k === k); if (r) { r.pushed = 1; r.outcome = outcome; jsave(); } } async function flush() { if (!lsconv.on() || flushing || Date.now() < nextAt) return { skipped: true }; flushing = true; let sent = 0; try { for (let round = 0; round < 10; round++) { const rows = await unsent(100); if (!rows.length) break; const res = await lsconv.signedPost('/api/partner/conv', { op: 'events', events: rows.map(r => ({ k: r.k, ev: r.ev, email: r.email, click: r.click, value: r.cents / 100, ts: r.ts, tx: r.tx || undefined, sk: r.sk || undefined })) }, 15000); if (!res || res.ok !== true || !Array.isArray(res.results)) throw new Error('linkspin answered without results'); for (const a of res.results) { await markSent(a.k, a.result); sent++; stats.sent++; } stats.lastAt = Date.now(); if (rows.length < 100) break; } fails = 0; nextAt = 0; return { sent }; } catch (e) { fails++; stats.errors++; stats.lastError = e.message; nextAt = Date.now() + Math.min(300000, 5000 * Math.pow(2, Math.min(fails, 6))); if (fails <= 3 || fails % 20 === 0) console.error('lsreport push', e.message); return { error: e.message, sent }; } finally { flushing = false; } } async function prune() { const now = Date.now(); const old = now - 60 * DAY, stale = now - 31 * DAY; if (useDb()) { await R.db.q('DELETE FROM ls_events WHERE ev_ts r.ts >= old); for (const k of Object.keys(st.clicks)) { const c = st.clicks[k]; if (c.ts < old || (!c.bound && c.ts < stale)) delete st.clicks[k]; } jsave(); } function adminView() { return { on: lsconv.on(), sent: stats.sent, lastAt: stats.lastAt, errors: stats.errors, lastError: stats.lastError, fails, nextAt: nextAt || null }; } module.exports = { init, ensureTables, fromUrl, pick, cookieHeader, COOKIE, isId, remember, signup, wallet, purchase, clickOf, flush, prune, adminView };