Control Room: shared shell with in-shell sign-in, Reports, Team and Wallet screens; postback rails (click ids, macros, lsid attribution, conversions, outbound + inbound postbacks with SSRF guards)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-09-29 15:52:07 -05:00
parent 688d3c4bb5
commit 8e1ddb892f
12 changed files with 652 additions and 138 deletions
+141
View File
@@ -0,0 +1,141 @@
// 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', '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 };
+90
View File
@@ -0,0 +1,90 @@
// LinkSpin Control Room shell (2026-09-29): the frame every workspace screen shares.
// Rail + topbar, session check, in-shell sign-in (email code, same endpoints as the dashboard),
// fetch helper, toast, in-page dialogs (never native prompt/confirm). Pages: put content in
// <div id="page">, then CR.mount({active,title,sub,actions}) and CR.requireSession(cb).
window.CR = (function () {
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const fmt = n => Number(n || 0).toLocaleString();
const NAV = [
['links', 'Links', '/links', '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>'],
['pages', 'Pages', '/pages', '<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M8 9h8M8 13h6"/>'],
['zones', 'Zones', '/zones', '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/>'],
['reports', 'Reports', '/reports', '<path d="M4 19V9M10 19V5M16 19v-8M22 19H2"/>'],
['team', 'Team', '/team', '<circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.5"/><path d="M3 19c0-3 3-5 6-5s6 2 6 5M15 15c3 0 6 1.5 6 4"/>'],
['wallet', 'Wallet', '/wallet', '<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M16 12h3"/>'],
];
// screens not built yet fall back to the classic dashboard pane so nothing is a dead end
const FALLBACK = { pages: '/my#promo', zones: '/my#campaigns', team: '/my#line', wallet: '/my#wallet' };
const BUILT = new Set(['links', 'reports', 'team', 'wallet']);
let ME = null, toastT;
function toast(msg, bad) { let t = $('crToast'); if (!t) { t = document.createElement('div'); t.id = 'crToast'; t.className = 'toast'; t.setAttribute('role', 'status'); document.body.appendChild(t); } t.textContent = msg; t.style.background = bad ? '#FF7A7A' : ''; t.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('on'), 2000); }
async function api(path, body) { const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) throw new Error(r.error); return r; }
async function get(path) { const r = await (await fetch(path, { headers: { Accept: 'application/json' } })).json(); if (r.error) throw new Error(r.error); return r; }
function copy(text) { try { navigator.clipboard.writeText(text).then(() => toast('Copied'), () => toast('Select and copy: ' + text)); } catch (e) { toast('Select and copy: ' + text); } }
function dialog(opts) {
return new Promise(resolve => {
let host = $('crModalHost'); if (!host) { host = document.createElement('div'); host.id = 'crModalHost'; document.body.appendChild(host); }
host.innerHTML = '';
const back = document.createElement('div'); back.className = 'modal-back';
back.innerHTML = '<div class="modal" role="dialog" aria-modal="true"><h2>' + esc(opts.title) + '</h2>' + (opts.text ? '<div class="ink2">' + esc(opts.text) + '</div>' : '') + (opts.html || '')
+ (opts.fields || []).map(f => '<label class="lbl">' + esc(f.label) + (f.type === 'textarea' ? '<textarea class="field' + (f.mono ? ' mono' : '') + '" id="dlg-' + f.k + '" rows="' + (f.rows || 3) + '" placeholder="' + esc(f.placeholder || '') + '">' + esc(f.value || '') + '</textarea>' : '<input class="field' + (f.mono ? ' mono' : '') + '" id="dlg-' + f.k + '" type="' + (f.type || 'text') + '" value="' + esc(f.value || '') + '" placeholder="' + esc(f.placeholder || '') + '"' + (f.max ? ' maxlength="' + f.max + '"' : '') + '>') + '</label>').join('')
+ '<div class="acts"><button class="btn" type="button" id="dlgNo">' + esc(opts.no || 'Cancel') + '</button><button class="btn pri' + (opts.danger ? ' danger' : '') + '" type="button" id="dlgOk">' + esc(opts.ok || 'OK') + '</button></div></div>';
host.appendChild(back);
const done = v => { host.innerHTML = ''; resolve(v); };
back.querySelector('#dlgNo').addEventListener('click', () => done(null));
back.addEventListener('click', e => { if (e.target === back) done(null); });
back.querySelector('#dlgOk').addEventListener('click', () => { const out = {}; (opts.fields || []).forEach(f => { out[f.k] = back.querySelector('#dlg-' + f.k).value; }); done(opts.fields ? out : true); });
const first = back.querySelector('input,textarea'); if (first) { first.focus(); if (first.select) first.select(); }
back.addEventListener('keydown', e => { if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') back.querySelector('#dlgOk').click(); if (e.key === 'Escape') done(null); });
});
}
function mount(o) {
const page = $('page'); if (!page) return;
const app = document.createElement('div'); app.className = 'app';
app.innerHTML = '<nav class="rail" aria-label="LinkSpin"><a class="mark" href="/" aria-label="LinkSpin home" title="LinkSpin"></a>'
+ NAV.map(([k, label, href, svg]) => '<a href="' + (BUILT.has(k) ? href : FALLBACK[k]) + '"' + (k === o.active ? ' class="on" aria-current="page"' : '') + ' title="' + label + '" aria-label="' + label + '"><svg viewBox="0 0 24 24">' + svg + '</svg></a>').join('')
+ '<span class="sp"></span><a href="#" id="crUserBtn" title="Account" aria-label="Account"><svg viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-6 8-6s8 2 8 6"/></svg></a></nav>'
+ '<div class="main"><div class="topbar"><h1>' + esc(o.title || '') + '</h1><span class="muted mono" id="crSub">' + esc(o.sub || '') + '</span><span class="grow"></span><span id="crActions">' + (o.actions || '') + '</span></div><div id="crBody"></div></div>';
page.parentNode.insertBefore(app, page); app.querySelector('#crBody').appendChild(page);
$('crUserBtn').addEventListener('click', async e => { e.preventDefault(); if (!ME || !ME.signedIn) return signInFlow(() => location.reload()); const v = await dialog({ title: ME.username ? '@' + ME.username : (ME.email || 'Account'), text: 'Signed in on LinkSpin. Your classic dashboard is still at /my.', ok: 'Sign out', no: 'Close', danger: true }); if (v) { try { await api('/api/auth/logout'); } catch (er) {} location.reload(); } });
}
const sub = t => { const s = $('crSub'); if (s) s.textContent = t; };
async function me(force) { if (ME && !force) return ME; try { ME = await (await fetch('/api/me', { headers: { Accept: 'application/json' } })).json(); } catch (e) { ME = { signedIn: false }; } return ME; }
// sign-in inside the shell: email -> six-digit code, on the same endpoints and guards as the dashboard.
const FTS = Date.now();
async function signInFlow(onReady) {
let host = $('crModalHost'); if (!host) { host = document.createElement('div'); host.id = 'crModalHost'; document.body.appendChild(host); }
host.innerHTML = '<div class="modal-back"><div class="modal" role="dialog" aria-modal="true"><h2>Sign in</h2><div class="ink2">Email first. We send a six-digit code; no password to remember. New here? The same box creates your account.</div>'
+ '<label class="lbl">Email<input class="field" id="siEmail" type="email" autocomplete="email" placeholder="you@example.com"></label>'
+ '<div id="siCodeRow" hidden><label class="lbl">Code from the email<input class="field mono" id="siCode" inputmode="numeric" maxlength="6" placeholder="123456"></label></div>'
+ '<div class="muted" id="siMsg"></div><div class="acts"><a class="btn" href="/my">Classic dashboard</a><button class="btn pri" type="button" id="siGo">Send code</button></div></div></div>';
const email = $('siEmail'), code = $('siCode'), go = $('siGo'), msg = $('siMsg'); let stage = 'email';
email.focus();
const say = (t, bad) => { msg.textContent = t; msg.className = bad ? 'bad' : 'muted'; };
async function step() {
try {
if (stage === 'email') {
const e = email.value.trim(); if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return say('That email address does not look right.', true);
go.disabled = true; say('Sending…');
// the sign-up guard refuses a form younger than a few seconds (bot defence); wait it out instead of bouncing the person
const wait = FTS + 4500 - Date.now(); if (wait > 0) await new Promise(r => setTimeout(r, wait));
const r = await api('/api/auth/email/start', { email: e, fts: FTS, hp_field_x9: '', pick: null });
go.disabled = false;
if (r.challenge) { say('One more check is needed for this address. Use the classic dashboard sign-in this once.', true); return; }
$('siCodeRow').hidden = false; code.focus(); stage = 'code'; go.textContent = 'Sign in';
if (r.devCode) code.value = r.devCode;
say(r.sent ? 'Code sent. Check your inbox, and spam the first time.' : 'Code filled in (local dev).');
} else {
go.disabled = true; say('Checking…');
await api('/api/auth/email/verify', { email: email.value.trim(), code: code.value.trim() });
host.innerHTML = ''; ME = null; await me(true); toast('You are in'); onReady && onReady(ME);
}
} catch (e) { go.disabled = false; say(e.message, true); }
}
go.addEventListener('click', step);
host.querySelector('.modal').addEventListener('keydown', e => { if (e.key === 'Enter') step(); });
}
async function requireSession(onReady) { const m = await me(); if (m && m.signedIn) return onReady(m); signInFlow(onReady); }
return { esc, fmt, api, get, copy, dialog, toast, mount, sub, me, requireSession, signInFlow };
})();
+52 -45
View File
@@ -1,68 +1,45 @@
// LinkSpin Links workspace (Control Room, first real screen, 2026-09-29). Talks to the existing rotator API:
// GET /api/my/rotations, POST /api/my/rotations, POST /api/my/rotations/:id, POST .../dest, POST .../dest/:did, GET .../stats
// LinkSpin Links workspace (Control Room). Rotator API + postbacks + share kit. Uses the shared shell (cr-shell.js).
(function () {
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const fmt = n => Number(n || 0).toLocaleString();
let ROT = [], HOSTS = [], SEL = null, STATS = {}, FILTER = '';
let toastT;
function toast(msg, bad) { const t = $('toast'); t.textContent = msg; t.style.background = bad ? '#FF7A7A' : ''; t.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('on'), 1800); }
async function api(path, body) { const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) throw new Error(r.error); return r; }
function copy(text) { try { navigator.clipboard.writeText(text).then(() => toast('Copied'), () => toast('Select and copy: ' + text)); } catch (e) { toast('Select and copy: ' + text); } }
// in-page dialogs (never native prompt/confirm)
function dialog(opts) {
return new Promise(resolve => {
const host = $('modalHost'); host.innerHTML = '';
const back = document.createElement('div'); back.className = 'modal-back';
back.innerHTML = '<div class="modal" role="dialog" aria-modal="true"><h2>' + esc(opts.title) + '</h2>' + (opts.text ? '<div class="ink2">' + esc(opts.text) + '</div>' : '')
+ (opts.fields || []).map(f => '<label class="lbl">' + esc(f.label) + '<input class="field' + (f.mono ? ' mono' : '') + '" id="dlg-' + f.k + '" type="' + (f.type || 'text') + '" value="' + esc(f.value || '') + '" placeholder="' + esc(f.placeholder || '') + '"' + (f.max ? ' maxlength="' + f.max + '"' : '') + '></label>').join('')
+ '<div class="acts"><button class="btn" type="button" id="dlgNo">' + esc(opts.no || 'Cancel') + '</button><button class="btn pri' + (opts.danger ? ' danger' : '') + '" type="button" id="dlgOk">' + esc(opts.ok || 'OK') + '</button></div></div>';
host.appendChild(back);
const done = v => { host.innerHTML = ''; resolve(v); };
back.querySelector('#dlgNo').addEventListener('click', () => done(null));
back.addEventListener('click', e => { if (e.target === back) done(null); });
back.querySelector('#dlgOk').addEventListener('click', () => { const out = {}; (opts.fields || []).forEach(f => { out[f.k] = back.querySelector('#dlg-' + f.k).value; }); done(opts.fields ? out : true); });
const first = back.querySelector('input'); if (first) { first.focus(); first.select(); back.addEventListener('keydown', e => { if (e.key === 'Enter') back.querySelector('#dlgOk').click(); if (e.key === 'Escape') done(null); }); }
});
}
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
let ROT = [], HOSTS = [], SEL = null, STATS = {}, FILTER = '', PB = null;
CR.mount({ active: 'links', title: 'Links', sub: 'loading', actions: '<button class="btn pri" id="newBtn" type="button">+ New spin</button>' });
const linkUrl = r => 'https://' + (HOSTS[0] || location.host) + '/r/' + r.code;
const clicks7 = r => r.hits7 || 0;
const health = r => r.paused ? { cls: 'warn', t: 'PAUSED' } : !r.destinations.some(d => d.active) ? { cls: 'bad', t: 'NO LIVE DESTINATION' } : { cls: 'ok', t: 'LIVE' };
async function load(keep) {
let r; try { r = await (await fetch('/api/my/rotations', { headers: { Accept: 'application/json' } })).json(); } catch (e) { r = { error: 'network' }; }
if (r.error) { $('signin').hidden = false; $('ws').hidden = true; $('tbSub').textContent = 'not signed in'; return; }
let r; try { r = await CR.get('/api/my/rotations'); } catch (e) { CR.sub('could not load'); return; }
ROT = (r.rotations || []).slice().sort((a, b) => clicks7(b) - clicks7(a)); HOSTS = r.hosts || [];
$('signin').hidden = true; $('ws').hidden = false;
const tot7 = ROT.reduce((n, x) => n + clicks7(x), 0);
$('tbSub').textContent = ROT.length + ' link' + (ROT.length === 1 ? '' : 's') + ' · ' + fmt(tot7) + ' clicks in 7 days';
CR.sub(ROT.length + ' link' + (ROT.length === 1 ? '' : 's') + ' · ' + fmt(tot7) + ' clicks in 7 days');
renderList();
if (keep && SEL != null) { const s = ROT.find(x => x.id === SEL); if (s) return select(s.id, true); }
const want = SEL != null ? SEL : (Number(location.hash.slice(1)) || null);
if (want != null && ROT.find(x => x.id === want)) return select(want, true);
if (!ROT.length) { $('noSel').hidden = false; $('sel').hidden = true; SEL = null; }
else if (SEL == null) select(ROT[0].id, true);
else select(ROT[0].id, true);
}
function renderList() {
const q = FILTER.trim().toLowerCase();
const rows = ROT.filter(x => !q || x.name.toLowerCase().includes(q) || x.code.includes(q));
$('listCount').textContent = ROT.length + ' link' + (ROT.length === 1 ? '' : 's');
$('items').innerHTML = rows.length ? rows.map(x => { const h = health(x); return '<div class="item' + (x.id === SEL ? ' on' : '') + '" data-id="' + x.id + '" role="button" tabindex="0">'
+ '<div><div class="nm">' + esc(x.name) + (h.cls !== 'ok' ? ' <span class="tag ' + h.cls + '">' + h.t + '</span>' : '') + '</div><div class="cd">' + esc((HOSTS[0] || location.host) + '/r/' + x.code) + '</div></div>'
+ '<div><div class="nm">' + esc(x.name) + (h.cls !== 'ok' ? ' <span class="tag ' + h.cls + '">' + h.t + '</span>' : '') + (x.conversions ? ' <span class="tag ok">' + x.conversions + ' conv</span>' : '') + '</div><div class="cd">' + esc((HOSTS[0] || location.host) + '/r/' + x.code) + '</div></div>'
+ '<div class="rt"><span class="n">' + fmt(clicks7(x)) + '</span><span class="muted" style="font-size:10px">7 d</span></div></div>'; }).join('')
: '<div class="empty"><div class="muted">' + (ROT.length ? 'No link matches that filter.' : 'No links yet.') + '</div></div>';
$('items').querySelectorAll('.item').forEach(el => { const go = () => select(Number(el.dataset.id)); el.addEventListener('click', go); el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); });
}
async function select(id, quiet) {
SEL = id; const r = ROT.find(x => x.id === id); if (!r) return;
if (String(location.hash.slice(1)) !== String(id)) history.replaceState(null, '', '#' + id);
$('noSel').hidden = true; $('sel').hidden = false; $('ws').classList.add('focus');
$('items').querySelectorAll('.item').forEach(el => el.classList.toggle('on', Number(el.dataset.id) === id));
$('dName').textContent = r.name; $('dUrl').textContent = linkUrl(r);
const h = health(r); $('dLive').innerHTML = '<span class="' + h.cls + '"><span class="dot"></span>' + h.t + '</span>';
$('pauseBtn').textContent = r.paused ? 'Resume' : 'Pause';
$('fallback').value = r.fallback || '';
const bots = r.bots || 0;
$('tiles').innerHTML = [['Served, 7 d', fmt(r.hits7 || 0)], ['Unique, all time', fmt(r.uniques || 0)], ['Clicks, all time', fmt(r.hits || 0)], ['Bots dropped', fmt(bots)], ['Live destinations', r.destinations.filter(d => d.active).length + ' / ' + r.destinations.length]]
$('tiles').innerHTML = [['Served, 7 d', fmt(r.hits7 || 0)], ['Unique, all time', fmt(r.uniques || 0)], ['Clicks, all time', fmt(r.hits || 0)], ['Bots dropped', fmt(r.bots || 0)], ['Conversions', fmt(r.conversions || 0)], ['Live destinations', r.destinations.filter(d => d.active).length + ' / ' + r.destinations.length]]
.map(([k, v], i) => '<div class="tile' + (i === 0 ? ' hi' : '') + '"><span class="k">' + k + '</span><span class="v">' + v + '</span></div>').join('');
renderDest(r);
renderDest(r); renderShare(r);
if (!quiet) window.scrollTo({ top: 0 });
loadStats(r.id);
}
@@ -80,19 +57,49 @@
$('destRows').querySelectorAll('[data-t]').forEach(b => b.addEventListener('click', async () => { const d = r.destinations.find(q => q.id === Number(b.dataset.t)); try { await api('/api/my/rotations/' + r.id + '/dest/' + d.id, { active: !d.active }); load(true); } catch (e) { toast(e.message, true); } }));
$('destRows').querySelectorAll('[data-x]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this destination?', text: 'Its click history stays in the stats.', ok: 'Remove', danger: true })) return; try { await api('/api/my/rotations/' + r.id + '/dest/' + b.dataset.x, { remove: true }); toast('Removed'); load(true); } catch (e) { toast(e.message, true); } }));
}
function renderShare(r) {
const url = linkUrl(r);
const kit = [
['Short post', 'One link, every page I promote, in turn. Take a look: ' + url],
['Email or Telegram line', 'Here is the link I use for everything: ' + url + ' (it always sends you to the right page).'],
['Tracker-ready link', url + '?clickid={clickid}&s1={source} (replace the braces with your network\'s macros)'],
['Sub-id split test', url + '?s1=email-A and ' + url + '?s1=email-B (each shows up under Sources)'],
];
$('shareKit').innerHTML = kit.map(([t, body], i) => '<div class="panel" style="padding:10px 12px"><div style="display:flex;justify-content:space-between;align-items:center;gap:8px"><b>' + esc(t) + '</b><button class="btn sm" type="button" data-cp="' + i + '">Copy</button></div><div class="mono muted" style="font-size:12px;overflow-wrap:anywhere;margin-top:6px" id="kit-' + i + '">' + esc(body) + '</div></div>').join('');
$('shareKit').querySelectorAll('[data-cp]').forEach(b => b.addEventListener('click', () => CR.copy($('kit-' + b.dataset.cp).textContent)));
}
const kv = rows => rows && rows.length ? rows.map(x => '<span style="overflow-wrap:anywhere">' + esc(x.k) + '</span><span class="bar"><i style="width:' + Math.round(x.n / (rows[0].n || 1) * 100) + '%"></i></span><span class="r num">' + fmt(x.n) + '</span>').join('') : '<span class="muted">nothing yet</span><span></span><span></span>';
async function loadStats(id) {
let s = STATS[id]; if (!s) { try { s = await (await fetch('/api/my/rotations/' + id + '/stats')).json(); } catch (e) { s = null; } if (!s || s.error) return; STATS[id] = s; setTimeout(() => { delete STATS[id]; }, 60000); }
let s = STATS[id]; if (!s) { try { s = await CR.get('/api/my/rotations/' + id + '/stats'); } catch (e) { return; } STATS[id] = s; setTimeout(() => { delete STATS[id]; }, 60000); }
if (SEL !== id) return;
const hmax = Math.max(1, ...s.hours); $('hourBars').innerHTML = s.hours.map((n, i) => '<i class="' + (n >= hmax * 0.6 ? '' : 'dim') + '" style="height:' + Math.round(n / hmax * 100) + '%" title="' + i + ':00 · ' + n + '"></i>').join('');
const kv = rows => rows.length ? rows.map(x => '<span>' + esc(x.k) + '</span><span class="bar"><i style="width:' + Math.round(x.n / (rows[0].n || 1) * 100) + '%"></i></span><span class="r num">' + fmt(x.n) + '</span>').join('') : '<span class="muted">nothing yet</span><span></span><span></span>';
$('srcRows').innerHTML = kv(s.source); $('geoRows').innerHTML = kv(s.country);
$('srcRows').innerHTML = kv(s.source); $('geoRows').innerHTML = kv(s.country); $('subRows').innerHTML = kv(s.subs); $('convRows').innerHTML = kv(s.conversions);
const dev = s.device || []; const dt = dev.reduce((n, x) => n + x.n, 0) || 1; $('devRow').textContent = dev.length ? dev.map(x => x.k + ' ' + Math.round(x.n / dt * 100) + '%').join(' · ') : '';
const days = s.days || []; const dmax = Math.max(1, ...days.map(d => d.n));
$('dayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))';
$('dayBars').innerHTML = days.length ? days.map(d => '<i style="height:' + Math.round(d.n / dmax * 100) + '%" title="' + d.day + ' · ' + d.n + '"></i>').join('') : '';
$('dayAxis').innerHTML = days.length ? '<span>' + days[0].day + '</span><span>' + days[days.length - 1].day + '</span>' : '<span class="muted">no clicks recorded yet</span>';
}
// actions
// postbacks (account level)
async function loadPb() {
try { PB = await CR.get('/api/my/postbacks'); } catch (e) { return; }
$('pbInUrl').textContent = PB.inboundUrl + '?key=' + PB.key + '&lsid={lsid}&event=sale&value=0.00';
const rows = PB.postbacks || [];
$('pbRows').innerHTML = rows.length ? rows.map(p => '<div class="rw"><div><b>' + esc(p.name) + '</b><br><span class="mono muted" style="font-size:11px">' + p.method + ' · sent ' + fmt(p.sent) + (p.lastAt ? ' · last ' + esc(String(p.lastStatus)) : '') + '</span></div><div class="mono" style="font-size:11px;overflow-wrap:anywhere">' + esc(p.url) + '</div><div>' + p.events.map(e => '<span class="tag dim">' + e + '</span>').join(' ') + '</div><div>' + (p.enabled ? '<span class="tag ok">ON</span>' : '<span class="tag warn">OFF' + (p.fails >= 10 ? ' · failed 10x' : '') + '</span>') + '</div><div style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap"><button class="btn sm" type="button" data-test="' + p.id + '">Test</button><button class="btn sm" type="button" data-tog="' + p.id + '">' + (p.enabled ? 'Off' : 'On') + '</button><button class="btn sm" type="button" data-edit="' + p.id + '">Edit</button><button class="btn sm danger" type="button" data-del="' + p.id + '" aria-label="Remove">&times;</button></div></div>').join('')
: '<div class="rw"><span class="muted">No postbacks yet. Add your tracker\'s postback URL and pick which events fire it.</span></div>';
const log = PB.log || []; $('pbFoot').textContent = log.length ? 'last delivery: ' + new Date(log[0].ts).toLocaleString() + ' · ' + log[0].name + ' · ' + log[0].event + ' · ' + (log[0].ok ? 'ok ' + log[0].status : 'failed ' + (log[0].status || log[0].note)) + ' · ' + log.filter(l => l.ok).length + ' of the last ' + log.length + ' succeeded' : 'no deliveries yet';
$('pbRows').querySelectorAll('[data-test]').forEach(b => b.addEventListener('click', async () => { b.disabled = true; try { const r = await api('/api/my/postbacks/' + b.dataset.test, { test: true }); toast(r.ok ? 'Test delivered, HTTP ' + r.status : 'Test failed: ' + (r.status || r.note), !r.ok); } catch (e) { toast(e.message, true); } b.disabled = false; loadPb(); }));
$('pbRows').querySelectorAll('[data-tog]').forEach(b => b.addEventListener('click', async () => { const p = rows.find(x => x.id === b.dataset.tog); try { await api('/api/my/postbacks/' + p.id, { enabled: !p.enabled }); loadPb(); } catch (e) { toast(e.message, true); } }));
$('pbRows').querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this postback?', ok: 'Remove', danger: true })) return; try { await api('/api/my/postbacks/' + b.dataset.del, { remove: true }); loadPb(); } catch (e) { toast(e.message, true); } }));
$('pbRows').querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => pbForm(rows.find(x => x.id === b.dataset.edit))));
}
async function pbForm(p) {
const ev = (PB && PB.events) || ['join', 'wallet', 'purchase', 'external'];
const v = await dialog({ title: p ? 'Edit postback' : 'New postback', text: 'Your tracker or network gives you a postback URL with macros. Paste it; LinkSpin fills the click id it saw on the link.',
fields: [{ k: 'name', label: 'Name', value: p ? p.name : '', placeholder: 'BeMob', max: 60 }, { k: 'url', label: 'URL template', value: p ? p.url : '', placeholder: 'https://tracker.example/postback?cid={clickid}&payout={payout}&txid={txid}', mono: true, type: 'url' }, { k: 'events', label: 'Events, comma separated: ' + ev.join(', '), value: p ? p.events.join(',') : 'join,purchase' }, { k: 'method', label: 'Method, GET or POST', value: p ? p.method : 'GET', max: 4 }], ok: p ? 'Save' : 'Create' });
if (!v) return;
try { if (p) await api('/api/my/postbacks/' + p.id, v); else await api('/api/my/postbacks', v); toast(p ? 'Saved' : 'Postback added'); loadPb(); } catch (e) { toast(e.message, true); }
}
async function newSpin() {
const v = await dialog({ title: 'New spin', text: 'Name it for you, not for visitors. You add the pages next.', fields: [{ k: 'name', label: 'Name', placeholder: 'IAP main invite', max: 80 }, { k: 'url', label: 'First page to send people to (optional)', placeholder: 'https://', mono: true, type: 'url' }], ok: 'Create' });
if (!v || !v.name.trim()) return;
@@ -100,16 +107,16 @@
}
$('newBtn').addEventListener('click', newSpin); $('newBtn2').addEventListener('click', newSpin);
$('filter').addEventListener('input', e => { FILTER = e.target.value; renderList(); });
$('copyBtn').addEventListener('click', () => { const r = ROT.find(x => x.id === SEL); if (r) copy(linkUrl(r)); });
$('copyBtn').addEventListener('click', () => { const r = ROT.find(x => x.id === SEL); if (r) CR.copy(linkUrl(r)); });
$('backBtn').addEventListener('click', () => { $('ws').classList.remove('focus'); });
$('renameBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const v = await dialog({ title: 'Rename', fields: [{ k: 'name', label: 'Name', value: r.name, max: 80 }], ok: 'Save' }); if (!v || !v.name.trim()) return; try { await api('/api/my/rotations/' + r.id, { name: v.name }); load(true); } catch (e) { toast(e.message, true); } });
$('pauseBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { paused: !r.paused }); toast(r.paused ? 'Live again' : 'Paused: visitors go to the fallback'); load(true); } catch (e) { toast(e.message, true); } });
$('delBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; if (!await dialog({ title: 'Delete ' + r.name + '?', text: 'The short link stops working for everyone who has it. This cannot be undone.', ok: 'Delete', danger: true })) return; try { await api('/api/my/rotations/' + r.id, { remove: true }); SEL = null; toast('Deleted'); load(); } catch (e) { toast(e.message, true); } });
$('delBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; if (!await dialog({ title: 'Delete ' + r.name + '?', text: 'The short link stops working for everyone who has it. This cannot be undone.', ok: 'Delete', danger: true })) return; try { await api('/api/my/rotations/' + r.id, { remove: true }); SEL = null; history.replaceState(null, '', location.pathname); toast('Deleted'); load(); } catch (e) { toast(e.message, true); } });
$('addBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const url = $('addUrl').value.trim(); if (!url) { $('addUrl').focus(); return; } try { await api('/api/my/rotations/' + r.id + '/dest', { url, label: $('addLabel').value, weight: $('addWeight').value }); $('addUrl').value = ''; $('addLabel').value = ''; toast('Destination added'); load(true); } catch (e) { toast(e.message, true); } });
$('addUrl').addEventListener('keydown', e => { if (e.key === 'Enter') $('addBtn').click(); });
$('fallback').addEventListener('change', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { fallback: $('fallback').value.trim() }); toast('Fallback saved'); load(true); } catch (e) { toast(e.message, true); } });
$('tabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { $('tabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); ['dest', 'hours', 'sources', 'report'].forEach(t => { $('tab-' + t).hidden = t !== b.dataset.tab; }); }));
$('tabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { $('tabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); ['dest', 'hours', 'sources', 'report', 'share'].forEach(t => { $('tab-' + t).hidden = t !== b.dataset.tab; }); }));
$('pbNew').addEventListener('click', () => pbForm(null));
$('backBtn').hidden = !window.matchMedia('(max-width:760px)').matches;
load();
setInterval(() => { if (!document.hidden) load(true); }, 60000);
CR.requireSession(() => { load(); loadPb(); setInterval(() => { if (!document.hidden) load(true); }, 60000); });
})();
+27
View File
@@ -0,0 +1,27 @@
// LinkSpin Reports: one view across every link the member owns (rotator.summary via /api/my/reports).
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt;
let RANGE = 30;
CR.mount({ active: 'reports', title: 'Reports', sub: 'loading', actions: '<div class="range" id="range"><button type="button" data-d="7">7d</button><button type="button" data-d="30" class="on">30d</button><button type="button" data-d="90">90d</button></div>' });
$('range').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { RANGE = Number(b.dataset.d); $('range').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); load(); }));
const kv = (rows, total) => rows && rows.length ? rows.map(x => '<span>' + esc(x.k) + '</span><span class="bar"><i style="width:' + Math.round(x.n / (rows[0].n || 1) * 100) + '%"></i></span><span class="r num">' + fmt(x.n) + (total ? ' <span class="muted">' + Math.round(x.n / total * 100) + '%</span>' : '') + '</span>').join('') : '<span class="muted">nothing yet</span><span></span><span></span>';
async function load() {
let s; try { s = await CR.get('/api/my/reports?days=' + RANGE); } catch (e) { CR.sub('could not load'); return; }
const t = s.totals || {};
CR.sub(RANGE + ' days · ' + fmt(s.links || 0) + ' link' + (s.links === 1 ? '' : 's') + ' · Central time days');
$('tiles').innerHTML = [['Served', fmt(t.served), ''], ['Unique', fmt(t.unique), ''], ['Bots dropped', fmt(t.bots), t.served ? Math.round(t.bots / (t.served + t.bots) * 100) + '% of hits' : ''], ['Joins', fmt(t.joins), t.unique ? (t.joins / t.unique * 100).toFixed(1) + '% of unique' : ''], ['Buyers', fmt(t.purchases), t.joins ? Math.round(t.purchases / t.joins * 100) + '% of joins' : ''], ['Partner conversions', fmt(t.external), '']]
.map(([k, v, n], i) => '<div class="tile' + (i === 4 ? ' hi' : '') + '"><span class="k">' + k + '</span><span class="v">' + v + '</span>' + (n ? '<span class="muted mono" style="font-size:11px">' + n + '</span>' : '') + '</div>').join('');
const days = s.days || []; const dmax = Math.max(1, ...days.map(d => Math.max(d.u, d.b)));
$('dayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))';
$('dayBars').innerHTML = days.map(d => '<i style="height:' + Math.round(d.u / dmax * 100) + '%;background:' + (d.u ? 'var(--accent)' : 'var(--line)') + '" title="' + d.day + ' · ' + d.u + ' unique, ' + d.b + ' bots"></i>').join('');
$('dayAxis').innerHTML = days.length ? '<span>' + days[0].day + '</span><span>' + days[Math.floor(days.length / 2)].day + '</span><span>' + days[days.length - 1].day + '</span>' : '<span class="muted">no clicks yet</span>';
$('srcRows').innerHTML = kv(s.source, t.unique); $('geoRows').innerHTML = kv(s.country, t.unique);
const dev = s.device || []; const dt = dev.reduce((n, x) => n + x.n, 0) || 1; $('devRow').textContent = dev.map(x => x.k + ' ' + Math.round(x.n / dt * 100) + '%').join(' · ');
$('topRows').innerHTML = (s.top || []).length ? s.top.map(x => '<div class="rw"><a href="/links#' + x.id + '" style="text-decoration:none;color:var(--ink)"><b>' + esc(x.name) + '</b><br><span class="mono muted" style="font-size:11px">' + esc(x.code) + '</span></a><span class="r num">' + fmt(x.unique) + '</span><span class="r num">' + fmt(x.hits) + '</span><span class="r num">' + fmt(x.conv) + '</span></div>').join('') : '<div class="rw"><span class="muted">No links yet.</span></div>';
const hmax = Math.max(1, ...(s.hours || [])); $('hourBars').innerHTML = (s.hours || []).map((n, i) => '<i class="' + (n >= hmax * 0.6 ? '' : 'dim') + '" style="height:' + Math.round(n / hmax * 100) + '%" title="' + i + ':00 UTC · ' + n + '"></i>').join('');
const best = (s.hours || []).map((n, i) => [n, i]).sort((a, b) => b[0] - a[0]).slice(0, 3).filter(x => x[0]).map(x => x[1] + ':00');
$('hourNote').textContent = best.length ? 'Busiest hours (UTC): ' + best.join(', ') + '. Hour rules per link come next.' : 'No clicks yet.';
$('convRows').innerHTML = kv(s.conversions || [], 0);
}
CR.requireSession(load);
})();
+41
View File
@@ -0,0 +1,41 @@
// LinkSpin Team: the line as a working table (dashboard + line + carry APIs from the engine).
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt;
let D = null, LINE = null, LEVEL = 1, FILTERS = new Set(), ME = null;
CR.mount({ active: 'team', title: 'Team', sub: 'loading' });
const dayStart = () => { const d = new Date(); d.setHours(0, 0, 0, 0); return d.getTime(); };
const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + ' h ago'; const days = Math.floor(d / 86400e3); return days === 1 ? 'yesterday' : days + ' d ago'; };
const pol = wei => { try { return (Number(BigInt(wei || '0') / 10000000000000000n) / 100).toFixed(2); } catch (e) { return '0.00'; } };
function rows() {
const L = (LINE && LINE.levels || []).find(x => x.level === LEVEL); let ms = L ? L.members.slice() : [];
const f = { today: m => (m.lastSeen || 0) >= dayStart(), wallet: m => !!m.wallet, nopay: m => !!m.wallet && !m.activated, nowallet: m => !m.wallet };
for (const k of FILTERS) ms = ms.filter(f[k]);
ms.sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0));
return ms;
}
function render() {
const ms = rows(); const L = (LINE && LINE.levels || []).find(x => x.level === LEVEL); const total = L ? L.members.length : 0;
$('rows').innerHTML = ms.length ? ms.map(m => { const today = (m.lastSeen || 0) >= dayStart();
return '<div class="rw"><div><b>' + esc(m.name) + (m.own ? ' <span class="tag dim">YOURS</span>' : '') + '</b><br><span class="mono muted" style="font-size:11px">' + (m.memberId ? '#' + m.memberId + ' · ' : '') + 'joined ' + new Date(m.joined).toLocaleDateString() + (m.bought ? ' · $20+ buy' : '') + (m.buyers ? ' · ' + m.buyers + ' qualifying' : '') + '</span></div>'
+ '<span class="mono ' + (today ? 'ok' : (m.lastSeen && Date.now() - m.lastSeen > 3 * 86400e3 ? 'warn' : '')) + '" style="font-size:12px">' + (today ? 'today' : ago(m.lastSeen)) + '</span>'
+ '<span class="mono" style="font-size:11px">' + (m.activated ? '<span class="ok">payouts on</span>' : m.wallet ? '<span class="warn">wallet, payouts off</span>' : '<span class="muted">no wallet</span>') + '</span>'
+ '<span class="r num">' + (m.earnedWei && m.earnedWei !== '0' ? '+' + pol(m.earnedWei) + ' POL' : '<span class="muted">0</span>') + '</span>'
+ '<span class="muted" style="font-size:12px">' + (m.sponsor ? 'via ' + esc(m.sponsor) : (m.email ? esc(m.email) : '')) + '</span></div>'; }).join('')
: '<div class="rw"><span class="muted">' + (total ? 'Nobody matches those filters.' : 'Nobody on this level yet. Share your link, or put it in a spin.') + '</span></div>';
$('foot').textContent = 'level ' + LEVEL + ' · ' + ms.length + (ms.length !== total ? ' of ' + total : '') + ' · surf earnings and full activity are in the classic dashboard for now';
}
async function load() {
try { [D, LINE, ME] = await Promise.all([CR.get('/api/my/dashboard'), CR.get('/api/my/line'), CR.me()]); } catch (e) { CR.sub('could not load'); return; }
const counts = (LINE.counts || []); const refs = D.referrals || [];
CR.sub((counts[0] || 0) + ' direct' + (counts[0] === 1 ? '' : 's') + ' · ' + ((counts[1] || 0) + (counts[2] || 0)) + ' deeper');
$('tiles').innerHTML = [['Directs', fmt(counts[0] || 0), refs.filter(r => r.activated).length + ' with payouts on'], ['Levels 2 and 3', fmt((counts[1] || 0) + (counts[2] || 0)), (counts[1] || 0) + ' · ' + (counts[2] || 0)], ['Qualifying buyers', fmt(D.buyerCount || 0), (D.buyerCount || 0) >= 5 ? 'level 3 open' : (D.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers'], ['Paid by the line', pol(D.earnedWei || '0') + ' POL', (D.earnCount || 0) + ' payouts']]
.map(([k, v, n], i) => '<div class="tile' + (i === 3 ? ' hi' : '') + '"><span class="k">' + k + '</span><span class="v">' + v + '</span><span class="muted mono" style="font-size:11px">' + n + '</span></div>').join('');
const inv = 'https://' + location.host + '/join/' + (ME.username || ME.refCode || ME.memberId || ''); $('invite').textContent = inv; $('copyInvite').onclick = () => CR.copy(inv);
$('sponsor').innerHTML = ME.sponsorName ? '<b>' + esc(ME.sponsorName) + '</b>' + (ME.sponsorId ? ' <span class="mono muted">#' + ME.sponsorId + '</span>' : '') + '<div class="muted">Carried over from the network where you first joined. Nothing to set up, nothing anyone can change.</div>' : (ME.sponsorId ? '<b>member #' + ME.sponsorId + '</b>' : '<span class="muted">Not set. Your first purchase locks a sponsor.</span>');
try { const c = await CR.get('/api/my/carry'); const cl = (c.claims || []).filter(x => x.sponsor === (ME.email || '').toLowerCase()); if (cl.length) { $('claimPanel').hidden = false; $('claims').innerHTML = cl.length + ' of your people can use every tool now; their first purchase waits up to ' + (c.claimDays || 3) + ' days for you to link a wallet and switch on payouts, then walks up your line.'; } } catch (e) {}
render();
}
document.querySelectorAll('.lvl [data-l]').forEach(b => b.addEventListener('click', () => { LEVEL = Number(b.dataset.l); document.querySelectorAll('.lvl [data-l]').forEach(x => x.classList.toggle('on', x === b)); render(); }));
$('chips').querySelectorAll('[data-f]').forEach(b => b.addEventListener('click', () => { const k = b.dataset.f; if (FILTERS.has(k)) FILTERS.delete(k); else FILTERS.add(k); b.classList.toggle('on', FILTERS.has(k)); render(); }));
CR.requireSession(load);
})();
+25
View File
@@ -0,0 +1,25 @@
// LinkSpin Wallet: paid-to-this-wallet, credits, positions, payout history (engine APIs). Connect/buy stay on /my#wallet for now.
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt;
CR.mount({ active: 'wallet', title: 'Wallet', sub: 'loading' });
const pol = wei => { try { return (Number(BigInt(wei || '0') / 10000000000000000n) / 100).toFixed(2); } catch (e) { return '0.00'; } };
async function load() {
let D, ME, POS = [], E = null;
try { [D, ME] = await Promise.all([CR.get('/api/my/dashboard'), CR.me()]); } catch (e) { CR.sub('could not load'); return; }
try { POS = await CR.get('/api/my/positions'); } catch (e) {}
try { E = await CR.get('/api/my/activity'); } catch (e) {}
const addr = ME.address || ''; const on = !!ME.memberId;
CR.sub(addr ? addr.slice(0, 6) + '…' + addr.slice(-4) + (on ? ' · payouts on' : ' · payouts off') : 'no wallet linked');
$('tiles').innerHTML = [['Paid to this wallet', pol(D.earnedWei || '0') + ' POL', (D.earnCount || 0) + ' transactions'], ['Credits', fmt((D.credits || 0) + (D.earnedCredits || 0)), fmt(D.credits || 0) + ' purchased · ' + fmt(D.earnedCredits || 0) + ' earned'], ['In campaigns', fmt(D.inCampaigns || 0), 'reserved by live campaigns'], ['Qualifying buyers', fmt(D.buyerCount || 0), (D.buyerCount || 0) >= 5 ? 'level 3 open' : (D.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers']]
.map(([k, v, n], i) => '<div class="tile' + (i === 0 ? ' hi' : '') + '"><span class="k">' + k + '</span><span class="v">' + v + '</span><span class="muted mono" style="font-size:11px">' + n + '</span></div>').join('');
$('walletBox').innerHTML = addr ? '<div class="code" style="display:block">' + esc(addr) + '</div><div style="margin-top:8px">' + (on ? '<span class="ok"><span class="dot"></span>PAYOUTS ON · member #' + ME.memberId + '</span>' : '<span class="warn"><span class="dot"></span>WALLET LINKED · PAYOUTS OFF</span><div class="muted" style="margin-top:4px">Switch payouts on so the people you bring pay you from their first purchase.</div>') + '</div>' : '<span class="warn">No wallet linked yet.</span><div class="muted" style="margin-top:4px">Link one to be paid. Your email account keeps working either way.</div>';
const pays = E && Array.isArray(E.earnings) ? E.earnings : [];
$('payRows').innerHTML = pays.length ? pays.slice(0, 25).map(x => '<div class="rw"><span class="mono muted" style="font-size:12px">' + new Date((x.ts || 0) * (x.ts > 1e12 ? 1 : 1000)).toLocaleString() + '</span><span><b>' + esc(x.buyerName || x.fromName || (x.buyerId ? 'member #' + x.buyerId : x.type === 'AwardPaid' ? 'award' : 'member')) + '</b></span><span class="mono">' + (x.tier ? 'L' + x.tier + ' · ' + (x.tier === 1 ? '50%' : x.tier === 2 ? '20%' : '10%') : (x.type === 'AwardPaid' ? 'award' : '')) + '</span><span class="mono">' + (x.priceCents ? '$' + (x.priceCents / 100) : '') + '</span><span class="r num ok">+' + pol(x.amountWei || '0') + ' POL</span>' + (x.tx ? '<a class="mono" style="font-size:11px" href="/tx/' + esc(x.tx) + '" target="_blank" rel="noopener">' + esc(String(x.tx).slice(0, 10)) + '…</a>' : '<span></span>') + '</div>').join('')
: '<div class="rw"><span class="muted">No payouts yet. They appear here the moment someone in your line buys.</span></div>';
$('payFoot').textContent = 'every line is a Polygon transaction · nothing is held by the site';
const rows = Array.isArray(POS) ? POS : (POS && (POS.positions || POS.list)) || [];
$('posRows').innerHTML = rows.length ? rows.map(p => '<div class="rw"><span><b>' + (p.main ? 'Main position' : 'Position') + '</b> <span class="mono muted">' + (p.memberId ? '#' + p.memberId : 'not on chain yet') + '</span><br><span class="mono muted" style="font-size:11px">' + esc(String(p.address || '').slice(0, 10)) + '…</span></span><span class="num">' + fmt(p.avail || 0) + '</span><span>' + (p.memberId ? '<span class="tag ok">ACTIVE</span>' : '<span class="tag dim">PENDING</span>') + '</span></div>').join('')
: '<div class="rw"><span class="muted">' + (addr ? 'Main wallet only.' : 'No positions yet.') + '</span></div>';
}
CR.requireSession(load);
})();
+69 -82
View File
@@ -6,9 +6,9 @@
<meta name="robots" content="noindex, nofollow">
<title>Links · LinkSpin</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700&family=JetBrains+Mono:wght@500;700&display=swap">
<link rel="stylesheet" href="/assets/cr.css?v=20260929a">
<link rel="stylesheet" href="/assets/cr.css?v=20260929b">
<style>
.ws{display:grid;grid-template-columns:320px minmax(0,1fr);flex:1;min-height:0}
.ws{display:grid;grid-template-columns:320px minmax(0,1fr);min-height:calc(100vh - 53px)}
.list{border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0}
.list .hd{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid var(--line)}
.list .hd h2{font-family:var(--display);font-size:20px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;margin:0}
@@ -27,103 +27,90 @@
.empty{padding:40px 24px;color:var(--muted);text-align:center;display:grid;gap:10px;justify-items:center}
.two{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:16px}
.kv{display:grid;grid-template-columns:minmax(0,1fr) 60px 60px;gap:8px;font-size:12px;align-items:center}
@media (max-width:900px){.two{grid-template-columns:1fr}.dest .hd{display:none}.dest .rw{grid-template-columns:1fr 1fr}}
.pb .hd,.pb .rw{grid-template-columns:minmax(0,1.2fr) minmax(0,2fr) 120px 90px 110px}
@media (max-width:900px){.two{grid-template-columns:1fr}.dest .hd{display:none}.dest .rw{grid-template-columns:1fr 1fr}.pb .hd{display:none}.pb .rw{grid-template-columns:1fr}}
@media (max-width:760px){.ws{grid-template-columns:minmax(0,1fr)}.tabs{flex-wrap:wrap}.list{border-right:0;border-bottom:1px solid var(--line);max-height:44vh}.ws.focus .list{display:none}.ws:not(.focus) .detail{display:none}
.dhead{padding:12px 16px}.dhead .code{flex:1 1 100%;word-break:break-all}.dbody{padding:12px 16px}
.dest .rw{grid-template-columns:1fr}.dest .rw .r{text-align:left}#addRow{grid-template-columns:1fr}.tiles{grid-template-columns:repeat(2,minmax(0,1fr))}.kv{grid-template-columns:minmax(0,1fr) 50px 50px}}
</style>
</head>
<body>
<div class="app">
<nav class="rail" aria-label="LinkSpin">
<div class="mark" aria-hidden="true"></div>
<a href="/links" class="on" title="Links" aria-label="Links"><svg viewBox="0 0 24 24"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg></a>
<a href="/my#promo" title="Pages" aria-label="Pages"><svg viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="2"/><path d="M8 9h8M8 13h6"/></svg></a>
<a href="/my#campaigns" title="Zones" aria-label="Zones"><svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg></a>
<a href="/my#earnings" title="Reports" aria-label="Reports"><svg viewBox="0 0 24 24"><path d="M4 19V9M10 19V5M16 19v-8M22 19H2"/></svg></a>
<a href="/my#line" title="Team" aria-label="Team"><svg viewBox="0 0 24 24"><circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.5"/><path d="M3 19c0-3 3-5 6-5s6 2 6 5M15 15c3 0 6 1.5 6 4"/></svg></a>
<a href="/my#wallet" title="Wallet" aria-label="Wallet"><svg viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M16 12h3"/></svg></a>
<span class="sp"></span>
</nav>
<div class="main">
<div class="topbar">
<h1>Links</h1>
<span class="muted mono" id="tbSub">loading</span>
<span class="grow"></span>
<button class="btn pri" id="newBtn" type="button">+ New spin</button>
<div id="page">
<div class="ws" id="ws">
<div class="list">
<div class="hd"><h2 id="listCount">Links</h2><span class="muted mono" id="listSort">by clicks, 7 days</span></div>
<div class="flt"><input class="field" id="filter" type="search" placeholder="Filter links" aria-label="Filter links"></div>
<div class="items" id="items"></div>
</div>
<div id="signin" class="empty" hidden>
<div class="h-disp" style="font-size:18px">Sign in to see your links</div>
<div class="muted">Your links, destinations and numbers live on your account.</div>
<a class="btn pri" href="/my?next=/links">Sign in</a>
</div>
<div class="ws" id="ws" hidden>
<div class="list">
<div class="hd"><h2 id="listCount">Links</h2><span class="muted mono" id="listSort">by clicks, 7 days</span></div>
<div class="flt"><input class="field" id="filter" type="search" placeholder="Filter links" aria-label="Filter links"></div>
<div class="items" id="items"></div>
</div>
<div class="detail" id="detail">
<div class="empty" id="noSel"><div class="h-disp" style="font-size:18px">Pick a link</div><div class="muted">Or make your first one. Paste the pages you promote, get one short link that spins them.</div><button class="btn pri" type="button" id="newBtn2">+ New spin</button></div>
<div id="sel" hidden>
<div class="dhead">
<button class="btn sm" type="button" id="backBtn" hidden>&larr; Links</button>
<h2 id="dName">Link</h2>
<span class="code" id="dUrl"></span>
<button class="btn sm" type="button" id="copyBtn">Copy</button>
<span class="mono" id="dLive"></span>
<span class="grow"></span>
<button class="btn sm" type="button" id="renameBtn">Rename</button>
<button class="btn sm" type="button" id="pauseBtn">Pause</button>
<button class="btn sm danger" type="button" id="delBtn">Delete</button>
<div class="detail" id="detail">
<div class="empty" id="noSel"><div class="h-disp" style="font-size:18px">Pick a link</div><div class="muted">Or make your first one. Paste the pages you promote, get one short link that spins them.</div><button class="btn pri" type="button" id="newBtn2">+ New spin</button></div>
<div id="sel" hidden>
<div class="dhead">
<button class="btn sm" type="button" id="backBtn" hidden>&larr; Links</button>
<h2 id="dName">Link</h2>
<span class="code" id="dUrl"></span>
<button class="btn sm" type="button" id="copyBtn">Copy</button>
<span class="mono" id="dLive"></span>
<span class="grow"></span>
<button class="btn sm" type="button" id="renameBtn">Rename</button>
<button class="btn sm" type="button" id="pauseBtn">Pause</button>
<button class="btn sm danger" type="button" id="delBtn">Delete</button>
</div>
<div class="dbody">
<div class="tiles" id="tiles"></div>
<div class="tabs" id="tabs">
<button type="button" class="on" data-tab="dest">Destinations</button>
<button type="button" data-tab="hours">Hours</button>
<button type="button" data-tab="sources">Sources</button>
<button type="button" data-tab="report">Report</button>
<button type="button" data-tab="share">Share kit</button>
</div>
<div class="dbody">
<div class="tiles" id="tiles"></div>
<div class="tabs" id="tabs">
<button type="button" class="on" data-tab="dest">Destinations</button>
<button type="button" data-tab="hours">Hours</button>
<button type="button" data-tab="sources">Sources</button>
<button type="button" data-tab="report">Report</button>
<div id="tab-dest">
<div class="tbl dest">
<div class="hd"><span>Destination</span><span>Weight</span><span class="r">Clicks</span><span class="r">Unique</span><span>Status</span><span></span></div>
<div id="destRows"></div>
<div class="ft" id="destFoot"></div>
</div>
<div id="tab-dest">
<div class="tbl dest">
<div class="hd"><span>Destination</span><span>Weight</span><span class="r">Clicks</span><span class="r">Unique</span><span>Status</span><span></span></div>
<div id="destRows"></div>
<div class="ft" id="destFoot"></div>
</div>
<div class="panel" style="margin-top:12px">
<h2>Add a destination</h2>
<div style="display:grid;grid-template-columns:minmax(0,2fr) minmax(0,1fr) 90px auto;gap:8px;align-items:end" id="addRow">
<label class="lbl">Page you are sending people to<input class="field mono" id="addUrl" type="url" placeholder="https://"></label>
<label class="lbl">Label<input class="field" id="addLabel" type="text" placeholder="Join page, instant hook" maxlength="60"></label>
<label class="lbl">Weight<input class="field mono" id="addWeight" type="number" min="1" max="100" value="10"></label>
<button class="btn pri" type="button" id="addBtn">Add</button>
</div>
<label class="lbl">Fallback, used when every destination is paused or the link is paused<input class="field mono" id="fallback" type="url" placeholder="https://"></label>
<div class="panel" style="margin-top:12px">
<h2>Add a destination</h2>
<div style="display:grid;grid-template-columns:minmax(0,2fr) minmax(0,1fr) 90px auto;gap:8px;align-items:end" id="addRow">
<label class="lbl">Page you are sending people to<input class="field mono" id="addUrl" type="url" placeholder="https://"></label>
<label class="lbl">Label<input class="field" id="addLabel" type="text" placeholder="Join page, instant hook" maxlength="60"></label>
<label class="lbl">Weight<input class="field mono" id="addWeight" type="number" min="1" max="100" value="10"></label>
<button class="btn pri" type="button" id="addBtn">Add</button>
</div>
<div class="muted">Macros in a destination are filled per visitor: <span class="mono">{clickid} {subid} {s1}…{s5} {source} {country} {device} {lsid}</span>. Example: <span class="mono">https://tracker.example/?cid={clickid}&amp;src={source}</span></div>
<label class="lbl">Fallback, used when every destination is paused or the link is paused<input class="field mono" id="fallback" type="url" placeholder="https://"></label>
</div>
<div id="tab-hours" hidden>
<div class="panel"><h2>Clicks by hour, UTC, all time</h2><div class="bars" id="hourBars" style="grid-template-columns:repeat(24,minmax(0,1fr))"></div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div><div class="muted">Hour rules (open a destination only at set hours) come in the next pass; this is where they will live.</div></div>
</div>
<div id="tab-sources" hidden>
<div class="two">
<div class="panel"><h2>Sources</h2><div id="srcRows" class="kv"></div></div>
<div class="panel"><h2>Countries · devices</h2><div id="geoRows" class="kv"></div><div id="devRow" class="muted"></div></div>
</div>
</div>
<div id="tab-report" hidden>
<div class="panel"><h2>Clicks by day, last 30</h2><div class="bars" id="dayBars"></div><div class="axis" id="dayAxis"></div></div>
</div>
<div id="tab-hours" hidden>
<div class="panel"><h2>Clicks by hour, UTC, all time</h2><div class="bars" id="hourBars" style="grid-template-columns:repeat(24,minmax(0,1fr))"></div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div><div class="muted">Hour rules (open a destination only at set hours) come in the next pass; this is where they will live.</div></div>
</div>
<div id="tab-sources" hidden>
<div class="two">
<div class="panel"><h2>Sources</h2><div id="srcRows" class="kv"></div><h2 style="margin-top:8px">Click ids and sub ids seen</h2><div id="subRows" class="kv"></div></div>
<div class="panel"><h2>Countries · devices</h2><div id="geoRows" class="kv"></div><div id="devRow" class="muted"></div><h2 style="margin-top:8px">Conversions</h2><div id="convRows" class="kv"></div></div>
</div>
</div>
<div id="tab-report" hidden>
<div class="panel"><h2>Clicks by day, last 30</h2><div class="bars" id="dayBars"></div><div class="axis" id="dayAxis"></div></div>
</div>
<div id="tab-share" hidden>
<div class="panel"><h2>Share kit</h2><div class="muted">Ready to paste. The link is yours; every click is counted and spun.</div><div id="shareKit" style="display:grid;gap:10px"></div></div>
</div>
</div>
</div>
</div>
</div>
<div class="dbody" id="pbWrap" style="border-top:1px solid var(--line)">
<div class="panel pbpanel">
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap"><h2>Postbacks</h2><span class="muted">Tell your tracker or traffic network when a click converts. Fired server to server with the click id that came in on the link.</span><span class="grow"></span><button class="btn sm" type="button" id="pbNew">+ Postback</button></div>
<div class="tbl pb"><div class="hd"><span>Name</span><span>URL template</span><span>Events</span><span>Status</span><span></span></div><div id="pbRows"></div><div class="ft" id="pbFoot"></div></div>
<div class="muted">Macros: <span class="mono">{clickid} {subid} {s1}…{s5} {source} {event} {payout} {currency} {txid} {lsid} {code}</span>. Inbound: partners can report a conversion to <span class="code" id="pbInUrl"></span> with your partner key.</div>
</div>
</div>
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<div id="modalHost"></div>
<script src="/assets/links.js?v=20260929a"></script>
<script src="/assets/cr-shell.js?v=20260929a"></script>
<script src="/assets/links.js?v=20260929b"></script>
</body>
</html>
+44
View File
@@ -0,0 +1,44 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="robots" content="noindex, nofollow">
<title>Reports · LinkSpin</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700&family=JetBrains+Mono:wght@500;700&display=swap">
<link rel="stylesheet" href="/assets/cr.css?v=20260929b">
<style>
.body{padding:16px 24px;display:grid;gap:16px}
.two{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:16px}
.grid2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
.kv{display:grid;grid-template-columns:minmax(0,1fr) 60px 70px;gap:8px;font-size:12px;align-items:center}
.range{display:flex;border:1px solid var(--line-strong);border-radius:var(--r);overflow:hidden} .range button{background:transparent;border:0;color:var(--muted);font-family:var(--mono);font-size:12px;padding:5px 10px;cursor:pointer} .range button.on{background:var(--accent);color:var(--accent-ink)}
.top .hd,.top .rw{grid-template-columns:minmax(0,1fr) 80px 80px 80px}
@media (max-width:900px){.two,.grid2{grid-template-columns:1fr}.body{padding:12px 16px}}
</style>
</head>
<body>
<div id="page">
<div class="body">
<div class="tiles" id="tiles"></div>
<div class="two">
<div class="panel">
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px"><h2>Unique visitors by day</h2><div style="display:flex;gap:14px;font-size:11px;color:var(--ink-2)"><span><span style="display:inline-block;width:10px;height:10px;background:var(--accent);vertical-align:middle;margin-right:5px"></span>unique</span><span><span style="display:inline-block;width:10px;height:10px;background:var(--line);vertical-align:middle;margin-right:5px"></span>bots</span></div></div>
<div class="bars" id="dayBars" style="height:190px"></div><div class="axis" id="dayAxis"></div>
<div class="grid2" style="margin-top:6px">
<div><div class="sec" style="margin-bottom:6px">By source</div><div class="kv" id="srcRows"></div></div>
<div><div class="sec" style="margin-bottom:6px">By country · device</div><div class="kv" id="geoRows"></div><div class="muted" id="devRow" style="margin-top:6px"></div></div>
</div>
</div>
<div style="display:grid;gap:16px;align-content:start">
<div class="panel"><h2>Top links</h2><div class="tbl top"><div class="hd"><span>Link</span><span class="r">Unique</span><span class="r">Clicks</span><span class="r">Conv.</span></div><div id="topRows"></div></div></div>
<div class="panel"><h2>Your best hours</h2><div class="bars" id="hourBars" style="grid-template-columns:repeat(24,minmax(0,1fr));height:80px"></div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div><div class="muted" id="hourNote"></div></div>
<div class="panel"><h2>Conversions</h2><div class="kv" id="convRows"></div><div class="muted">Joins, wallets and purchases matched to a click on one of your links, plus anything a partner reported by postback.</div></div>
</div>
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20260929a"></script>
<script src="/assets/reports.js?v=20260929a"></script>
</body>
</html>
+44
View File
@@ -0,0 +1,44 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="robots" content="noindex, nofollow">
<title>Team · LinkSpin</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700&family=JetBrains+Mono:wght@500;700&display=swap">
<link rel="stylesheet" href="/assets/cr.css?v=20260929b">
<style>
.body{padding:16px 24px;display:grid;gap:16px}
.two{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:16px}
.line .hd,.line .rw{grid-template-columns:minmax(0,2fr) 110px 130px 110px 110px}
.lvl{display:flex;gap:4px;padding:10px 16px;border-bottom:1px solid var(--line);align-items:center;flex-wrap:wrap}
.lvl button{background:transparent;border:1px solid transparent;border-radius:var(--r);color:var(--muted);font-family:var(--display);font-size:14px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;padding:4px 10px;cursor:pointer}
.lvl button.on{background:var(--bg);border-color:var(--accent);color:var(--accent-hi)}
.chips{display:flex;gap:6px;flex-wrap:wrap} .chip{font-size:11px;color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:2px 9px;cursor:pointer;background:transparent} .chip.on{border-color:var(--accent);color:var(--ink);background:rgba(59,157,255,.1)}
@media (max-width:900px){.two{grid-template-columns:1fr}.line .hd{display:none}.line .rw{grid-template-columns:1fr 1fr}.body{padding:12px 16px}}
</style>
</head>
<body>
<div id="page">
<div class="body">
<div class="tiles" id="tiles"></div>
<div class="two">
<div class="tbl line">
<div class="lvl"><button type="button" class="on" data-l="1">Directs</button><button type="button" data-l="2">Level 2</button><button type="button" data-l="3">Level 3</button><span class="grow"></span><span class="chips" id="chips"><button class="chip" type="button" data-f="today">Active today</button><button class="chip" type="button" data-f="wallet">Wallet linked</button><button class="chip" type="button" data-f="nopay">Wallet, payouts off</button><button class="chip" type="button" data-f="nowallet">No wallet</button></span></div>
<div class="hd"><span>Member</span><span>Last seen</span><span>Wallet</span><span class="r">Paid you</span><span>Came from</span></div>
<div id="rows"></div>
<div class="ft" id="foot"></div>
</div>
<div style="display:grid;gap:16px;align-content:start">
<div class="panel"><h2>Your invite link</h2><span class="code" id="invite"></span><div style="display:flex;gap:8px"><button class="btn sm" type="button" id="copyInvite">Copy</button><a class="btn sm" href="/links">Put it in a spin</a></div><div class="muted">Everyone who joins through it becomes part of your line. Payouts lock to you once your payouts are on.</div></div>
<div class="panel"><h2>Your sponsor</h2><div id="sponsor" class="ink2">loading</div></div>
<div class="panel" id="claimPanel" hidden><h2 class="warn">Waiting on a wallet</h2><div id="claims" class="ink2"></div></div>
<div class="panel"><h2>Message your line</h2><div class="muted">One broadcast a day, on-site and email.</div><a class="btn sm" href="/my#line" style="justify-self:start">Write one in the classic dashboard</a></div>
</div>
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20260929a"></script>
<script src="/assets/team.js?v=20260929a"></script>
</body>
</html>
+37
View File
@@ -0,0 +1,37 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="robots" content="noindex, nofollow">
<title>Wallet · LinkSpin</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700&family=JetBrains+Mono:wght@500;700&display=swap">
<link rel="stylesheet" href="/assets/cr.css?v=20260929b">
<style>
.body{padding:16px 24px;display:grid;gap:16px}
.two{display:grid;grid-template-columns:minmax(0,1fr) 380px;gap:16px}
.pay .hd,.pay .rw{grid-template-columns:110px minmax(0,1.4fr) 70px 110px 110px 120px}
.pos .rw{grid-template-columns:minmax(0,1fr) 120px 100px}
@media (max-width:900px){.two{grid-template-columns:1fr}.pay .hd{display:none}.pay .rw{grid-template-columns:1fr 1fr}.body{padding:12px 16px}}
</style>
</head>
<body>
<div id="page">
<div class="body">
<div class="tiles" id="tiles"></div>
<div class="two">
<div style="display:grid;gap:16px;align-content:start">
<div class="tbl pay"><div class="hd"><span>When</span><span>From</span><span>Level</span><span>Package</span><span class="r">You got</span><span>Transaction</span></div><div id="payRows"></div><div class="ft" id="payFoot"></div></div>
<div class="tbl pos"><div class="hd" style="grid-template-columns:minmax(0,1fr) 120px 100px"><span>Position</span><span>Credits</span><span>Status</span></div><div id="posRows"></div><div class="ft">linked positions share this account's credits; levels pay on the main position</div></div>
</div>
<div style="display:grid;gap:16px;align-content:start">
<div class="panel"><h2>This wallet</h2><div id="walletBox" class="ink2">loading</div><div style="display:flex;gap:8px;flex-wrap:wrap"><a class="btn sm" href="/my#wallet">Connect, switch on payouts, buy</a></div><div class="muted">Connecting a wallet and buying a package use the wallet screen in the classic dashboard until the on-chain flow moves into this shell.</div></div>
<div class="panel"><h2>How you get paid</h2><div class="ink2">Every package splits in the same transaction: 50% direct sponsor, 20% level 2, 10% level 3, 20% platform. Nothing is held by the site, ever. Your sponsor is paid the moment your purchase settles.</div></div>
</div>
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20260929a"></script>
<script src="/assets/wallet-screen.js?v=20260929a"></script>
</body>
</html>
+45 -8
View File
@@ -8,15 +8,15 @@ const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
let DATA_DIR = null, geo = null;
let DATA_DIR = null, geo = null, OWN_HOSTS = () => [];
const DAY = 86400000;
const J = {
db: null,
FILE: () => path.join(DATA_DIR, 'rotator.json'),
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, rotations: [], hits: [] }; } },
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, rotations: [], hits: [], conv: [] }; } if (!this.db.conv) this.db.conv = []; },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }
};
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; J.load(); }
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); J.load(); }
const norm = e => String(e || '').trim().toLowerCase();
const newCode = () => { const a = 'abcdefghjkmnpqrstuvwxyz23456789'; let s = ''; for (let i = 0; i < 6; i++) s += a[crypto.randomInt(a.length)]; return s; };
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
@@ -27,7 +27,8 @@ function pub(r) {
const since7 = Date.now() - 7 * DAY;
const perDest = {};
for (const h of hits) { const d = perDest[h.d] = perDest[h.d] || { hits: 0, hits7: 0, uniques: new Set() }; d.hits++; if (h.ts >= since7) d.hits7++; d.uniques.add(h.v); }
return { id: r.id, code: r.code, name: r.name, owner: r.owner, created: r.created, fallback: r.fallback || '', paused: !!r.paused,
const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
return { id: r.id, code: r.code, name: r.name, owner: r.owner, created: r.created, fallback: r.fallback || '', paused: !!r.paused, conversions: conv.length, convBy,
destinations: r.destinations.map(d => Object.assign({}, d, { hits: (perDest[d.id] || { hits: 0 }).hits, hits7: (perDest[d.id] || { hits7: 0 }).hits7, uniques: (perDest[d.id] || { uniques: new Set() }).uniques.size })),
hits: hits.length, hits7: hits.filter(h => h.ts >= since7).length, uniques: new Set(hits.map(h => h.v)).size, bots: hits.filter(h => h.bot).length };
}
@@ -86,10 +87,43 @@ async function resolve(code, req) {
let country = ''; try { country = geo && geo.countryOf ? (geo.countryOf(ip) || '') : ''; } catch (e) {}
const ref = String(req.headers.referer || ''); let src = 'direct'; try { if (ref) src = new URL(ref).hostname.replace(/^www\./, ''); } catch (e) {}
const device = /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop';
J.db.hits.push({ r: r.id, d: d ? d.id : 0, ts: Date.now(), v, c: country, s: src, dv: device, bot: bot ? 1 : 0 });
// click ids and sub ids that rode in on the link (tracker / traffic-network params), kept per click
const q = {}; try { const sp = new URL(req.url, 'http://x').searchParams; let n = 0; for (const [k, val] of sp) { const key = String(k).toLowerCase(); if (n >= 20) break; if (/^(clickid|click_id|cid|subid|sub_id|s[1-5]|sub[1-5]|t[1-5]|aff_sub[1-5]?|utm_(source|medium|campaign|term|content)|src|source|campaign|zone|placement)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } } catch (e) {}
const id = crypto.randomBytes(6).toString('hex').slice(0, 10);
J.db.hits.push({ id, r: r.id, d: d ? d.id : 0, ts: Date.now(), v, c: country, s: src, dv: device, bot: bot ? 1 : 0, q: Object.keys(q).length ? q : undefined });
if (J.db.hits.length > 200000) J.db.hits = J.db.hits.slice(-150000);
J.save();
return { url, dest: d, rotation: r };
let out = url;
if (out) {
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: src, country, device, lsid: id, code: r.code };
for (const [k, val] of Object.entries(q)) if (vals[k] == null) vals[k] = val;
out = out.replace(/\{([a-z0-9_]{1,24})\}/gi, (m, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()]));
// our own pages get the click id automatically, so a join can be matched back to this click without any macro
try { const t = new URL(out); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid')) { t.searchParams.set('lsid', id); out = t.toString(); } } catch (e) {}
}
return { url: out, dest: d, rotation: r, lsid: id };
}
// conversions: record an event against the click that brought the person (dedupe per click + event)
async function convert(lsid, ev, facts) {
const h = J.db.hits.find(x => x.id === String(lsid)); if (!h) return null;
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
if (!J.db.conv.some(c => c.lsid === h.id && c.ev === ev)) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
return { owner: r.owner, code: r.code, rotationId: r.id, q: h.q || {}, s: h.s, c: h.c, dv: h.dv };
}
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
// one view across everything a member owns, for Reports
async function summary(owner, days) {
const mine = J.db.rotations.filter(r => r.owner === norm(owner)); const ids = new Set(mine.map(r => r.id));
const since = Date.now() - (Number(days) || 30) * DAY;
const all = J.db.hits.filter(h => ids.has(h.r) && h.ts >= since); const hits = all.filter(h => !h.bot);
const by = key => { const m = {}; for (const h of hits) { const k = h[key] || '(none)'; m[k] = (m[k] || 0) + 1; } return Object.entries(m).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })); };
const dayMap = {}; for (const h of all) { const k = ctDay(h.ts); const d = dayMap[k] = dayMap[k] || { day: k, u: new Set(), b: 0 }; if (h.bot) d.b++; else d.u.add(h.v); }
const dlist = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1).map(d => ({ day: d.day, u: d.u.size, b: d.b }));
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
const conv = J.db.conv.filter(c => ids.has(c.r) && c.ts >= since); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
const top = mine.map(r => { const hs = hits.filter(h => h.r === r.id); return { id: r.id, name: r.name, code: r.code, hits: hs.length, unique: new Set(hs.map(h => h.v)).size, conv: conv.filter(c => c.r === r.id).length }; }).sort((a, b) => b.unique - a.unique).slice(0, 10);
return { links: mine.length, totals: { served: hits.length, unique: new Set(hits.map(h => h.v)).size, bots: all.length - hits.length, joins: convBy.join || 0, wallets: convBy.wallet || 0, purchases: convBy.purchase || 0, external: convBy.external || 0 },
days: dlist, source: by('s'), country: by('c'), device: by('dv'), hours, top, conversions: Object.entries(convBy).map(([k, n]) => ({ k, n })).sort((a, b) => b.n - a.n) };
}
async function stats(owner, id) {
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return null;
@@ -97,8 +131,11 @@ async function stats(owner, id) {
const by = key => { const m = {}; for (const h of hits) { const k = h[key] || '(none)'; m[k] = (m[k] || 0) + 1; } return Object.entries(m).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })); };
const days = {}; for (const h of hits) { const k = new Date(h.ts).toISOString().slice(0, 10); days[k] = (days[k] || 0) + 1; }
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length };
const subs = {}; for (const h of hits) if (h.q) for (const [k, v] of Object.entries(h.q)) { const key = k + '=' + v; subs[key] = (subs[key] || 0) + 1; }
const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length,
subs: Object.entries(subs).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
}
function totals() { return { rotations: J.db.rotations.length, hits: J.db.hits.length }; }
module.exports = { init, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals };
module.exports = { init, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary };
+37 -3
View File
@@ -38,7 +38,8 @@ const leaderboard = require('./leaderboard');
const toolkit = require('./toolkit');
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
const carry = require('./carry'); // sponsor carry-over: engine activation, claim window, notices
const rotator = require('./rotator'); // the rotator: rotations, weighted destinations, /r/<code>
const rotator = require('./rotator');
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29) // the rotator: rotations, weighted destinations, /r/<code>
const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15)
const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15)
const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12)
@@ -367,7 +368,8 @@ async function frameCheck(url) {
}
async function boot() {
await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode)
chain.init({ onEvent: ev => { attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev)); emailOnEvent(ev).catch(() => {}); telegramOnEvent(ev).catch(() => {}); } });
chain.init({ onEvent: ev => { attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev)); emailOnEvent(ev).catch(() => {}); telegramOnEvent(ev).catch(() => {});
if (ev && ev.type === 'Purchase' && ev.buyerId) accounts.byMemberId(Number(ev.buyerId)).then(a => { if (a) return postbacks.convertFor(a.email, 'purchase', { payout: (Number(ev.priceCents) || 0) / 100, currency: 'USD', txid: ev.tx || '' }); }).catch(() => {}); } });
auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: 'linkspin-test.saasy.top' });
accounts.init({ dataDir: DATA_DIR });
ads.init({ dataDir: DATA_DIR, chain });
@@ -384,7 +386,9 @@ async function boot() {
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
registry.init({ dataDir: DATA_DIR });
carry.init({ dataDir: DATA_DIR, accounts, registry, chain, mailer, messages, siteConfig, adminEmail: ADMIN_EMAIL, host: SITE_HOST });
rotator.init({ dataDir: DATA_DIR, geo });
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean));
rotator.init({ dataDir: DATA_DIR, geo, ownHosts });
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator });
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } });
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: 'https://linkspin-test.saasy.top' });
@@ -899,6 +903,7 @@ const server = http.createServer(async (req, res) => {
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit
const set = [];
set.push('iap.sponsor=' + tok + cookieTail); // last touch wins
{ const lsid = String(u.searchParams.get('lsid') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution)
const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup
if (ang) set.push('iap.angle=' + angle + cookieTail);
if (!cookies['iap.ref']) set.push('iap.ref=' + encodeURIComponent(coach.refHost(req.headers.referer)) + cookieTail); // first-touch source
@@ -1061,6 +1066,7 @@ const server = http.createServer(async (req, res) => {
const ref = parseCookies(req)['iap.sponsor'] || ''; // last-touch attribution, locked at account creation
const r = await accounts.signup(b.email, b.password, ref);
if (r.error) return json(res, 400, r);
{ const lc = parseCookies(req)['ls.click']; if (lc) { postbacks.bindClick(String(b.email || '').trim().toLowerCase(), lc); postbacks.convertFor(String(b.email || '').trim().toLowerCase(), 'join', {}).catch(() => {}); } }
// sponsor is notified once the new member picks a username (onboarding),
// so the email can name them — see /api/my/profile
if (b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent
@@ -1116,6 +1122,7 @@ const server = http.createServer(async (req, res) => {
const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged
if (r.error) return json(res, 400, r);
if (r.created) carry.onJoin(r.account, !!ref).catch(() => {}); // network sponsor carries over when no link was used (LinkSpin)
if (r.created) { const lc = parseCookies(req)['ls.click']; if (lc) { postbacks.bindClick(e, lc); postbacks.convertFor(e, 'join', {}).catch(() => {}); } }
// the lead is in the door: queue the getting-started sequence (opt-in box is pre-checked on both forms)
if (r.created && (b.followups || b.newsletter)) drip.enqueue(e, ref, via).catch(() => {});
// a wallet-only session (signed with a wallet, no account) finishing setup:
@@ -1185,6 +1192,7 @@ const server = http.createServer(async (req, res) => {
}
if (s && s.email) {
const lr = await accounts.linkWallet(s.email, r.address);
if (!lr.error) postbacks.convertFor(s.email, 'wallet', {}).catch(() => {});
if (lr.error) return json(res, 400, lr);
await auth.updateSession(s.token, { address: r.address, memberId });
return json(res, 200, { ok: true, linked: true, address: r.address, memberId });
@@ -1796,6 +1804,29 @@ const server = http.createServer(async (req, res) => {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await rotator.stats(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such rotation.' });
}
if (p === '/api/my/reports' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const days = Math.max(1, Math.min(365, Number(u.searchParams.get('days')) || 30));
return json(res, 200, await rotator.summary(s.email, days), { 'Cache-Control': 'no-store' });
}
if (p === '/api/my/postbacks' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, { postbacks: await postbacks.list(s.email), events: postbacks.EVENTS, key: postbacks.partnerKey(s.email), inboundUrl: 'https://' + SITE_HOST + '/pb/in', log: await postbacks.logFor(s.email, 40) }, { 'Cache-Control': 'no-store' });
}
if (p === '/api/my/postbacks' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req); if (b.rotateKey) return json(res, 200, { ok: true, key: postbacks.rotateKey(s.email) });
const r = await postbacks.create(s.email, b); return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/postbacks\/([a-f0-9]{10})$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req); const r = b.test ? await postbacks.test(s.email, m[1]) : await postbacks.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r);
}
if (p === '/pb/in' && (req.method === 'GET' || req.method === 'POST')) { // partner-reported conversion against our click id
const b = req.method === 'POST' ? await readBody(req).catch(() => ({})) : {}; for (const [k, v] of u.searchParams) if (b[k] == null) b[k] = v;
const r = await postbacks.inbound(b.key, b); return json(res, r.error ? 400 : 200, r, { 'Cache-Control': 'no-store' });
}
if (p === '/api/my/carry' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const st = carry.status(); const me = s.email.toLowerCase();
@@ -2809,6 +2840,9 @@ const server = http.createServer(async (req, res) => {
if (p === '/disclaimer') return sendFile(res, path.join(PUBLIC_DIR, 'disclaimer.html'));
if (p === '/my') return sendFile(res, path.join(PUBLIC_DIR, 'my.html'));
if (p === '/links') return sendFile(res, path.join(PUBLIC_DIR, 'links.html')); // Control Room: the links workspace, first screen of the new front end (2026-09-29)
if (p === '/reports') return sendFile(res, path.join(PUBLIC_DIR, 'reports.html'));
if (p === '/team') return sendFile(res, path.join(PUBLIC_DIR, 'team.html'));
if (p === '/wallet') return sendFile(res, path.join(PUBLIC_DIR, 'wallet.html'));
if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html'));
if (p === '/shorts') return sendFile(res, path.join(PUBLIC_DIR, 'shorts.html'));
if (p === '/plays') return sendFile(res, path.join(PUBLIC_DIR, 'plays.html'));