// Postback rails (LinkSpin, 2026-09-29). Outbound: a member's tracker or traffic network is told, server to // server, when a click on one of their links converts (join, wallet, purchase, or a partner-reported event), // with the click id that came in on the link. Inbound: a partner reports a conversion against our click id // with the member's partner key. Every delivery is logged; nothing member-supplied is trusted: // https/http only, no private or internal hosts (checked by name AND by resolved address), short timeouts, // small bodies, per-member rate cap, auto-disable after repeated failures, and only the member's own clicks. 'use strict'; const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const dns = require('dns').promises; const net = require('net'); let DATA_DIR = null, ownHosts = () => [], rotator = null; const J = { db: null, FILE: () => path.join(DATA_DIR, 'postbacks.json'), load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, items: [], log: [], keys: {}, clicks: {} }; } for (const k of ['items', 'log']) if (!Array.isArray(this.db[k])) this.db[k] = []; for (const k of ['keys', 'clicks']) if (!this.db[k]) this.db[k] = {}; }, 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; J.load(); } const norm = e => String(e || '').trim().toLowerCase(); const EVENTS = ['join', 'lead', 'wallet', 'purchase', 'external']; const MACRO = /\{([a-z0-9_]{1,24})\}/gi; function isPrivateIp(ip) { if (net.isIPv4(ip)) { const p = ip.split('.').map(Number); return p[0] === 10 || p[0] === 127 || p[0] === 0 || (p[0] === 169 && p[1] === 254) || (p[0] === 172 && p[1] >= 16 && p[1] <= 31) || (p[0] === 192 && p[1] === 168) || (p[0] === 100 && p[1] >= 64 && p[1] <= 127); } if (net.isIPv6(ip)) { const l = ip.toLowerCase(); return l === '::1' || l === '::' || l.startsWith('fc') || l.startsWith('fd') || l.startsWith('fe80') || l.startsWith('::ffff:'); } return true; } function validateUrl(template) { const t = String(template || '').trim(); if (!t) return 'Give the postback a URL.'; if (t.length > 1500) return 'That URL is too long.'; if (!/^https?:\/\//i.test(t)) return 'The URL must start with http:// or https://.'; let u; try { u = new URL(t.replace(MACRO, 'x')); } catch (e) { return 'That is not a valid URL.'; } const h = u.hostname.toLowerCase(); if (!h.includes('.') || /(^|\.)(localhost|local|internal|lan|home|arpa)$/.test(h)) return 'The URL must point at a public host.'; if (net.isIP(h) && isPrivateIp(h)) return 'Private network addresses are not allowed.'; if (ownHosts().map(x => String(x).toLowerCase()).includes(h)) return 'A postback cannot point back at LinkSpin.'; return null; } async function hostIsPublic(hostname) { if (net.isIP(hostname)) return !isPrivateIp(hostname); try { const rs = await dns.lookup(hostname, { all: true }); return rs.length > 0 && rs.every(r => !isPrivateIp(r.address)); } catch (e) { return false; } } function fill(template, vals) { return String(template).replace(MACRO, (m, k) => { const key = k.toLowerCase(); return encodeURIComponent(vals[key] == null ? '' : String(vals[key]).slice(0, 200)); }); } // -- member config function mine(owner) { return J.db.items.filter(p => p.owner === norm(owner)); } function pubItem(p) { return { id: p.id, name: p.name, url: p.url, method: p.method, events: p.events, enabled: !!p.enabled, created: p.created, fails: p.fails || 0, lastStatus: p.lastStatus || null, lastAt: p.lastAt || 0, sent: p.sent || 0 }; } async function list(owner) { return mine(owner).map(pubItem); } async function create(owner, body) { if (mine(owner).length >= 20) return { error: 'Up to 20 postbacks per account.' }; const name = String(body.name || '').trim().slice(0, 60) || 'Postback'; const bad = validateUrl(body.url); if (bad) return { error: bad }; const events = (Array.isArray(body.events) ? body.events : String(body.events || '').split(',')).map(x => String(x).trim().toLowerCase()).filter(x => EVENTS.includes(x)); if (!events.length) return { error: 'Pick at least one event.' }; const p = { id: crypto.randomBytes(5).toString('hex'), owner: norm(owner), name, url: String(body.url).trim(), method: String(body.method || 'GET').toUpperCase() === 'POST' ? 'POST' : 'GET', events, enabled: true, created: Date.now(), fails: 0, sent: 0 }; J.db.items.push(p); J.save(); return { ok: true, postback: pubItem(p) }; } async function update(owner, id, body) { const p = J.db.items.find(x => x.id === id && x.owner === norm(owner)); if (!p) return { error: 'No such postback.' }; if (body.remove) { J.db.items = J.db.items.filter(x => x !== p); J.save(); return { ok: true, removed: true }; } if (body.name != null) p.name = String(body.name).trim().slice(0, 60) || p.name; if (body.url != null) { const bad = validateUrl(body.url); if (bad) return { error: bad }; p.url = String(body.url).trim(); p.fails = 0; } if (body.events != null) { const ev = (Array.isArray(body.events) ? body.events : String(body.events).split(',')).map(x => String(x).trim().toLowerCase()).filter(x => EVENTS.includes(x)); if (ev.length) p.events = ev; } if (body.method != null) p.method = String(body.method).toUpperCase() === 'POST' ? 'POST' : 'GET'; if (body.enabled != null) { p.enabled = !!body.enabled; if (p.enabled) p.fails = 0; } J.save(); return { ok: true, postback: pubItem(p) }; } async function logFor(owner, n) { return J.db.log.filter(l => l.owner === norm(owner)).slice(-(n || 50)).reverse(); } // -- partner key (inbound) function partnerKey(owner) { const o = norm(owner); if (!J.db.keys[o]) { J.db.keys[o] = crypto.randomBytes(12).toString('hex'); J.save(); } return J.db.keys[o]; } function rotateKey(owner) { const o = norm(owner); J.db.keys[o] = crypto.randomBytes(12).toString('hex'); J.save(); return J.db.keys[o]; } function ownerOfKey(key) { const k = String(key || ''); if (!/^[a-f0-9]{24}$/.test(k)) return null; for (const [o, v] of Object.entries(J.db.keys)) if (v === k) return o; return null; } // -- click binding (which click brought this account) function bindClick(email, lsid) { const e = norm(email); if (!e || !/^[a-z0-9]{6,20}$/i.test(String(lsid || ''))) return; if (J.db.clicks[e]) return; J.db.clicks[e] = { lsid: String(lsid), ts: Date.now() }; J.save(); } function clickOf(email) { return J.db.clicks[norm(email)] || null; } // -- delivery const rate = {}; // owner -> [timestamps] function rateOk(owner) { const now = Date.now(); const a = (rate[owner] = (rate[owner] || []).filter(t => now - t < 3600000)); if (a.length >= 300) return false; a.push(now); return true; } async function deliver(p, url, ctx) { const t0 = Date.now(); let status = 0, ok = false, note = ''; try { const u = new URL(url); if (!(await hostIsPublic(u.hostname))) { note = 'host resolves to a private address'; } else { const ctl = new AbortController(); const tm = setTimeout(() => ctl.abort(), 8000); const r = await fetch(url, { method: p.method, redirect: 'manual', signal: ctl.signal, headers: { 'User-Agent': 'LinkSpin-Postback/1.0' }, body: p.method === 'POST' ? '' : undefined }); clearTimeout(tm); status = r.status; ok = r.status >= 200 && r.status < 400; try { note = (await r.text()).slice(0, 120); } catch (e) {} } } catch (e) { note = String(e && e.message || e).slice(0, 120); } p.lastStatus = status || note.slice(0, 40); p.lastAt = Date.now(); if (ok) { p.sent = (p.sent || 0) + 1; p.fails = 0; } else { p.fails = (p.fails || 0) + 1; if (p.fails >= 10) p.enabled = false; } J.db.log.push({ ts: t0, owner: p.owner, pb: p.id, name: p.name, event: ctx.event, lsid: ctx.lsid || '', url: url.slice(0, 300), status, ok, ms: Date.now() - t0, note, test: !!ctx.test }); if (J.db.log.length > 2000) J.db.log = J.db.log.slice(-1500); J.save(); return { ok, status, note }; } // fire every enabled postback of `owner` that listens to `event`; ctx carries the click's params and the event facts async function fire(owner, event, ctx) { const o = norm(owner); const out = []; for (const p of J.db.items.filter(x => x.owner === o && x.enabled && x.events.includes(event))) { if (!rateOk(o)) break; const q = (ctx.q || {}); const vals = { clickid: q.clickid || q.cid || q.click_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)$/.test(k) && vals[k] == null) vals[k] = v; const url = fill(p.url, vals); let r = await deliver(p, url, Object.assign({}, ctx, { event })); if (!r.ok && !ctx.test) { await new Promise(res => setTimeout(res, 4000)); r = await deliver(p, url, Object.assign({}, ctx, { event })); } out.push({ id: p.id, name: p.name, ok: r.ok, status: r.status, note: r.note }); } return out; } async function test(owner, id) { const p = J.db.items.find(x => x.id === id && x.owner === norm(owner)); if (!p) return { error: 'No such postback.' }; const ev = p.events[0] || 'join'; const url = fill(p.url, { clickid: 'test-click-123', subid: 'test-sub', s1: 'test-s1', s2: '', s3: '', s4: '', s5: '', source: 'test', event: ev, payout: '0.00', currency: 'USD', txid: '0xtest', lsid: 'testlsid', code: 'test', country: 'US', device: 'desktop' }); const r = await deliver(p, url, { event: ev, lsid: 'testlsid', test: true }); return { ok: r.ok, status: r.status, note: r.note, url }; } // a conversion happened for an account: find the click that brought them, record it on the rotator, fire the owner's postbacks async function convertFor(email, event, facts) { const c = clickOf(email); if (!c) return null; const hit = rotator && rotator.convert ? await rotator.convert(c.lsid, event, facts || {}) : null; if (!hit) return null; const ctx = Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: c.lsid, code: hit.code }, facts || {}); try { await fire(hit.owner, event, ctx); } catch (e) {} return hit; } // a partner reported a conversion against one of our click ids async function inbound(key, body) { const owner = ownerOfKey(key); if (!owner) return { error: 'Unknown partner key.' }; const lsid = String(body.lsid || body.clickid || '').trim(); if (!/^[a-z0-9]{6,20}$/i.test(lsid)) return { error: 'lsid is required.' }; const event = 'external'; const value = Number(body.value || body.payout || 0) || 0; const label = String(body.event || body.name || 'conversion').slice(0, 40); const hit = rotator && rotator.convert ? await rotator.convert(lsid, event, { payout: value, label }) : null; if (!hit) return { error: 'No click with that lsid.' }; if (hit.owner !== owner) return { error: 'That click is not yours.' }; const ctx = { q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid, code: hit.code, payout: value, currency: String(body.currency || 'USD').slice(0, 6), txid: String(body.txid || '').slice(0, 80), label }; try { await fire(owner, event, ctx); } catch (e) {} return { ok: true, recorded: event, lsid }; } module.exports = { init, EVENTS, validateUrl, list, create, update, logFor, partnerKey, rotateKey, bindClick, clickOf, fire, test, convertFor, inbound };