3cc687aff5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4435 lines
368 KiB
JavaScript
4435 lines
368 KiB
JavaScript
// LinkSpin — membership advertising with immutable on-chain settlement.
|
|
// Zero-dependency Node server (RM Circle pattern): static pages + JSON API,
|
|
// wallet sign-in (SIWE), live contract ledger, sponsor join links.
|
|
//
|
|
// Chain selection (Amoy rehearsal vs mainnet) lives in data/config.json —
|
|
// see chain.js. Wipe the volume's accounts/sessions + flip config = launch.
|
|
const http = require('http');
|
|
const https = require('https');
|
|
const dns = require('dns');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const crypto = require('crypto');
|
|
const sendy = require('./sendy');
|
|
const { URL } = require('url');
|
|
const chain = require('./chain');
|
|
const auth = require('./auth');
|
|
const accounts = require('./accounts');
|
|
const themehead = require('./themehead'); // 2026-11-01 light/dark theme head script for server-rendered pages
|
|
const ads = require('./ads');
|
|
const mailer = require('./mailer');
|
|
const { emailIssue } = require('./emailcheck'); // typo / no-mail-domain check for NEW addresses (2026-10-22)
|
|
// only addresses we have never seen get the typo check; existing members always sign in with what they have.
|
|
// Skipped when this server cannot send mail (local QA copies sign in as @example.com via devCode).
|
|
const newEmailIssue = async e => (!mailer.hasKey() || (await accounts.byEmail(e)) ? null : emailIssue(e));
|
|
const messages = require('./messages');
|
|
const reports = require('./reports');
|
|
const drip = require('./drip');
|
|
const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set)
|
|
let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ }
|
|
const chatbot = require('./chatbot');
|
|
const kb = require('./kb'); // the assistant's knowledge base: Admin > Knowledge base, seeded from chatbot.js CANNED + kb-seed.js (2026-10-20)
|
|
const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats
|
|
const tank = require('./tank'); // holding tank: unsponsored free members, adoptions, pay-it-forward
|
|
const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails
|
|
const traffic = require('./traffic'); // public page views by referring domain (admin Traffic tab)
|
|
const promos = require('./promos'); // partner promo codes -> free ad credits (link ?promo=CODE or the dashboard box)
|
|
const blog = require('./blog');
|
|
const adminMember = require('./adminmember');
|
|
const syndicate = require('./syndicate');
|
|
const releases = require('./releases');
|
|
const updates = require('./updates');
|
|
const audit = require('./audit'); // counter audit: views vs delivery logs, charges vs shows (Marty, 2026-09-15) // member update emails from Admin > Releases (Marty, 2026-09-14)
|
|
const leaderboard = require('./leaderboard');
|
|
const toolkit = require('./toolkit');
|
|
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
|
|
const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15)
|
|
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to InstantAdPay until chain-bound + one network tank (2026-10-22)
|
|
let follow = null, followStore = null;
|
|
const IAP_BASE = () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
|
let activationCache = { at: 0, map: null };
|
|
function activationByAddress() { // MemberActivated events by wallet, for the Sponsor check (when the contract bound the sponsor)
|
|
if (activationCache.map && Date.now() - activationCache.at < 60000) return activationCache.map;
|
|
const m = new Map(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'MemberActivated' && ev.account) { const k = String(ev.account).toLowerCase(); if (!m.has(k)) m.set(k, { id: ev.id, sponsorId: ev.sponsorId, block: ev.block, tx: ev.tx }); }
|
|
activationCache = { at: Date.now(), map: m }; return m;
|
|
}
|
|
// signed partner body (registry sync secret, see sponsorfollow.verify): resolves { body } or { status, error }
|
|
async function readPartnerSigned(req, maxBytes) {
|
|
let raw; try { raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > maxBytes) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); }); } catch (e) { return { status: 413, error: 'too big' }; }
|
|
const bad = SF.verify(raw, req.headers); if (bad) return bad;
|
|
try { return { body: JSON.parse(raw || '{}') }; } catch (e) { return { status: 400, error: 'bad json' }; }
|
|
}
|
|
const helpdesk = require('./helpdesk'); // support: Help screen, /support, ticket link, chat hand-off, all on InstantAdPay's one desk (2026-10-16)
|
|
const carry = require('./carry'); // sponsor carry-over: engine activation, claim window, notices
|
|
const rotator = require('./rotator');
|
|
const health = require('./health'); // destination health checks + auto-pause (2026-10-10)
|
|
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29)
|
|
const convtrack = require('./convtrack'); // conversion pixel: goals, ad click ids, landing tag + goal pixel, per-goal reports (2026-10-23)
|
|
const netconv = require('./netconv'); // network conversions: InstantAdPay's joins, wallets, purchases counted for the click's owner, reporting only (2026-11-07)
|
|
const marks = require('./marks'); // one-time claims shared by both app copies during a deploy (event_marks or exclusive files), 2026-10-24
|
|
const refill = require('./refill');
|
|
const refuel = require('./refuel');
|
|
const prohibited = require('./prohibited'); // prohibited-content policy shared with InstantAdPay (2026-10-30 link-farm incident)
|
|
const spamscan = require('./spamscan'); // daily link-farm scan + quarantine rule, byte-for-byte copy of InstantAdPay's
|
|
const kit = require('./kit');
|
|
const engine = require('./engine'); // the Engine Room (same file as InstantAdPay), 2026-10-24
|
|
const kitspin = require('./kitspin'); // Refuel Kit -> Banner Spin loader // the Refuel Kit: monthly members-only LinkSpin banner sets, personalized per member (2026-10-24) // Monthly Refuel streak, LinkSpin side: reports $25+ packages to InstantAdPay (the source of truth), applies its grants (2026-10-24) // refill notices: low / out / idle, one message per owner, conversions tracked (2026-10-24)
|
|
const bannerspin = require('./bannerspin'); // Banner Spin: one image URL + one click URL rotating up to 25 banners (2026-10-18)
|
|
const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12)
|
|
const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/<slug> (2026-09-29)
|
|
const domains = require('./domains'); // link-domain pool by channel + six-hourly safety checks; burned domains leave the pool (2026-10-10)
|
|
const zonereport = require('./zonereport'); // read-only zone numbers for member Reports (2026-10-10)
|
|
const zones = require('./zones'); // ad zones on members' own sites (2026-09-29)
|
|
const nas = require('./nas');
|
|
const audiences = require('./audiences'); // first-party retargeting (2026-10-08) // only asked whether syndication is on (the status strip)
|
|
const MEMBER_AD_TYPES = ['banner', 'text', 'login']; // the formats LinkSpin members can buy (video, visits, featured, solo stay off) // 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 content = require('./content'); // admin Member content: one read-only list of everything members create (2026-10-18)
|
|
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)
|
|
const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/publishers', '/earning', '/blog', '/whats-new', '/leaderboard', '/refuel', '/conversion-tracking']);
|
|
let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute)
|
|
const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting
|
|
const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY)
|
|
const launchweek = require('./launchweek'); // launch week (2026-11-05): Founder badge grant + the launch contest (admin-approved POL prizes)
|
|
const override = require('./override'); // level-4 override: weekly dry-run report; the payer ships OFF (overrideMode 'live' + overrideGoLive + OVERRIDE_PAYER_KEY), 2026-10-23
|
|
|
|
const PORT = Number(process.env.PORT || 3000);
|
|
const ROOT = __dirname;
|
|
const PUBLIC_DIR = path.join(ROOT, 'public');
|
|
const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, 'data');
|
|
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme';
|
|
const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase();
|
|
const { SITE_HOST, SITE_URL } = require('./host');
|
|
// Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept
|
|
// in the volume so a restart doesn't log the admin out. Separate cookie and
|
|
// store from member sessions; the Bearer ADMIN_PASSWORD API path still works.
|
|
const ADMIN_SESS_FILE = path.join(DATA_DIR, 'admin-sessions.json');
|
|
const ADMIN_TTL = 12 * 60 * 60 * 1000;
|
|
let adminSessions = {};
|
|
try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; }
|
|
function saveAdminSessions() {
|
|
const now = Date.now();
|
|
for (const k of Object.keys(adminSessions)) if (!adminSessions[k] || adminSessions[k].expires < now) delete adminSessions[k];
|
|
try { fs.writeFileSync(ADMIN_SESS_FILE, JSON.stringify(adminSessions), { mode: 0o600 }); } catch (e) {}
|
|
}
|
|
function mintAdminSession(email) {
|
|
const t = crypto.randomBytes(32).toString('hex');
|
|
adminSessions[t] = { email, expires: Date.now() + ADMIN_TTL };
|
|
saveAdminSessions();
|
|
return t;
|
|
}
|
|
function adminTokenOf(req) { const m = /(?:^|;\s*)iap\.adm=([^;]+)/.exec(req.headers.cookie || ''); return m ? decodeURIComponent(m[1]) : null; }
|
|
function adminFromRequest(req) { const t = adminTokenOf(req); const s = t && adminSessions[t]; return (s && s.expires > Date.now()) ? s : null; }
|
|
function dropAdminSession(req) { const t = adminTokenOf(req); if (t && adminSessions[t]) { delete adminSessions[t]; saveAdminSessions(); } }
|
|
function adminCookie(t) { return 'iap.adm=' + encodeURIComponent(t) + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (ADMIN_TTL / 1000) + (IS_PROD ? '; Secure' : ''); }
|
|
function clearAdminCookie() { return 'iap.adm=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
|
|
const IS_PROD = process.env.NODE_ENV === 'production';
|
|
// Posture gates. mailer.js is the authority on outbound; this copy only decides whether the
|
|
// mailing loops are worth starting. SIGNUPS=closed shuts registration without taking the
|
|
// site down — members already here keep their dashboards.
|
|
const OUTBOUND_MAIL = process.env.OUTBOUND === 'on';
|
|
const SIGNUPS_OPEN = process.env.SIGNUPS !== 'closed';
|
|
const SHUT = { error: 'LinkSpin is not accepting new accounts right now.' };
|
|
// pre-launch whitelist (Marty 2026-10-08: public pages visible, nobody signs in unless whitelisted): LS_TESTERS = comma list of
|
|
// emails or usernames; empty = everyone with an account may sign in
|
|
const TESTERS = new Set(String(process.env.LS_TESTERS || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean));
|
|
const TESTING = { error: 'LinkSpin is in testing. Members get in on launch day.' };
|
|
const isTester = (email, acct) => !TESTERS.size || TESTERS.has(String(email || '').toLowerCase()) || TESTERS.has(String((acct && acct.username) || '').toLowerCase());
|
|
const SITE_FILE = path.join(DATA_DIR, 'site.json');
|
|
|
|
const db = require('./db');
|
|
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
const UPLOADS_DIR = path.join(DATA_DIR, 'uploads'); // solo-ad media lives on the volume
|
|
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
|
const uploadCounts = new Map(); // email:day -> uploads today
|
|
// the owner (ADMIN_EMAIL) and the admin portal have no daily upload cap (Marty 2026-11-08); every other member keeps 10 a day
|
|
const uploadCapHit = (who, key) => who !== 'admin' && String(who || '').toLowerCase() !== ADMIN_EMAIL && (uploadCounts.get(key) || 0) >= 10;
|
|
// open earn tokens (ad view / video / visit / tour) live in memory but mirror to the volume so a
|
|
// redeploy mid-watch does not lose them (2026-09-13: a member's video watch died in a restart)
|
|
const OPEN_TOKENS_FILE = () => path.join(DATA_DIR, 'open-tokens.json');
|
|
const persistedMaps = {};
|
|
let tokenSaveTimer = null;
|
|
function saveOpenTokens() {
|
|
tokenSaveTimer = null;
|
|
try {
|
|
const out = {};
|
|
for (const [name, m] of Object.entries(persistedMaps)) out[name] = Object.fromEntries(m);
|
|
fs.writeFileSync(OPEN_TOKENS_FILE(), JSON.stringify(out));
|
|
} catch (e) {}
|
|
}
|
|
function persistedMap(name) {
|
|
const m = new Map();
|
|
const touch = () => { if (!tokenSaveTimer) tokenSaveTimer = setTimeout(saveOpenTokens, 500); };
|
|
const set = m.set.bind(m), del = m.delete.bind(m);
|
|
m.set = (k, v) => { set(k, v); touch(); return m; };
|
|
m.delete = k => { const r = del(k); if (r) touch(); return r; };
|
|
persistedMaps[name] = m;
|
|
return m;
|
|
}
|
|
function loadOpenTokens() {
|
|
let saved = null; try { saved = JSON.parse(fs.readFileSync(OPEN_TOKENS_FILE(), 'utf8')); } catch (e) { return; }
|
|
const cutoff = Date.now() - 2 * 3600 * 1000; let n = 0;
|
|
for (const [name, m] of Object.entries(persistedMaps)) {
|
|
for (const [k, v] of Object.entries(saved[name] || {})) if (v && Number(v.ts || 0) > cutoff) { Map.prototype.set.call(m, k, v); n++; }
|
|
}
|
|
if (n) console.log('open earn tokens restored:', n);
|
|
}
|
|
const gauntletTokens = persistedMap('gauntlet'); // email -> welcome-tour token (server-clock dwell floor)
|
|
const videoTokens = persistedMap('video'); // email -> watch-to-earn video token (server-clock watch floor)
|
|
const faucetHits = new Map(); // address -> last faucet ts (rehearsal test-POL faucet rate limit)
|
|
const visitTokens = persistedMap('visit'); // email -> verified-visit token (dwell + captcha floor)
|
|
// walk the referral chain upward via sponsorRef (code/username/member id)
|
|
const polUsdC = { at: 0, v: 0 }; // /api/public/polusd cache (2026-10-22)
|
|
// A PAYING member (memberId > 0, or a registered linked position) gets their profile on public pages; a free account gets
|
|
// nothing from the profile there (2026-10-30 link-farm incident: 106 free accounts used bios and socials as backlinks).
|
|
async function hasBought(a) {
|
|
if (!a) return false; if (Number(a.memberId) > 0) return true;
|
|
try { return (await accounts.positions(a.email)).some(p => Number(p.memberId) > 0); } catch (e) { return false; }
|
|
}
|
|
// the wall's meta description is always this sentence, never profile text, so the indexed snippet is ours
|
|
const wallDescription = nm => nm + '\u2019s ad wall on LinkSpin: the network\u2019s member ads, paid out on Polygon the moment a package clears.';
|
|
async function uplineSlides(email, depth = 3) {
|
|
const out = [];
|
|
let cur = await accounts.byEmail(email);
|
|
for (let i = 0; i < depth && cur; i++) {
|
|
const ref = String(cur.sponsorRef || '').trim().toLowerCase();
|
|
if (!ref) break;
|
|
let s = null;
|
|
if (/^\d+$/.test(ref)) s = await accounts.byMemberId(Number(ref));
|
|
if (!s) s = await accounts.byCode(ref);
|
|
if (!s) s = await accounts.byUsername(ref);
|
|
if (!s || s.email === cur.email) break;
|
|
out.push(s);
|
|
cur = s;
|
|
}
|
|
return out;
|
|
}
|
|
// Wall ownership ladder: position 1 is always the member's own line banner;
|
|
// positions 2 and 3 become theirs at 2 and 5 qualifying buyers (the same
|
|
// thresholds that open payout levels 2 and 3). Until then, or while an unlocked
|
|
// slot is empty, the slot shows an upline's banner, then a house ad.
|
|
const catalogCache = { at: 0, products: null };
|
|
const wallUnlockedFor = bc => (bc >= 5 ? 3 : bc >= 2 ? 2 : 1);
|
|
// every on-chain member id this session controls: the main wallet plus linked
|
|
// positions (Qualified Start). Credits pool across them on the dashboard.
|
|
const memberInfoCache = new Map(); // id -> { t, v } (60s): line views ask for every member's on-chain row
|
|
async function cachedMember(id) {
|
|
const c = memberInfoCache.get(id); if (c && Date.now() - c.t < 60000) return c.v;
|
|
let v = null; try { v = await chain.member(id); } catch (e) {}
|
|
memberInfoCache.set(id, { t: Date.now(), v }); return v;
|
|
}
|
|
// Banner Spin access facts (2026-10-18): an own package of $25 or more on the main id or any linked position (the tank
|
|
// adoption rule), and qualifying buyers counted the way pay levels count them (main + positions, so Qualified Start counts).
|
|
// Cached a minute; bannerspin.js remembers what it has seen so the chain index window never takes a tier away.
|
|
const bsFacts = new Map();
|
|
async function bannerFacts(email) {
|
|
const e = String(email || '').toLowerCase(); const hit = bsFacts.get(e); if (hit && Date.now() - hit.ts < 60000) return hit.f;
|
|
const ids = []; try { const a = await accounts.byEmail(e); if (a && a.memberId) ids.push(a.memberId); for (const p of await accounts.positions(e)) if (p.memberId && !ids.includes(p.memberId)) ids.push(p.memberId); } catch (er) {}
|
|
const ownBuy = ids.some(id => tank.hasOwnBuy(id));
|
|
let buyers = 0; for (const id of ids) { try { buyers += (await chain.member(id)).buyerCount || 0; } catch (er) {} }
|
|
const idset = new Set(ids), counted = new Set(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'BuyerCounted' && idset.has(ev.sponsorId) && ev.newBuyerId) counted.add(ev.newBuyerId);
|
|
buyers = Math.max(buyers, counted.size);
|
|
try { const ms = await ads.milestonesOf(e); if (ms.includes('level3')) buyers = Math.max(buyers, 5); else if (ms.includes('level2')) buyers = Math.max(buyers, 2); } catch (er) {} // a badge once earned stays earned
|
|
const f = { ownBuy, buyers }; bsFacts.set(e, { ts: Date.now(), f }); return f;
|
|
}
|
|
// Tool tiers for spin links and pages (Marty 2026-10-21: "cap this ... and there needs to be more of an incentive for
|
|
// upgrading"): free 3, Starter (any package of your own) 10, Builder (2 qualifying buyers) 50, Leader (5) unlimited with a
|
|
// fair-use ceiling. Existing items above a cap are never removed; only new ones wait for the upgrade.
|
|
const TOOL_TIERS = { free: { label: 'Free', max: 3, need: '' }, starter: { label: 'Starter', max: 10, need: 'any package of your own' },
|
|
builder: { label: 'Builder', max: 50, need: 'level 2 open (2 qualifying buyers)' }, leader: { label: 'Leader', max: 500, unlimited: true, need: 'level 3 open (5 qualifying buyers)' } };
|
|
const TOOL_ORDER = ['free', 'starter', 'builder', 'leader'];
|
|
const toolCache = new Map();
|
|
async function toolTier(email) {
|
|
const e = String(email || '').toLowerCase(); const hit = toolCache.get(e); if (hit && Date.now() - hit.ts < 60000) return hit.t;
|
|
let key = 'free';
|
|
if (ADMIN_EMAIL && e === ADMIN_EMAIL) key = 'leader';
|
|
else {
|
|
const ids = []; try { const a = await accounts.byEmail(e); if (a && a.memberId) ids.push(a.memberId); for (const pz of await accounts.positions(e)) if (pz.memberId && !ids.includes(pz.memberId)) ids.push(pz.memberId); } catch (er) {}
|
|
let paid = false; if (ids.length) { const idset = new Set(ids); for (const ev of chain.recentEvents(200000)) if (ev.type === 'Purchase' && idset.has(ev.buyerId)) { paid = true; break; } }
|
|
let buyers = 0; try { buyers = (await bannerFacts(e)).buyers || 0; } catch (er) {}
|
|
key = buyers >= 5 ? 'leader' : buyers >= 2 ? 'builder' : paid ? 'starter' : 'free';
|
|
}
|
|
const t = TOOL_TIERS[key], nk = TOOL_ORDER[TOOL_ORDER.indexOf(key) + 1], n = nk ? TOOL_TIERS[nk] : null;
|
|
const out = { key, label: t.label, max: t.max, unlimited: !!t.unlimited, next: n ? { key: nk, label: n.label, max: n.max, unlimited: !!n.unlimited, need: n.need } : null };
|
|
toolCache.set(e, { ts: Date.now(), t: out }); return out;
|
|
}
|
|
function toolCapError(kind, have, t) {
|
|
const nx = t.next ? ' ' + t.next.label + ' (' + t.next.need + ') ' + (t.next.unlimited ? 'makes them unlimited.' : 'holds ' + t.next.max + '.') : '';
|
|
return 'Your ' + t.label + ' tier holds ' + t.max + ' ' + kind + ' and you have ' + have + '.' + nx;
|
|
}
|
|
async function myMemberIds(s) {
|
|
const main = await auth.refreshMemberId(s);
|
|
const ids = main ? [main] : [];
|
|
if (s && s.email) for (const p of await accounts.positions(s.email)) if (p.memberId && !ids.includes(p.memberId)) ids.push(p.memberId);
|
|
return { main, ids };
|
|
}
|
|
function parseWallOffers(a) {
|
|
try { const v = JSON.parse((a && a.wallOffers) || '[]'); return Array.isArray(v) ? v.slice(0, 2) : []; } catch (e) { return []; }
|
|
}
|
|
// admin fallback ads for wall positions 2 & 3 when a member has no upline.
|
|
// Configurable by dropping data/admin-wall-ads.json ([{name,targetUrl,bannerUrl}]).
|
|
function getAdminWallAds() {
|
|
try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); if (Array.isArray(j) && j.length) return j; } catch (e) {}
|
|
return [{ name: 'LinkSpin', targetUrl: SITE_URL + '/', bannerUrl: null }];
|
|
}
|
|
const chatHits = new Map();
|
|
const demoLimits = new Map(); // ip -> timestamps of home-page demo spins (5 per hour)
|
|
function chatLimited(ip) {
|
|
const now = Date.now(), rec = chatHits.get(ip);
|
|
if (!rec || now > rec.reset) { chatHits.set(ip, { count: 1, reset: now + 60000 }); return false; }
|
|
rec.count += 1;
|
|
return rec.count > 10;
|
|
}
|
|
// magic-code sign-in: emailLower -> {code, exp, tries}
|
|
const emailCodes = new Map();
|
|
const inviteTokens = new Map(); // admin-minted one-time sign-in links for testers: token -> {email, exp, next}
|
|
// ── sign-up code guard (Marty, 2026-09-11): the email box is one field and one
|
|
// tap, so nothing visible stands in a human's way. Bots hit four invisible walls:
|
|
// a honeypot field, a minimum form age, per-IP + global send limits, and, only
|
|
// once an IP trips a limit, the same icon check the ad viewer uses.
|
|
const CODE_LIMITS = { per10m: 5, perDay: 20, globalPerMin: 60, passMs: 5 * 60 * 1000, minFormMs: 2000 };
|
|
const codeHits = new Map(); // ip -> { t: [send timestamps, 24h], passUntil, chal: { answer, exp } }
|
|
const codeGlobal = { minute: 0, n: 0 };
|
|
const codeAlert = { last: 0, trips: 0, ips: new Set() };
|
|
function clientIp(req) { return String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim() || 'unknown'; }
|
|
// the viewer's country and tier for ad targeting (null tier = unknown: never matches a restricted campaign)
|
|
// CORS for the zone tag: echo the calling origin and allow credentials, so the browser may send the ls.vid cookie
|
|
function corsCreds(req) { const o = String(req.headers.origin || ''); return o ? { 'Access-Control-Allow-Origin': o, 'Access-Control-Allow-Credentials': 'true', 'Vary': 'Origin' } : { 'Access-Control-Allow-Origin': '*' }; }
|
|
const PIXEL_GIF = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');
|
|
function viewerGeo(req) { const cc = geo.countryOf(clientIp(req)); return { cc, tier: geo.tierOf(cc, siteConfig()) }; }
|
|
function codeChallenge(rec) {
|
|
const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5);
|
|
const answer = Math.floor(Math.random() * pick.length);
|
|
rec.chal = { answer: pick[answer][0], exp: Date.now() + 5 * 60 * 1000 };
|
|
return { prompt: pick[answer][1], options: pick.map(x => x[0]) };
|
|
}
|
|
// returns null to allow the send, or { status, body } to answer with instead
|
|
const guardLog = (req, why, b) => console.log('signup-guard', why, clientIp(req), String(b.email || '').replace(/^(.).*(@.*)$/, '$1***$2'));
|
|
function codeGuard(req, b) {
|
|
const now = Date.now();
|
|
// honeypot: bots fill it, humans never see it. Some form-filler extensions fill every field,
|
|
// hidden or not (seen 2026-09-11), so a filled honeypot is a CHALLENGE, never a silent drop:
|
|
// a person passes the icon check and gets the code, a bot cannot.
|
|
const hpRaw = String(b.hp_field_x9 || '').trim();
|
|
const hpIsEmail = !!hpRaw && hpRaw.toLowerCase() === String(b.email || '').trim().toLowerCase();
|
|
const hp = !!hpRaw && !hpIsEmail; // 2026-09-13: phones were autofilling the hidden field; own email = autofill, not a bot
|
|
if (hpRaw) console.log('signup-guard honeypot-value', clientIp(req), hpIsEmail ? 'own-email' : (/^https?:/i.test(hpRaw) ? 'url' : /@/.test(hpRaw) ? 'other-email' : /^\+?[\d\s()-]{6,}$/.test(hpRaw) ? 'phone' : 'text'), 'len=' + hpRaw.length, hpIsEmail ? '' : hpRaw.slice(0, 2) + '***');
|
|
const fts = Number(b.fts) || 0;
|
|
if (!fts || now - fts < CODE_LIMITS.minFormMs) { guardLog(req, 'form-age', b); return { status: 400, body: { error: 'Give the page a second, then tap again.' } }; }
|
|
if (now - fts > 12 * 3600 * 1000) { guardLog(req, 'form-stale', b); return { status: 400, body: { error: 'This page has been open a long time. Refresh it, then tap again.' } }; }
|
|
const minute = Math.floor(now / 60000);
|
|
if (codeGlobal.minute !== minute) { codeGlobal.minute = minute; codeGlobal.n = 0; }
|
|
if (codeGlobal.n >= CODE_LIMITS.globalPerMin) { guardLog(req, 'global-limit', b); codeTrip(req, 'global'); return { status: 429, body: { error: 'Busy right now. Try again in a minute.' } }; }
|
|
const ip = clientIp(req);
|
|
const rec = codeHits.get(ip) || { t: [], passUntil: 0, chal: null };
|
|
rec.t = rec.t.filter(ts => now - ts < 24 * 3600 * 1000);
|
|
const n10 = rec.t.filter(ts => now - ts < 10 * 60 * 1000).length;
|
|
const limited = hp || n10 >= CODE_LIMITS.per10m || rec.t.length >= CODE_LIMITS.perDay;
|
|
if (limited && now >= rec.passUntil) {
|
|
const pick = String(b.pick || '');
|
|
if (pick && rec.chal && rec.chal.exp > now && pick === rec.chal.answer) { rec.passUntil = now + CODE_LIMITS.passMs; rec.chal = null; }
|
|
else {
|
|
guardLog(req, pick ? 'wrong-pick' : hp ? 'honeypot-challenge' : 'ip-limit', b); if (!hp) codeTrip(req, ip);
|
|
const challenge = codeChallenge(rec); codeHits.set(ip, rec);
|
|
return { status: 429, body: { error: pick ? 'That was not it. Try once more.' : 'Quick check before we send another code.', challenge } };
|
|
}
|
|
}
|
|
rec.t.push(now); codeHits.set(ip, rec); codeGlobal.n += 1;
|
|
if (codeHits.size > 5000) for (const [k, v] of codeHits) { if (!v.t.length || now - v.t[v.t.length - 1] > 24 * 3600 * 1000) codeHits.delete(k); }
|
|
return null;
|
|
}
|
|
// Public support form + signed-out chat hand-off (2026-10-16): the sign-up guard's walls (honeypot, form age, per-IP
|
|
// limits with the icon check once tripped, a global cap) plus a hard per-email cap, on counters of their own so a
|
|
// support ticket never eats into anyone's sign-in codes. Returns null to allow, or { status, body }.
|
|
const SUPPORT_LIMITS = { ipHour: 5, ipDay: 15, emailHour: 3, emailDay: 8, globalPerMin: 20 };
|
|
const supportHits = new Map(); // 'ip:<ip>' | 'em:<email>' | 'tk:<token or ref>' -> [timestamps, 24h]
|
|
const supportChal = new Map(); // ip -> { chal, passUntil }
|
|
const supportGlobal = { minute: 0, n: 0 };
|
|
const supportRecent = (k, ms) => { const now = Date.now(); const t = (supportHits.get(k) || []).filter(ts => now - ts < 86400000); supportHits.set(k, t); return t.filter(ts => now - ts < ms).length; };
|
|
const supportMark = k => { const t = supportHits.get(k) || []; t.push(Date.now()); supportHits.set(k, t); if (supportHits.size > 5000) for (const [kk, v] of supportHits) if (!v.length || Date.now() - v[v.length - 1] > 86400000) supportHits.delete(kk); };
|
|
const supportFlood = (k, n, ms) => { if (supportRecent(k, ms) >= n) return true; supportMark(k); return false; }; // signed-in and private-link replies: a plain cap
|
|
// tickets are open to platform members only (Marty, 2026-10-24, after a throwaway-address 'pentest' ticket):
|
|
// a signed-out sender's email must belong to an account on this site
|
|
const MEMBER_ONLY_TICKET_MSG = "Support tickets are for LinkSpin members. Use the email on your LinkSpin account, or sign in first. Not a member yet? Join free at https://linkspin.app/join and ask from inside.";
|
|
async function memberOnlyTicket(email) { try { return (await accounts.byEmail(email)) ? null : { status: 403, body: { error: MEMBER_ONLY_TICKET_MSG, membersOnly: true } }; } catch (e) { return null; } }
|
|
function supportGuard(req, b, email) {
|
|
const now = Date.now();
|
|
const hpRaw = String(b.hp_field_x9 || '').trim();
|
|
const hp = !!hpRaw && hpRaw.toLowerCase() !== email; // own email = phone autofill, not a bot
|
|
const fts = Number(b.fts) || 0;
|
|
if (!fts || now - fts < CODE_LIMITS.minFormMs) { guardLog(req, 'support form-age', b); return { status: 400, body: { error: 'Give the page a few seconds, then send again.' } }; }
|
|
if (now - fts > 12 * 3600 * 1000) { guardLog(req, 'support form-stale', b); return { status: 400, body: { error: 'This page has been open a long time. Refresh it, then send again.' } }; }
|
|
const minute = Math.floor(now / 60000);
|
|
if (supportGlobal.minute !== minute) { supportGlobal.minute = minute; supportGlobal.n = 0; }
|
|
if (supportGlobal.n >= SUPPORT_LIMITS.globalPerMin) { guardLog(req, 'support global-limit', b); return { status: 429, body: { error: 'Busy right now. Try again in a minute.' } }; }
|
|
if (supportRecent('em:' + email, 3600000) >= SUPPORT_LIMITS.emailHour || supportRecent('em:' + email, 86400000) >= SUPPORT_LIMITS.emailDay) {
|
|
guardLog(req, 'support email-limit', b);
|
|
return { status: 429, body: { error: 'You have sent several tickets already. Reply on the one you have open (the link is in your confirmation email) and Marty will see it there.' } };
|
|
}
|
|
const ip = clientIp(req);
|
|
const limited = hp || supportRecent('ip:' + ip, 3600000) >= SUPPORT_LIMITS.ipHour || supportRecent('ip:' + ip, 86400000) >= SUPPORT_LIMITS.ipDay;
|
|
const rec = supportChal.get(ip) || { chal: null, passUntil: 0 };
|
|
if (limited && now >= rec.passUntil) {
|
|
const pick = String(b.pick || '');
|
|
if (pick && rec.chal && rec.chal.exp > now && pick === rec.chal.answer) { rec.passUntil = now + CODE_LIMITS.passMs; rec.chal = null; }
|
|
else { guardLog(req, pick ? 'support wrong-pick' : hp ? 'support honeypot-challenge' : 'support ip-limit', b); const challenge = codeChallenge(rec); supportChal.set(ip, rec); if (supportChal.size > 5000) supportChal.clear(); return { status: 429, body: { error: pick ? 'That was not it. Try once more.' : 'Quick check before we send it.', challenge } }; }
|
|
supportChal.set(ip, rec);
|
|
}
|
|
supportGlobal.n += 1; supportMark('ip:' + ip); supportMark('em:' + email);
|
|
return null;
|
|
}
|
|
// what an anonymous visitor may load while the curtain is up: the support page, its ticket link, its API and the files they use
|
|
const SUPPORT_OPEN = new Set(['/support', '/api/support', '/api/support/chatbot', '/assets/pub.css', '/assets/common.js', '/assets/support.js', '/logo-icon.png', '/favicon-256.png']);
|
|
const supportOpen = p => SUPPORT_OPEN.has(p) || /^\/support\/t\/[A-Za-z0-9_.-]{20,80}$/.test(p) || /^\/api\/support\/t\/[A-Za-z0-9_.-]{20,80}(\/reply)?$/.test(p);
|
|
// burst alert: at most one message per 10 minutes, to the admin Telegram chat if set, else the admin email
|
|
function codeTrip(req, ip) {
|
|
codeAlert.trips += 1; codeAlert.ips.add(ip);
|
|
if (Date.now() - codeAlert.last < 10 * 60 * 1000) return;
|
|
codeAlert.last = Date.now();
|
|
const text = '\u26A0\uFE0F LinkSpin sign-up guard: ' + codeAlert.trips + ' blocked code request' + (codeAlert.trips === 1 ? '' : 's') + ' from ' + codeAlert.ips.size + ' source' + (codeAlert.ips.size === 1 ? '' : 's') + ' (' + [...codeAlert.ips].slice(0, 5).join(', ') + ') in the last window.';
|
|
codeAlert.trips = 0; codeAlert.ips = new Set();
|
|
const sc = siteConfig();
|
|
if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {});
|
|
else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: sign-up guard tripped', text).catch(() => {});
|
|
}
|
|
// earn-view tokens: emailLower -> {token, ts} (one live token per member)
|
|
const earnTokens = persistedMap('earn');
|
|
// human-check pairs for the view verifier: [emoji shown, word named in the prompt]
|
|
const CAPTCHA = [['🚀', 'rocket'], ['⚡', 'lightning bolt'], ['🔑', 'key'], ['🎯', 'target'],
|
|
['🌊', 'wave'], ['🔥', 'flame'], ['💎', 'diamond'], ['🧲', 'magnet'], ['🔔', 'bell'], ['🌙', 'moon']];
|
|
|
|
// ── frame-breaking check ─────────────────────────────────
|
|
// Surf views frame the advertiser's URL full screen, so a target that refuses
|
|
// framing (X-Frame-Options / CSP frame-ancestors) would burn members' views on
|
|
// a blank frame. Catch it the moment the campaign is submitted. The lookup
|
|
// also refuses private/internal addresses so member URLs can't probe our LAN.
|
|
const PRIVATE_IP = /^(127\.|10\.|192\.168\.|169\.254\.|0\.|172\.(1[6-9]|2\d|3[01])\.|::1$|::$|f[cd])/i;
|
|
function frameFetch(url, depth) {
|
|
return new Promise(resolve => {
|
|
let u;
|
|
try { u = new URL(String(url || '')); } catch (e) { return resolve({ error: 'that is not a valid URL' }); }
|
|
if (!/^https?:$/.test(u.protocol)) return resolve({ error: 'only http(s) URLs work' });
|
|
if (u.port && u.port !== '80' && u.port !== '443') return resolve({ error: 'custom ports are not allowed' });
|
|
if (u.hostname === 'localhost' || u.hostname.endsWith('.local')) return resolve({ error: 'that address is not reachable from here' });
|
|
dns.lookup(u.hostname, (de, addr) => {
|
|
if (de) return resolve({ error: 'that domain does not resolve' });
|
|
if (PRIVATE_IP.test(addr)) return resolve({ error: 'that address is not reachable from here' });
|
|
const mod = u.protocol === 'https:' ? https : http;
|
|
// Our own hosts (the app and the link domains) answer the curtain's 503 to anonymous fetches while the
|
|
// app is curtained, which made a test ad aimed at a spin link look dead (2026-10-07). Carry the pass.
|
|
const own = [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
|
|
const hdrs = { 'User-Agent': 'Mozilla/5.0 (compatible; LinkSpin-FrameCheck/1.0)', Accept: 'text/html' };
|
|
if (CURTAIN && own.includes(u.hostname.toLowerCase())) hdrs.Cookie = 'ls.pass=' + encodeURIComponent(CURTAIN);
|
|
const rq = mod.get(u.href, { timeout: 8000, headers: hdrs }, r => {
|
|
const loc = r.headers.location;
|
|
r.resume(); // headers are all we need
|
|
if ([301, 302, 303, 307, 308].includes(r.statusCode) && loc && depth < 4) {
|
|
rq.destroy();
|
|
let next; try { next = new URL(loc, u.href).href; } catch (e2) { return resolve({ error: 'it redirects somewhere invalid' }); }
|
|
return resolve(frameFetch(next, depth + 1)); // every hop re-runs the private-IP guard
|
|
}
|
|
resolve({ status: r.statusCode, xfo: r.headers['x-frame-options'] || '', csp: r.headers['content-security-policy'] || '' });
|
|
rq.destroy();
|
|
});
|
|
rq.on('timeout', () => { rq.destroy(); resolve({ error: 'it did not answer within 8 seconds' }); });
|
|
rq.on('error', e2 => resolve({ error: 'it did not answer (' + (e2.code || 'connection failed') + ')' }));
|
|
});
|
|
});
|
|
}
|
|
// shared upload path for member creatives (/api/my/upload) and admin house-ad
|
|
// creatives (/api/admin/upload): `who` keys the per-day upload counter
|
|
async function handleUpload(req, res, who) {
|
|
const ct = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
|
|
const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif',
|
|
'video/mp4': 'mp4', 'video/webm': 'webm' };
|
|
if (!EXT[ct]) return json(res, 400, { error: 'Use a PNG, JPG, WebP, GIF, MP4 or WebM file.' });
|
|
const isVideo = ct.startsWith('video/');
|
|
const key = who + ':' + new Date().toISOString().slice(0, 10);
|
|
if (uploadCapHit(who, key)) return json(res, 400, { error: 'Upload limit for today reached (10 files).' });
|
|
let buf;
|
|
try { buf = await readRaw(req, isVideo ? 25 * 1024 * 1024 : 3 * 1024 * 1024); }
|
|
catch (e) { return json(res, 400, { error: 'File too large. Images up to 3MB, video up to 25MB.' }); }
|
|
const magicOk = buf.length > 16 && (
|
|
(ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) ||
|
|
(ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) ||
|
|
(ct === 'image/webp' && buf.slice(0, 4).toString() === 'RIFF' && buf.slice(8, 12).toString() === 'WEBP') ||
|
|
(ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8') ||
|
|
(ct === 'video/mp4' && buf.slice(4, 8).toString() === 'ftyp') ||
|
|
(ct === 'video/webm' && buf[0] === 0x1a && buf[1] === 0x45 && buf[2] === 0xdf && buf[3] === 0xa3));
|
|
if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' });
|
|
const name = crypto.randomBytes(12).toString('hex') + '.' + EXT[ct];
|
|
uploadCounts.set(key, (uploadCounts.get(key) || 0) + 1);
|
|
// video goes to DO Spaces when configured (keeps big files off the volume);
|
|
// images stay local. Falls back to the volume if Spaces isn't set or errors.
|
|
if (isVideo && spaces.enabled()) {
|
|
try {
|
|
const url = await spaces.put('iap-uploads/' + name, buf, ct);
|
|
content.noteUpload(name, who, buf.length, ct, url); // who uploaded what (admin Member content)
|
|
return json(res, 200, { url, type: 'video' });
|
|
} catch (e) { console.error('spaces put', e.message); /* fall through to volume */ }
|
|
}
|
|
fs.writeFileSync(path.join(UPLOADS_DIR, name), buf);
|
|
content.noteUpload(name, who, buf.length, ct, '');
|
|
return json(res, 200, { url: '/uploads/' + name, type: isVideo ? 'video' : 'image' });
|
|
}
|
|
// lead-capture page hooks (og tags + copy live in public/assets/join.js too)
|
|
const JOIN_ALIASES = { company: 'martbost', top: 'martbost' }; // neutral partner links -> the top position
|
|
const JOIN_ANGLES = {
|
|
// legacy bridge pages (/from/<brand>): former members of Marty's closed EvolutionScript sites
|
|
'fw-adv': { t: 'Your next ad budget pays you back.', d: 'Faucet Wave closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave?seg=advertiser' },
|
|
'fw-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Faucet Wave. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave' },
|
|
't1-adv': { t: 'Your next ad budget pays you back.', d: 'Tier One Ads closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads?seg=advertiser' },
|
|
'b4h': { t: 'BTC4Hits is now LinkSpin.', d: 'Your BTC4Hits account came with you. Sign in with the same email; an active rotator is already waiting as a LinkSpin spin link.', url: SITE_URL + '/from/btc4hits' },
|
|
't1-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Tier One Ads. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads' },
|
|
instant: { t: 'Paid before the page reloads.', d: 'A smart contract on Polygon splits every ad package the moment it sells. Same transaction, real wallets, public ledger. Join free by email.' },
|
|
adspend: { t: 'You were buying ads anyway.', d: 'Here the ad spend in your line pays you, in the same transaction, on a public ledger. Banner, text and login ads, packages from $10. Join free.' },
|
|
free: { t: 'Watch first. Spend never.', d: 'Join free, view a few ads, earn credits, run your first campaign for zero dollars. Every payout public on Polygon.' },
|
|
// LinkSpin-only hooks (2026-10-09), each with a video on the join page
|
|
links: { t: 'Stop juggling links.', d: 'One short link rotates every page you promote, with weights, hours and a fallback, and a report by source. Free, try a spin with no account.' },
|
|
pages: { t: 'A bridge page in a minute.', d: 'Point LinkSpin at any offer, add one line in your words, and get a bridge, review or squeeze page on a clean domain. Leads are yours. Free.' },
|
|
zones: { t: 'Your site pays you.', d: 'One script tag puts an ad slot on your website. Every viewable view pays you ad credits you spend on your own campaign. Nine sizes, free.' },
|
|
audiences: { t: 'Retarget without renting an audience.', d: 'Everyone who sees your pages or zones is remembered for 30 days in an audience you own. Show a campaign only to them, or never to them.' },
|
|
stack: { t: 'Three tools, zero dollars.', d: 'A link rotator, a bridge-page builder and an ad slot for your own site, free with an email. Buy a package only if you want more.' },
|
|
ledger: { t: 'No back office. No payday.', d: 'Every payout is a public transaction on Polygon you can read yourself. Nothing is ever held. Join free by email.' },
|
|
two: { t: 'Two buyers open level two.', d: 'Every direct buyer pays you 50 percent from their first package. Two qualifying buyers open level two, five open level three. Written in a verified contract.' }
|
|
};
|
|
function serveJoinPage(res, tok, angle, ang, setCookies) {
|
|
let html;
|
|
try { html = fs.readFileSync(path.join(PUBLIC_DIR, 'join.html'), 'utf8'); } catch (e) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
|
|
const base = SITE_URL;
|
|
const url = (ang && ang.url) || (base + '/join/' + tok + (angle ? '?v=' + angle : ''));
|
|
const title = ang ? ang.t : 'Advertise and earn. Paid on-chain, instantly.';
|
|
const desc = ang ? ang.d : 'You are invited to LinkSpin: real ad packages with same-transaction payouts on Polygon, every payment public. Join free by email.';
|
|
const escA = t => String(t).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
|
const og = '<meta property="og:type" content="website"><meta property="og:site_name" content="LinkSpin">'
|
|
+ '<meta property="og:title" content="' + escA(title) + '"><meta property="og:description" content="' + escA(desc) + '">'
|
|
+ '<meta property="og:url" content="' + escA(url) + '">' // keeps ?v= so shares stay on the angle
|
|
+ '<meta property="og:image" content="' + base + '/banners/linkspin-og-1200x630.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">'
|
|
+ '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' + escA(title) + '"><meta name="twitter:description" content="' + escA(desc) + '"><meta name="twitter:image" content="' + base + '/banners/linkspin-og-1200x630.png">';
|
|
html = html.replace(/<title>[^<]*<\/title>/, '<title>' + escA(title) + ' | LinkSpin</title>' + og);
|
|
if (ang) html = html.replace('<body>', '<body class="squeeze">'); // angle pages: squeeze layout from the first paint
|
|
const headers = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, must-revalidate' };
|
|
if (setCookies && setCookies.length) headers['Set-Cookie'] = setCookies;
|
|
res.writeHead(200, baseHeaders(headers));
|
|
res.end(html);
|
|
}
|
|
async function frameCheck(url) {
|
|
const h = await frameFetch(url, 0);
|
|
if (h.error) return { ok: false, reason: 'We checked your URL and ' + h.error + '. Fix the URL and try again.' };
|
|
if (h.status >= 400) return { ok: false, reason: 'Your URL answers with HTTP ' + h.status + '. Point the campaign at a working page.' };
|
|
if (/deny|sameorigin/i.test(String(h.xfo)))
|
|
return { ok: false, reason: 'That site blocks framing (X-Frame-Options), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' };
|
|
const fa = /frame-ancestors\s+([^;]+)/i.exec(String(h.csp));
|
|
if (fa && !fa[1].split(/\s+/).some(x => {
|
|
const v = x.replace(/['"]/g, '').toLowerCase();
|
|
return v === '*' || v === 'https:' || v.includes(SITE_HOST);
|
|
}))
|
|
return { ok: false, reason: 'That site blocks framing (CSP frame-ancestors), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' };
|
|
return { ok: true };
|
|
}
|
|
// ── banner image check (2026-10-18, with ad editing): the image has to load, be a real PNG / JPG / GIF / WebP and stay
|
|
// within the 3 MB the uploader allows. Our own uploads are read off the volume; anything else is fetched through the same
|
|
// private-address guard as the frame check. A size that differs from the banner slot is a warning, never a refusal.
|
|
const IMG_MAGIC = b => b.length > 16 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47 ? 'image/png'
|
|
: b.length > 16 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff ? 'image/jpeg'
|
|
: b.length > 16 && b.slice(0, 4).toString() === 'GIF8' ? 'image/gif'
|
|
: b.length > 16 && b.slice(0, 4).toString() === 'RIFF' && b.slice(8, 12).toString() === 'WEBP' ? 'image/webp' : '';
|
|
const IMG_MAX = 3 * 1024 * 1024;
|
|
function imageFetch(url, depth) {
|
|
return new Promise(resolve => {
|
|
let u; try { u = new URL(String(url || '')); } catch (e) { return resolve({ error: 'that is not a valid URL' }); }
|
|
if (!/^https?:$/.test(u.protocol)) return resolve({ error: 'only http(s) URLs work' });
|
|
if (u.port && u.port !== '80' && u.port !== '443') return resolve({ error: 'custom ports are not allowed' });
|
|
if (u.hostname === 'localhost' || u.hostname.endsWith('.local')) return resolve({ error: 'that address is not reachable from here' });
|
|
dns.lookup(u.hostname, (de, addr) => {
|
|
if (de) return resolve({ error: 'that domain does not resolve' });
|
|
if (PRIVATE_IP.test(addr)) return resolve({ error: 'that address is not reachable from here' });
|
|
const mod = u.protocol === 'https:' ? https : http;
|
|
const rq = mod.get(u.href, { timeout: 8000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; LinkSpin-ImageCheck/1.0)', Accept: 'image/*' } }, r => {
|
|
const loc = r.headers.location;
|
|
if ([301, 302, 303, 307, 308].includes(r.statusCode) && loc && depth < 4) {
|
|
r.resume(); rq.destroy();
|
|
let next; try { next = new URL(loc, u.href).href; } catch (e2) { return resolve({ error: 'it redirects somewhere invalid' }); }
|
|
return resolve(imageFetch(next, depth + 1));
|
|
}
|
|
if (r.statusCode >= 400) { r.resume(); rq.destroy(); return resolve({ error: 'it answers with HTTP ' + r.statusCode }); }
|
|
const chunks = []; let n = 0, done = false;
|
|
r.on('data', c => { if (done) return; n += c.length; if (n > IMG_MAX) { done = true; rq.destroy(); return resolve({ error: 'it is larger than 3 MB' }); } chunks.push(c); });
|
|
r.on('end', () => { if (!done) { done = true; resolve({ buf: Buffer.concat(chunks) }); } });
|
|
r.on('error', () => { if (!done) { done = true; resolve({ error: 'it stopped loading part way' }); } });
|
|
});
|
|
rq.on('timeout', () => { rq.destroy(); resolve({ error: 'it did not answer within 8 seconds' }); });
|
|
rq.on('error', e2 => resolve({ error: 'it did not answer (' + (e2.code || 'connection failed') + ')' }));
|
|
});
|
|
});
|
|
}
|
|
async function imageCheck(url, size) {
|
|
let got = null;
|
|
try {
|
|
const u = new URL(String(url || ''));
|
|
const own = [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
|
|
const local = /^\/uploads\/([a-f0-9]{24}\.(png|jpg|webp|gif))$/.exec(u.pathname);
|
|
if (local && (own.includes(u.hostname.toLowerCase()) || (!IS_PROD && /^(localhost|127\.0\.0\.1)$/.test(u.hostname)))) {
|
|
try { const buf = fs.readFileSync(path.join(UPLOADS_DIR, local[1])); got = buf.length > IMG_MAX ? { error: 'it is larger than 3 MB' } : { buf }; }
|
|
catch (e) { got = { error: 'that upload is not on this server' }; }
|
|
}
|
|
} catch (e) {}
|
|
if (!got) got = await imageFetch(url, 0);
|
|
// a host that is slow or blocks our checker must not block a real ad: only a too-big file or a missing upload refuses
|
|
// outright; anything else goes through with a warning (review 2026-10-18)
|
|
if (got.error && !/larger than 3 MB|not on this server/.test(got.error)) return { ok: true, warn: 'We could not check your banner image just now (' + got.error + '). If it does not show in your ad, upload the image instead.' };
|
|
if (got.error) return { ok: false, reason: 'We checked your banner image and ' + got.error + '. Upload the image or paste a working https link to it.' };
|
|
const mime = IMG_MAGIC(got.buf);
|
|
if (!mime) return { ok: false, reason: 'That link does not lead to a PNG, JPG, GIF or WebP image. Upload the image or paste a direct link to the image file.' };
|
|
const d = mime === 'image/webp' ? { w: 0, h: 0 } : bannerspin.dims(got.buf, mime);
|
|
const want = /^(\d+)x(\d+)$/.exec(String(size || ''));
|
|
return { ok: true, w: d.w, h: d.h, bytes: got.buf.length,
|
|
warn: want && d.w && (d.w !== Number(want[1]) || d.h !== Number(want[2])) ? 'This image is ' + d.w + 'x' + d.h + ' and the ad slot is ' + want[1] + 'x' + want[2] + ', so it will be scaled to fit.' : '' };
|
|
}
|
|
// the outside checks a campaign's link and image go through, shared by member create, house-ad create and every edit.
|
|
// Banner and text views frame the target, so it has to allow framing; login (and solo, video, featured) open in a new
|
|
// tab or our own player. A banner image has to load and be an image. `f` carries only what is being set or changed.
|
|
async function adChecks(type, f) {
|
|
if (f.targetUrl !== undefined && !['login', 'solo', 'video', 'featured'].includes(String(type || ''))) {
|
|
const fc = await frameCheck(f.targetUrl); if (!fc.ok) return { error: fc.reason };
|
|
}
|
|
let warn = '';
|
|
if (type === 'banner' && f.imageUrl !== undefined && /^https?:\/\/\S+$/i.test(String(f.imageUrl || '').trim())) { // a malformed URL gets the plain shape message from ads.validate
|
|
const ic = await imageCheck(String(f.imageUrl).trim(), f.size); if (!ic.ok) return { error: ic.reason }; warn = ic.warn || '';
|
|
}
|
|
return { ok: true, warn };
|
|
}
|
|
// Qualified Start attempts (2026-10-19, Michael: 'Add a position and nothing happens'): every step the browser reports
|
|
// and every server answer to a position sign-in, kept as the last 1000 in DATA_DIR/position-attempts.json + one log line
|
|
function posLog(x) {
|
|
const e = Object.assign({ ts: Date.now() }, x); e.email = e.email ? String(e.email).toLowerCase() : null;
|
|
console.log('position attempt', e.email || '-', e.stage, String(e.detail || '').slice(0, 160), e.address || '');
|
|
try { const f = path.join(DATA_DIR, 'position-attempts.json'); let a = []; try { a = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (er) {}
|
|
a.push(e); if (a.length > 1000) a = a.slice(-1000); fs.writeFileSync(f + '.tmp', JSON.stringify(a)); fs.renameSync(f + '.tmp', f); } catch (er) {}
|
|
}
|
|
const editFee = () => { const n = Math.floor(Number(siteConfig().campaignEditFee)); return n >= 0 ? n : 100; };
|
|
// one path for member and admin edits: the outside checks on whatever changed, then ads.editCampaign (shape checks,
|
|
// fee, history, network copy). Open ad-viewer tokens for this campaign get the new link, so a view in flight frames it.
|
|
async function editAd(id, b, who) {
|
|
const c = await ads.campaignById(id);
|
|
if (!c || (!who.admin && String(c.owner || '').toLowerCase() !== String(who.owner || '').toLowerCase())) return { error: 'No such campaign.' };
|
|
const f = {};
|
|
if (b.targetUrl !== undefined && String(b.targetUrl).trim() !== String(c.targetUrl || '')) f.targetUrl = String(b.targetUrl).trim();
|
|
if (c.type === 'banner' && b.imageUrl !== undefined && String(b.imageUrl).trim() !== String(c.imageUrl || '')) { f.imageUrl = String(b.imageUrl).trim(); f.size = c.width && c.height ? c.width + 'x' + c.height : ''; }
|
|
const ck = await adChecks(c.type, f); if (ck.error) return { error: ck.error };
|
|
const r = await ads.editCampaign(who.owner, id, b, { admin: !!who.admin, fee: editFee(), ids: who.ids });
|
|
if (r.ok && r.changed.includes('targetUrl')) for (const t of earnTokens.values()) if (t && Number(t.adId) === Number(id)) t.targetUrl = r.campaign.targetUrl;
|
|
if (r.ok) { r.nextFee = who.admin ? null : editFee(); if (ck.warn) r.warn = ck.warn; }
|
|
return r;
|
|
}
|
|
async function boot() {
|
|
await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode)
|
|
marks.init({ db, dataDir: DATA_DIR });
|
|
marks.ensureTable().catch(e => console.error('marks table', e.message));
|
|
setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref();
|
|
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(() => {});
|
|
if (ev && ev.type === 'Purchase') refuel.onPurchase(ev).catch(e => console.error('refuel report', e.message)); } }); // no-op while refuelStreak is off
|
|
auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: SITE_HOST });
|
|
accounts.init({ dataDir: DATA_DIR });
|
|
ads.init({ dataDir: DATA_DIR, chain });
|
|
mailer.init({ dataDir: DATA_DIR });
|
|
messages.init({ dataDir: DATA_DIR });
|
|
messages.reclassifyCarryNotices(ADMIN_EMAIL || 'house@linkspin.co').then(n => { if (n) console.log('messages: ' + n + ' carry notices made quiet (notice kind)'); }).catch(() => {});
|
|
reports.init({ dataDir: DATA_DIR });
|
|
drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: SITE_URL });
|
|
chatbot.init({ dataDir: DATA_DIR, chain, refuelOn: () => refuel.cfg().on });
|
|
setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000);
|
|
setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000);
|
|
setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends
|
|
// prepaid login-slot queue (Marty, 2026-10-23): a freed slot goes to the oldest paid reservation within the minute
|
|
setInterval(() => ads.promoteLoginQueue().catch(e => console.error('login queue', e.message)), 60 * 1000);
|
|
ads.setLoginQueueNotifier(async (c, info) => {
|
|
const subject = 'Your login ad is live: ' + c.name;
|
|
const text = 'Good news. Your reserved login-ad slot "' + c.name + '" (#' + c.id + ') reached the front of the line and started just now.\n\n'
|
|
+ 'Your page ' + c.targetUrl + ' now shows full screen to every member right after they sign in, for ' + info.days + ' days, until ' + info.endsCt + ' (Central time). '
|
|
+ 'You paid for it when you reserved, so nothing more is charged.\n\nSee it on the Ads screen: ' + SITE_URL + '/ads';
|
|
const html = '<p>' + text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>') + '</p>';
|
|
try { await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [c.owner], subject, html, 'notice'); } catch (e) { console.error('login queue notice', e.message); }
|
|
try { if (mailer.hasKey() && !(await drip.isUnsubscribed(c.owner))) await mailer.send(c.owner, subject, text + '\n\nStop these emails: ' + drip.unsubUrl(c.owner) + '\n\nLinkSpin'); } catch (e) { console.error('login queue email', e.message); }
|
|
});
|
|
// campaign refill notices (2026-10-24, copied from InstantAdPay): told when an ad is nearly out, when it stops, and once more
|
|
// a week later if credits sit idle; one email + one on-site notice per owner, every send watched for what they did next
|
|
refuel.init({ dataDir: DATA_DIR, siteConfig, ads, accounts, marks, mailer, drip, siteUrl: SITE_URL, iapBase: IAP_BASE,
|
|
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [to], subject, html, 'notice'); } });
|
|
kit.init({ dataDir: DATA_DIR, program: 'linkspin', publicDir: PUBLIC_DIR, siteUrl: SITE_URL,
|
|
entitled: async email => { const v = await refuel.status(email); return v && v.on && !v.error ? { on: true, months: v.kits || {}, nextRefuel: v.refuelDayLabel || null, today: v.today || null } : { on: false }; },
|
|
linkFor: async email => { const a = await accounts.byEmail(email); if (!a) return null; const tok = a.username || a.code; return tok ? { username: a.username || null, link: SITE_URL + '/join/' + tok } : null; } });
|
|
setTimeout(() => refuel.tick().catch(e => console.error('refuel', e.message)), 75000);
|
|
setInterval(() => refuel.tick().catch(e => console.error('refuel', e.message)), 60 * 1000);
|
|
// link-farm scan (2026-10-30): 06:30 Central, once a day across app copies (marks), Telegram to the private admin chat only when there is something to review
|
|
spamscan.init({ dataDir: DATA_DIR, site: 'LinkSpin', siteUrl: SITE_URL, otherSite: 'InstantAdPay', accounts, siteConfig, marks,
|
|
saveSite: patch => { const cur = siteConfig(); fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, patch), null, 2)); },
|
|
notify: async text => { const sc = siteConfig(); const chat = String(sc.telegramAdminChatId || '1289244227').trim(); if (sc.telegramBotToken) return telegramSend(chat, text); if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'LinkSpin link-farm scan', text); },
|
|
alsoOn: async (email, a) => (a && a.joinedVia === 'instantadpay') ? true : !!(await registry.get(email)) }); // the local registry mirror of InstantAdPay's rows, never a cascade
|
|
setTimeout(() => spamscan.tick().catch(e => console.error('spamscan', e.message)), 150000);
|
|
setInterval(() => spamscan.tick().catch(e => console.error('spamscan', e.message)), 5 * 60 * 1000);
|
|
refill.init({ dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks, siteUrl: SITE_URL, houseOwner: ads.HOUSE_OWNER, streakLine: email => refuel.streakLine(email),
|
|
creditsFor: async email => { const v = await adminMember.view(email); return (v && v.credits && v.credits.available) || 0; },
|
|
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [to], subject, html, 'notice'); } });
|
|
setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000);
|
|
setInterval(() => refill.tick().catch(e => console.error('refill', e.message)), 20 * 60 * 1000);
|
|
// follow-up email sequence: send whatever came due (every 10 min, first pass shortly after boot)
|
|
coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig, adminEmail: ADMIN_EMAIL });
|
|
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,
|
|
tankGate: (a, o) => tank.gate(a, o), claim: k => marks.claim(k), payoutBlocked: id => payoutChainBlocked(id, 2) }); // holding tank (2026-10-27): network sponsor first, a plain activation held, a purchase never
|
|
// sponsor follow (sponsorfollow.js): deliberate changes (tank adoption, rescue, release, window expiry, admin edit) are
|
|
// recorded and follow to InstantAdPay, and InstantAdPay's are applied here, until the member is bound or binding on the
|
|
// LinkSpin contract (memberId, wallet already on chain, or an engine activation in flight). Ordinary bindings: first platform.
|
|
followStore = SF.create({ dataDir: DATA_DIR, platform: 'linkspin' });
|
|
follow = SF.glue({ store: followStore, accounts, tank: () => tank, peer: 'instantadpay',
|
|
isBound: async a => {
|
|
if (Number(a.memberId) > 0) return { bound: true, why: 'LinkSpin member #' + a.memberId };
|
|
if (carry.isBinding(a.email)) return { retry: true, why: 'a LinkSpin activation is in flight' };
|
|
if (!a.address) return { bound: false };
|
|
try { const id = Number(await chain.memberIdByAccount(a.address)) || 0; if (id) { await accounts.setMemberId(a.email, id).catch(() => {}); return { bound: true, why: 'wallet is LinkSpin member #' + id }; } return { bound: false }; }
|
|
catch (e) { return { retry: true, why: 'LinkSpin chain read failed' }; }
|
|
},
|
|
sponsorAccount: em => accounts.byEmail(em),
|
|
wouldCycle: async (email, sp) => { let cur = sp; const seen = new Set(); for (let i = 0; cur && i < 60; i++) { if (cur.email === email || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); } return false; },
|
|
activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null,
|
|
// a follow that waited (chain read, activation in flight, sponsor not here yet) is settled: switch payouts on now if the
|
|
// wallet arrived meanwhile (the wallet hook below skipped it so the contract would not bind the old sponsor)
|
|
afterResolve: async email => { const a = await accounts.byEmail(email); if (a && a.address && !(Number(a.memberId) > 0)) await carry.ensureOnChain(a, 0, 'wallet'); } });
|
|
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000);
|
|
// payouts on the moment a wallet is linked (Marty, 2026-10-17); the engine pays the gas, sponsors above are activated first.
|
|
// Not while a deliberate sponsor change from InstantAdPay is still waiting to be applied (afterResolve above does it then).
|
|
accounts.onWalletLinked(async email => { if (followStore.pendingFor(email)) { console.log('activation deferred: sponsor follow pending for', email); return; } const a = await accounts.byEmail(email); if (a && a.address) await carry.ensureOnChain(a, 0, 'wallet'); });
|
|
// member numbers for accounts the engine activated before 2026-10-18 (the ledger names people by them); 60 s after boot so a deploy's old copy is gone
|
|
setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000);
|
|
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
|
|
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => iapsync.touch(email));
|
|
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
|
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
|
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
|
|
rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources, wantsClickId: owner => convtrack.goalsOf(owner).length > 0, isNetworkHost: h => networkHosts().includes(String(h || '').toLowerCase().replace(/^www\./, '')), goalRows: () => convtrack.goalRows() });
|
|
convtrack.init({ dataDir: DATA_DIR, rotator, bannerspin, campaignOf: id => ads.campaignById(id) });
|
|
auth.onSeen((email, req) => convtrack.noteSession(email, req)); // own-click tests (2026-10-26): the soft keys a member signs in from
|
|
// destination health: every 30 min, first pass 2 min after boot; a pause lands in the owner's on-site inbox (same path as the payment notices)
|
|
health.init({ rotator, bannerspin, dataDir: DATA_DIR, notify: (email, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, html) });
|
|
setTimeout(() => health.tick().catch(e => console.error('health', e.message)), 2 * 60 * 1000);
|
|
setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000);
|
|
setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
|
|
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources });
|
|
bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts, wantsClickId: (owner, url) => { if (convtrack.goalsOf(owner).length > 0) return true; try { return networkHosts().includes(new URL(url).hostname.toLowerCase().replace(/^www\./, '')); } catch (e) { return false; } }, withClickId: convtrack.withClickId });
|
|
rotator.setExternalConvert((lsid, ev, facts) => /^[ai]/.test(String(lsid)) ? netconv.fromLinkSpin(lsid, ev, facts) : bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks; ad clicks through the ledger
|
|
netconv.init({ dataDir: DATA_DIR, convtrack, rotator, bannerspin, postbacks, marks });
|
|
sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } });
|
|
zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST });
|
|
pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } });
|
|
audiences.init({ dataDir: DATA_DIR });
|
|
// link-domain pool: channels live in site.json (linkDomainChannels), check state in domains.json; a burn alerts the admin once
|
|
domains.init({ dataDir: DATA_DIR, siteConfig, saveSite: patch => fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(siteConfig(), patch), null, 2)),
|
|
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) await telegramSend(sc.telegramAdminChatId, text); else if (ADMIN_EMAIL && mailer.hasKey()) await mailer.send(ADMIN_EMAIL, 'LinkSpin: link domain burned', text.replace(/<[^>]+>/g, '')); } });
|
|
zonereport.init({ dataDir: DATA_DIR });
|
|
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, accounts, rotator, bannerspin, zones, pages, 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({ capOpen: () => siteConfig().tankAdoptCap, dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore,
|
|
// network alignment + activation hold + 24-hour safety net (2026-10-27): a tank member's plain activation is never
|
|
// bound under the fallback position; their InstantAdPay sponsor first, else an adopter (a purchase is never held)
|
|
hooks: { network: (email, address) => networkSponsor(email, address), prefetch: emails => iapFacts(emails, { timeout: 20000 }),
|
|
iapOwns: (email, o) => iapOwnsTank(email, o), bound: async a => { const id = Number(await chain.memberIdByAccount(a.address)) || 0; if (id) await accounts.setMemberId(a.email, id).catch(() => {}); return id; },
|
|
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
|
|
notify: (email, subject, text) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, '<p>' + String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/(https:\/\/[^\s)]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>') + '</p>'),
|
|
lifted: email => tankLifted(email), claim: k => marks.claim(k), assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text) } });
|
|
legacy.init({ dataDir: DATA_DIR });
|
|
traffic.init({ dataDir: DATA_DIR });
|
|
promos.init({ dataDir: DATA_DIR });
|
|
blog.init({ dataDir: DATA_DIR });
|
|
adminMember.init({ accounts, ads, chain, tank, legacy, promos, messages, dataDir: DATA_DIR });
|
|
loadOpenTokens();
|
|
syndicate.init({ dataDir: DATA_DIR, publicDir: PUBLIC_DIR, uploadsDir: UPLOADS_DIR });
|
|
releases.init({ dataDir: DATA_DIR });
|
|
toolkit.init({ dataDir: DATA_DIR, ads, accounts, siteConfig, coach, messages, promos, videomaker, chain });
|
|
updates.init({ dataDir: DATA_DIR, accounts, releases, mailer, drip, sendy, adminEmail: ADMIN_EMAIL });
|
|
audit.init({ dataDir: DATA_DIR, notify: text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: counter audit', text).catch(() => {}); } });
|
|
setTimeout(() => audit.dailyTick(), 5 * 60 * 1000); setInterval(() => audit.dailyTick(), 24 * 60 * 60 * 1000);
|
|
videomaker.init({ dataDir: DATA_DIR, spaces, accounts });
|
|
content.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, accounts, pages, rotator, bannerspin, sources, zones, ads, postbacks, audiences, messages, videomaker, reports, domains, adminEmail: ADMIN_EMAIL, houseOwner: ads.HOUSE_OWNER, siteHost: SITE_HOST, linkHost: () => domains.live()[0] || SITE_HOST, pagesHost });
|
|
leaderboard.init({ chain, accounts, ads, dataDir: DATA_DIR, siteConfig, pushFeed, adminEmail: ADMIN_EMAIL,
|
|
notify: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); if (String(sc.leaderboardAnnounceGeneral || '1') !== '0') await telegramSend(sc.telegramEchoChatId, text, null); } });
|
|
setTimeout(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 90 * 1000);
|
|
setInterval(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 60 * 60 * 1000);
|
|
console.log('blog syndication:', syndicate.enabled() ? 'on (X + Instagram via Blotato)' : 'off (no blotato.key)');
|
|
setInterval(() => tankNotifyTick().catch(e => console.error('tank notify', e.message)), 15 * 60 * 1000); // new tank arrivals -> Telegram
|
|
setTimeout(() => tankReadyTick().catch(e => console.error('tank ready', e.message)), 3 * 60 * 1000); // after the first iapsync / registry rows
|
|
setInterval(() => tankReadyTick().catch(e => console.error('tank ready', e.message)), 15 * 60 * 1000); // align / 24-hour hold / safety net
|
|
geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message));
|
|
setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily
|
|
setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window
|
|
burner.init({ chain, ads, accounts });
|
|
if (OUTBOUND_MAIL) { // the stall nudges are a mailing loop; do not even start it when mail is off
|
|
setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000);
|
|
setInterval(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 60 * 60 * 1000);
|
|
}
|
|
setTimeout(() => burner.tick().catch(e => console.error('burner', e.message)), 45 * 1000);
|
|
setInterval(() => burner.tick().catch(e => console.error('burner', e.message)), 5 * 60 * 1000);
|
|
// level-4 override: Monday report (dry run) or the weekly payer (live); summaries to Marty's admin Telegram, email fallback
|
|
override.init({ dataDir: DATA_DIR, chain, siteConfig, db, brand: 'LinkSpin', siteUrl: SITE_URL,
|
|
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) { await telegramSend(sc.telegramAdminChatId, text); return true; } if (ADMIN_EMAIL && mailer.hasKey()) { await mailer.send(ADMIN_EMAIL, 'LinkSpin: level-4 override', text.replace(/<[^>]+>/g, '')); return true; } return false; } });
|
|
setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000);
|
|
// launch week: Founder grant from the launch moment (idempotent, every 10 minutes) + the /leaderboard contest panel; POL prizes only by the admin button
|
|
launchweek.init({ accounts, chain, marks, leaderboard, siteConfig, dataDir: DATA_DIR, adminEmail: ADMIN_EMAIL, payer: () => override.payerHandle(), txLink: h => override.polygonTx(h) });
|
|
leaderboard.setLaunchPanel(() => launchweek.panelHtml());
|
|
setTimeout(() => launchweek.tick().catch(e => console.error('launchweek', e.message)), 2 * 60 * 1000);
|
|
setInterval(() => launchweek.tick().catch(e => console.error('launchweek', e.message)), 10 * 60 * 1000);
|
|
if (OUTBOUND_MAIL) { // same for the lead follow-up sequence
|
|
setTimeout(() => drip.tick().catch(e => console.error('drip', e.message)), 30 * 1000);
|
|
setInterval(() => drip.tick().catch(e => console.error('drip', e.message)), 10 * 60 * 1000);
|
|
}
|
|
// NAS reconcile: pull syndicated delivery into the unified credit pool
|
|
// (inert unless NAS_DB_* is set). Every 5 min after a short warm-up.
|
|
if (ads.nasEnabled()) {
|
|
console.log('NAS syndication enabled');
|
|
setTimeout(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 90 * 1000);
|
|
setInterval(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 5 * 60 * 1000);
|
|
}
|
|
}
|
|
|
|
// InstantAdPay's Engine Room facts + the streak for one member (signed /api/partner/engine), cached a minute
|
|
const iapEngineCache = new Map();
|
|
async function engineFromIap(email, fresh) {
|
|
const hit = iapEngineCache.get(email); if (!fresh && hit && Date.now() - hit.at < 60000) return hit.v;
|
|
let v = null; try { const r = await SF.peerPost(IAP_BASE(), '/api/partner/engine', { email }, 6000); v = r && r.refuel ? { refuel: r.refuel, facts: r.facts } : null; } catch (e) { v = null; }
|
|
iapEngineCache.set(email, { at: Date.now(), v }); if (iapEngineCache.size > 2000) iapEngineCache.delete(iapEngineCache.keys().next().value);
|
|
return v;
|
|
}
|
|
function siteConfig() {
|
|
let saved = {};
|
|
try { saved = JSON.parse(fs.readFileSync(SITE_FILE, 'utf8')); } catch (e) {}
|
|
return Object.assign({
|
|
siteName: 'LinkSpin',
|
|
tagline: 'Advertise and earn. Locked in code, not promises.',
|
|
rehearsal: true, // shows the testnet banner; flipped off at mainnet launch
|
|
// payment-proof Telegram feed (blank = off) and the P&L pane's fixed monthly cost
|
|
telegramBotToken: '', telegramChatId: '', telegramTopicId: '', telegramEvents: 'payouts', telegramCtaUrl: SITE_URL + '/',
|
|
telegramEchoChatId: '', telegramEchoTopicId: '', telegramEchoEvents: 'payouts', // shared cross-program payments topic
|
|
telegramAdminChatId: '', // private chat for admin alerts (sign-up guard bursts); falls back to ADMIN_EMAIL
|
|
spamScanAllow: spamscan.DEFAULT_ALLOW.join(', '), // link-farm scan (2026-10-30): emails never listed as candidates; Admin > Members > Link-farm list > Allow adds here
|
|
founderGrant: '1', // Founder badge: '0' stops the automatic grant at the launch moment (launchweek.js); the badge is cosmetic
|
|
launchContest: '1', launchContestStart: '', launchContestEnd: '2026-11-22T00:00:00-06:00', launchContestPrizesPol: '10,6,4', launchContestMinSales: 2, launchContestMinCents: 0, launchContestExcludeEmails: '', launchContestExcludeIds: '', // launch week contest: start '' = launchAt; end is EXCLUSIVE (all of Sat Nov 21 Central); POL prizes 1st,2nd,3rd paid only by the admin button; admin + overrideHouseIds always excluded
|
|
launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark
|
|
aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation
|
|
carryClaimDays: '3',
|
|
carryNotices: '1', // 0 = carry-over notices stay on-site (test area), 1 = email too // sponsor with no wallet: days to link one before a downline seat walks up (LinkSpin)
|
|
linkDomains: '', // comma list of short link domains this server answers for (each gets a real mini-site + /r/ redirects)
|
|
pagesDomain: '', // the host member pages are published on at the root (https://<pagesDomain>/<slug>); empty = first link domain under /p/
|
|
snapshotEnabled: '1', snapshotHourUtc: '14', snapshotTargets: 'feed,echo', // daily growth snapshot: 14 UTC = 9 AM Central; feed = proof channel, echo = shared payments topic
|
|
pipelineMode: 'off', // Pipeline board: off = 'coming soon' card, preview = only the admin account sees the live board, on = everyone (Marty, 2026-09-15)
|
|
pipelineEta: 'Sep 28', // what the coming-soon card and the roadmap promise
|
|
coachMail: '1', // 0 = stall-nudge emails off (pre-launch: imported shell accounts must not be nudged)
|
|
memberWeeklyEmail: '0', // 1 = the weekly 'Your week on LinkSpin' email goes to every active member, not only sponsors with a line
|
|
noPayoutIds: '', // LinkSpin member ids differ from InstantAdPay's (IAP #25 = Jim's compromised wallet; LinkSpin #25 is a real member, cleared 2026-10-15). Positions kept for linkage only (compromised wallets): no buys signed from them, no new joins routed under them or their upline chain (Marty, 2026-09-14)
|
|
leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover)
|
|
tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11
|
|
legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand>
|
|
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
|
|
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
|
|
pnlFixedMonthlyUsd: 0,
|
|
refillNotices: '1', refillLowPct: 80,
|
|
refuelStreak: '0', refuelMinLsCents: 2500, // Monthly Refuel streak (2026-10-24): '0' = nothing reported or shown; the streak itself lives on InstantAdPay // refill notices (2026-10-24): '0' turns them off; the share of a budget delivered that counts as running low
|
|
campaignEditFee: 100 // credits per ad edit after each campaign's first, free one (Orlando's ask, 2026-10-18); 0 = edits always free
|
|
}, saved);
|
|
}
|
|
|
|
// ---- helpers ----
|
|
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript',
|
|
'.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp',
|
|
'.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2',
|
|
'.gif': 'image/gif', '.webm': 'video/webm', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' };
|
|
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:";
|
|
function baseHeaders(extra) {
|
|
return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff',
|
|
'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {});
|
|
}
|
|
function json(res, code, obj, extra) {
|
|
const body = JSON.stringify(obj);
|
|
res.writeHead(code, baseHeaders(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra)));
|
|
res.end(body);
|
|
}
|
|
function sendFile(res, file) {
|
|
fs.readFile(file, (err, data) => {
|
|
if (err) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
|
|
const ext = path.extname(file).toLowerCase();
|
|
// Public pages carry {{SITE_URL}} / {{SITE_HOST}} in canonical, OG and sitemap lines so the same files
|
|
// serve every deployment (test host today, linkspin.app at launch); filled here, per request.
|
|
if (ext === '.html' || ext === '.txt' || ext === '.xml') data = Buffer.from(data.toString('utf8').split('{{SITE_URL}}').join(SITE_URL).split('{{SITE_HOST}}').join(SITE_HOST));
|
|
res.writeHead(200, baseHeaders({ 'Content-Type': MIME[ext] || 'application/octet-stream',
|
|
// HTML is never stored (so a fresh load always gets the current asset
|
|
// versions — aggressive in-app wallet browsers were serving stale pages
|
|
// that pointed at old, since-fixed JS); versioned assets cache for an hour.
|
|
'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' }));
|
|
res.end(data);
|
|
});
|
|
}
|
|
function readRaw(req, maxBytes) {
|
|
return new Promise((resolve, reject) => {
|
|
const chunks = [];
|
|
let n = 0;
|
|
req.on('data', c => {
|
|
n += c.length;
|
|
if (n > maxBytes) { req.destroy(); reject(new Error('too big')); return; }
|
|
chunks.push(c);
|
|
});
|
|
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
req.on('error', reject);
|
|
});
|
|
}
|
|
// conversion pixel (2026-10-23): the click-id cookie on our own host. SameSite=None so the goal pixel (a third-party image
|
|
// on the member's thank-you page) can still send it where the browser allows third-party cookies; 30 days like the window.
|
|
// the image pixel cannot read the thank-you page's address, but a browser that sends the full referrer hands it to us
|
|
function refClickId(req) { try { const r = new URL(String(req.headers.referer || '')); const v = r.searchParams.get('lsclk') || r.searchParams.get('lsid') || ''; return /^[a-z0-9]{6,24}$/i.test(v) ? v : ''; } catch (e) { return ''; } }
|
|
// the sites of the network a click id may travel to (the landing tag's list, 2026-11-07): this site, InstantAdPay, its share domains
|
|
const NETWORK_HOSTS = String(process.env.NETWORK_HOSTS || 'instantadpay.com,instantadpay.link,ctbgo.com,mylinehq.com').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
|
function networkHosts() { return [...new Set([String(SITE_HOST || '').toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '')].concat(NETWORK_HOSTS))].filter(Boolean); }
|
|
function clickCookie(id) { return 'ls.clk=' + id + '; Path=/; Max-Age=2592000; ' + (IS_PROD ? 'SameSite=None; Secure' : 'SameSite=Lax'); }
|
|
// an ad click: record a click id for the campaign and append ?lsclk=<id> to the target (existing params kept, an lsclk
|
|
// already there left alone). A spin-link target passes it on, so the spin-link click inherits the ad as its source.
|
|
// Never blocks the click: on any failure the visitor goes to the target unchanged.
|
|
// a spin-link or Banner Spin click by its owner (signed in here, or from a browser the owner signs in from) is marked so
|
|
// a goal it leads to is kept as a test, never counted (2026-10-26). Only for owners who track goals; never blocks the click.
|
|
async function markOwnClick(id, owner, req) {
|
|
try {
|
|
if (!owner || !convtrack.goalsOf(owner).length) return;
|
|
let email = ''; if (/(?:^|;\s*)iap\.sid=/.test(req.headers.cookie || '')) { const s = await auth.fromRequest(req); email = (s && s.email) || ''; }
|
|
convtrack.markSelfClick(id, owner, req, email);
|
|
} catch (e) { console.error('own click mark', e.message); }
|
|
}
|
|
async function adClickTarget(campOrId, url, req, extra) {
|
|
try {
|
|
const camp = typeof campOrId === 'object' ? campOrId : await ads.campaignById(campOrId); if (!camp) return { url };
|
|
let self = false; try { const s = await auth.fromRequest(req); self = !!(s && s.email && String(s.email).toLowerCase() === String(camp.owner || '').toLowerCase()); } catch (e) {}
|
|
const id = convtrack.recordAdClick(camp, req, Object.assign({ country: viewerGeo(req).cc || '', self }, extra || {})); if (!id) return { url };
|
|
let out = url; try { const t = new URL(url); if (!t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {}
|
|
return { url: out, cookie: clickCookie(id), id };
|
|
} catch (e) { console.error('ad click id', e.message); return { url }; }
|
|
}
|
|
function readBody(req, max) { // max: a larger body for one admin route only (2026-11-11, BTC4Hits import: #297 has 834 URLs); everything else stays at 64 KB
|
|
return new Promise((resolve, reject) => {
|
|
let d = ''; let n = 0;
|
|
req.on('data', c => { n += c.length; if (n > (max || 64 * 1024)) { req.destroy(); reject(new Error('too big')); } d += c; });
|
|
req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { reject(e); } });
|
|
req.on('error', reject);
|
|
});
|
|
}
|
|
function parseCookies(req) {
|
|
const out = {};
|
|
for (const p of (req.headers.cookie || '').split(';')) {
|
|
const i = p.indexOf('='); if (i > 0) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim());
|
|
}
|
|
return out;
|
|
}
|
|
function isAdmin(req) {
|
|
const h = req.headers.authorization || '';
|
|
if (h === 'Bearer ' + ADMIN_PASSWORD) return true;
|
|
return !!adminFromRequest(req); // /admin portal session
|
|
}
|
|
// attach a memberId->username map to events so activity shows real people
|
|
async function attachNames(evts) {
|
|
try {
|
|
const ids = [];
|
|
for (const ev of evts)
|
|
for (const k of ['id', 'buyerId', 'recipientId', 'skippedId', 'sponsorId', 'newBuyerId', 'toId', 'memberId'])
|
|
if (ev[k]) ids.push(ev[k]);
|
|
const names = await accounts.namesForMembers(ids);
|
|
if (!Object.keys(names).length) return evts;
|
|
return evts.map(ev => Object.assign({}, ev, { names }));
|
|
} catch (e) { return evts; }
|
|
}
|
|
// A sponsor token is a numeric chain id or a site share code. Codes resolve
|
|
// to the referrer's CURRENT chain id, so activation any time before the
|
|
// referral's first purchase still locks the line to them.
|
|
// No-payout positions (siteConfig.noPayoutIds): a member id whose on-chain wallet must never be paid again.
|
|
// A purchase pays the buyer's three uplines, so a buy from `id` is blocked when id itself or any of its three
|
|
// uplines is listed; a join under `id` is blocked when id or its two uplines is listed (the new member's buys
|
|
// would reach the listed wallet at tier 2 or 3). Returns the listed id that would be hit, else 0.
|
|
function noPayoutSet() { return new Set(String(siteConfig().noPayoutIds || '').split(/[,\s]+/).map(Number).filter(n => n > 0)); }
|
|
async function payoutChainBlocked(id, hops) {
|
|
const bad = noPayoutSet(); if (!bad.size || !id) return 0;
|
|
let cur = Number(id);
|
|
for (let i = 0; i <= hops && cur; i++) { if (bad.has(cur)) return cur; let m = null; try { m = await chain.member(cur); } catch (e) { break; } cur = m ? Number(m.sponsorId) || 0 : 0; }
|
|
return 0;
|
|
}
|
|
// Why a sponsor token did not resolve matters (vladz79 → #24 locked under the company on 2026-09-13 because a
|
|
// lookup came back empty and the code fell back silently): 'ok' | 'none' (no token) | 'unknown' (no such account)
|
|
// | 'notActivated' (sponsor has no wallet / payouts off) | 'rpc' (chain lookup failed right now).
|
|
async function resolveSponsorDetailed(tok) {
|
|
const t = String(tok || '').trim().toLowerCase();
|
|
if (!t) return { id: 0, reason: 'none' };
|
|
if (/^\d+$/.test(t)) return { id: Number(t), reason: 'ok' };
|
|
let acct = await accounts.byCode(t);
|
|
if (!acct) acct = await accounts.byUsername(t); // vanity links: /join/<username>
|
|
if (!acct) return { id: 0, reason: 'unknown', name: t };
|
|
if (!acct.address) return { id: 0, reason: 'notActivated', name: acct.username ? '@' + acct.username : t };
|
|
try { const id = await chain.memberIdByAccount(acct.address); return { id, reason: id ? 'ok' : 'notActivated', name: acct.username ? '@' + acct.username : t }; }
|
|
catch (e) { return { id: 0, reason: 'rpc', name: acct.username ? '@' + acct.username : t }; }
|
|
}
|
|
// The chain-bound sponsor of an activated member, as a resolveSponsorDetailed-shaped answer with a display name; null when the
|
|
// member is not on chain or the read fails (callers then fall back to the account's sponsor field).
|
|
async function sponsorByChain(memberId) {
|
|
const id = Number(memberId) || 0; if (id <= 0) return null;
|
|
try {
|
|
const me = await chain.member(id); const sid = Number(me && me.sponsorId) || 0; if (!sid) return null;
|
|
let name = 'member #' + sid;
|
|
try { const sp = await chain.member(sid); const a = sp && sp.account ? await accounts.byAddress(String(sp.account).toLowerCase()) : null; if (a && a.username) name = '@' + a.username; } catch (e) { /* name stays member #N */ }
|
|
return { id: sid, reason: 'ok', name, chain: true };
|
|
} catch (e) { return null; }
|
|
}
|
|
async function resolveSponsorToken(tok) { return (await resolveSponsorDetailed(tok)).id; }
|
|
const sponsorAlertLast = new Map(); // email -> ts (one alert per member per hour)
|
|
function sponsorBlockedAlert(who, r) {
|
|
const k = String(who || '?'); if (Date.now() - (sponsorAlertLast.get(k) || 0) < 3600000) return; sponsorAlertLast.set(k, Date.now());
|
|
const text = '\u26A0\uFE0F LinkSpin: sale routed for ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + '. Their sponsor ' + (r.name || r.tok || '?') + ' could not be paid (' + r.reason + '), so the purchase went to ' + (r.routedTo || 'the company') + ' and the member moved with it. Purchases are never held.';
|
|
const sc = siteConfig();
|
|
if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {});
|
|
else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: sale routed, sponsor could not be paid', text).catch(() => {});
|
|
}
|
|
// The moment someone joins through a code, nudge its owner to activate.
|
|
// Email a member's sponsor the moment they get a new referral (free OR paid).
|
|
// Resolves the sponsor from the join token by member id, share code, or username,
|
|
// and notifies EVERY sponsor — activated or not (an active sponsor still wants to
|
|
// know their team grew). A referral is on the line from signup; it only counts
|
|
// toward qualification once it makes a $25+ purchase.
|
|
async function notifyNewReferral(ref, newAcct) {
|
|
try {
|
|
if (!mailer.hasKey()) return;
|
|
const t = String(ref || '').trim().toLowerCase();
|
|
if (!t) return;
|
|
let owner = null;
|
|
if (/^\d+$/.test(t)) { try { owner = await accounts.byMemberId(Number(t)); } catch (e) {} }
|
|
if (!owner) { try { owner = await accounts.byCode(t); } catch (e) {} }
|
|
if (!owner) { try { owner = await accounts.byUsername(t); } catch (e) {} }
|
|
if (!owner || !owner.email) return;
|
|
const who = newAcct && newAcct.username ? '@' + newAcct.username : 'A new member';
|
|
let body = who + ' just joined LinkSpin through your link — they are on your team from today.\n\n'
|
|
+ 'They count toward your qualification once they make a $25+ purchase.\n\n';
|
|
if (!owner.address) body += 'Make sure payouts are switched on (one free wallet step) so you never miss a commission — '
|
|
+ 'the contract locks each buyer to their sponsor at their first purchase.\n\n';
|
|
body += 'See your team: ' + SITE_URL + '/team\n\nLinkSpin';
|
|
mailer.send(owner.email, 'You have a new referral on LinkSpin', body)
|
|
.catch(e => console.error('referral notify failed', e.message));
|
|
} catch (e) {}
|
|
}
|
|
// welcome email on a new account: onboarding steps + who their sponsor is
|
|
// how a member is named in emails/alerts: @username, a linked position named after its owner, else member #id
|
|
async function memberLabel(id) {
|
|
try {
|
|
let a = await accounts.byMemberId(id);
|
|
if (!a) { // brand-new buyer: the account learns its member id on its next page load, so read the
|
|
// wallet from the chain and match it now (Jim's purchase mailed as "member #25", 2026-09-13)
|
|
try { const m = await chain.member(id); if (m && m.account) { a = await accounts.byAddress(String(m.account).toLowerCase()); if (a && !a.memberId) accounts.setMemberId(a.email, id).catch(() => {}); } } catch (e) {}
|
|
}
|
|
if (a && a.username) return '@' + a.username;
|
|
const pos = await accounts.positionByMember(id);
|
|
if (pos && pos.email) { const o = await accounts.byEmail(pos.email); if (o && o.username) return '@' + o.username + ' (extra position #' + id + ')'; }
|
|
} catch (e) {}
|
|
return 'member #' + id;
|
|
}
|
|
async function sendWelcome(email, ref) {
|
|
try {
|
|
if (!mailer.hasKey()) return;
|
|
const spon = await accounts.sponsorOf(email);
|
|
const who = spon ? (spon.username ? '@' + spon.username : 'member #' + (spon.memberId || 0)) : '';
|
|
const sponsorLine = who ? ('You joined through ' + who + ', your sponsor. They are there to help you get started, and you can message them anytime from your dashboard.\n\n') : '';
|
|
mailer.send(email, 'Welcome to LinkSpin',
|
|
'Your free LinkSpin account is ready.\n\n' + sponsorLine
|
|
+ 'Getting started:\n'
|
|
+ '1. Pick your username and fill out your profile.\n'
|
|
+ '2. Grab your invite link and start sharing to build your line.\n'
|
|
+ '3. Explore the ad packages when you are ready. Every payout settles on-chain, straight to your wallet.\n\n'
|
|
+ 'Sign in anytime: ' + SITE_URL + '/links\n\nLinkSpin').catch(() => {});
|
|
} catch (e) {}
|
|
}
|
|
// on-chain event emails: a payout received, or a payout that passed you by
|
|
const weiToPol = w => { try { return (Number(BigInt(w) / (10n ** 14n)) / 10000).toString(); } catch (e) { return '?'; } };
|
|
async function emailOnEvent(ev) {
|
|
if (!ev) return;
|
|
const notify = async (memberId, subject, body) => {
|
|
if (!memberId || !mailer.hasKey()) return;
|
|
const a = await accounts.byMemberId(memberId);
|
|
if (a && a.email) mailer.send(a.email, subject, body + '\n\nSee it on the live ledger: ' + SITE_URL + '/ledger\n\nLinkSpin').catch(() => {});
|
|
};
|
|
// Marty (2026-09-15): payment and missed-payment notices also land in the on-site inbox, so
|
|
// they are waiting (login modal + Messages card) whether or not the email was read. Sent as
|
|
// the company account (#1), the same sender the credit-return notes used. Plain text in, HTML out.
|
|
const inboxNote = async (memberId, subject, text) => {
|
|
if (!memberId) return;
|
|
try {
|
|
const a = await accounts.byMemberId(memberId);
|
|
if (!a || !a.email) return;
|
|
const html = '<p>' + String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
.replace(/(https:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>';
|
|
await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [a.email], subject, html);
|
|
} catch (e) {}
|
|
};
|
|
const tell = async (memberId, subject, text) => { await notify(memberId, subject, text); await inboxNote(memberId, subject, text); };
|
|
const PCT = { 1: 50, 2: 20, 3: 10 };
|
|
// the Purchase event of the same tx is already indexed (it precedes every payout log), so the
|
|
// dollar side of any share is that purchase's price times the tier percentage
|
|
const purchaseOf = tx => { try { return chain.recentEvents(600).find(e => e.tx === tx && e.type === 'Purchase'); } catch (e) { return null; } };
|
|
const usdShare = (pur, pct) => pur ? (' (about ' + ('$' + (pur.priceCents * pct / 10000).toFixed(2)).replace(/\.00$/, '') + ')') : '';
|
|
const txUrlOf = tx => { const cc = chain.getConfig(); return (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + tx; };
|
|
if (ev.type === 'Purchase') {
|
|
const cc = chain.getConfig();
|
|
const txUrl = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx;
|
|
let bal = ev.creditAmount;
|
|
try { bal = await chain.creditBalance(ev.buyerId, ev.creditType); } catch (e) {}
|
|
await notify(ev.buyerId, 'Your LinkSpin purchase is confirmed',
|
|
'Your purchase is complete and settled on-chain.\n\n' +
|
|
'Ad credits added: ' + ev.creditAmount + '\n' +
|
|
'Your ad-credit balance is now: ' + bal + '\n' +
|
|
'Amount paid: ' + weiToPol(ev.paidWei) + ' POL\n\n' +
|
|
'View your transaction on the blockchain:\n' + txUrl);
|
|
// tell the buyer's DIRECT sponsor their referral just bought (upline earners
|
|
// are separately notified by the TierPaid payout email when they earn)
|
|
try {
|
|
const buyer = await chain.member(ev.buyerId);
|
|
if (buyer && buyer.sponsorId) {
|
|
const sp = await accounts.byMemberId(buyer.sponsorId);
|
|
if (sp && sp.email) {
|
|
const bn = await memberLabel(ev.buyerId); // @username at a glance (Marty, 2026-09-12)
|
|
const usd = ('$' + (ev.priceCents / 100).toFixed(2)).replace(/\.00$/, '');
|
|
const qual = ev.priceCents >= 2500
|
|
? ' This is a $25+ purchase, so it counts toward your qualification.'
|
|
: ' (Purchases under $25 do not count toward qualification.)';
|
|
mailer.send(sp.email, bn + ' just bought a ' + usd + ' ad package',
|
|
'Your referral ' + bn + ' (member #' + ev.buyerId + ') just purchased a package (' + usd + ' — ' + ev.creditAmount + ' credits).' + qual + '\n\n' +
|
|
'See your team and the live ledger: ' + SITE_URL + '/team\n\nLinkSpin').catch(() => {});
|
|
}
|
|
}
|
|
} catch (e) {}
|
|
}
|
|
else if (ev.type === 'TierPaid') {
|
|
const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx);
|
|
let buyer = 'a member on your level ' + ev.tier; try { buyer = await memberLabel(ev.buyerId); } catch (e) {}
|
|
const pol = weiToPol(ev.amountWei);
|
|
await tell(ev.recipientId, 'You just got paid ' + pol + ' POL on LinkSpin',
|
|
buyer + ' just bought an ad package on your level ' + ev.tier + (pur ? ' ($' + (pur.priceCents / 100).toFixed(2).replace(/\.00$/, '') + ')' : '') + '. Your ' + pct + ' percent share, ' + pol + ' POL' + usdShare(pur, pct) + ', landed in your wallet in the same transaction' + (ev.hops ? ', passed up to you because someone between you was not qualified for this level' : '') + '.\n\n' +
|
|
'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
|
}
|
|
else if (ev.type === 'AwardPaid') {
|
|
const ov = override.txInfo(ev.tx); // a level-4 override payment from the weekly payer
|
|
const lw = !ov && launchweek.txInfo(ev.tx); // a launch week contest prize (admin-approved)
|
|
if (lw) await tell(ev.toId, 'Your launch week contest prize is paid: ' + weiToPol(ev.amountWei) + ' POL', 'You placed ' + ['1st', '2nd', '3rd', '4th', '5th'][lw.place - 1] + ' in the LinkSpin launch week contest. Your prize just landed in your wallet: ' + weiToPol(ev.amountWei) + ' POL.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
|
else if (ov) await tell(ev.toId, 'Your Level 4 override is paid: ' + weiToPol(ev.amountWei) + ' POL', 'Your Level 4 override for the week of ' + ov.week + ' just landed in your wallet: ' + weiToPol(ev.amountWei) + ' POL. That is 3 percent of the purchases made four levels down in your line (or deeper, when the upline between was not yet qualified), paid weekly from the company wallet. You earn it while you have 5 or more qualifying buyers.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
|
else await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on LinkSpin', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
|
}
|
|
else if (ev.type === 'PassedUp' && ev.reason === 'send-failed') {
|
|
// the member WAS qualified but their wallet rejected the POL (usually a smart-contract
|
|
// wallet that needs more than the capped gas): tell them and the admin, loudly
|
|
await tell(ev.skippedId, 'Your wallet rejected a payout on LinkSpin', 'A level-' + ev.tier + ' payout tried to reach your linked wallet and the wallet refused the transfer, so it passed to the next qualified member. This happens with some smart-contract wallets. Link a regular wallet address (MetaMask, SafePal, Phantom) on the Wallet tab so the next payout lands.\n\nTransaction: ' + txUrlOf(ev.tx));
|
|
if (ADMIN_EMAIL) mailer.send(ADMIN_EMAIL, 'LinkSpin: payout send-failed for member #' + ev.skippedId, 'A level-' + ev.tier + ' payout to member #' + ev.skippedId + ' failed at the wallet (send-failed) and passed up. Tx: ' + ev.tx + '\n\nThe member has been emailed to link a regular wallet.').catch(() => {});
|
|
}
|
|
else if (ev.type === 'PassedUp') {
|
|
// Marty (2026-09-15): a member who missed a payout because they were not qualified must be told
|
|
// exactly what they missed: who bought, the share in POL and dollars, and how to close the gap.
|
|
const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx);
|
|
let pol = '', buyer = 'a member on your level ' + ev.tier;
|
|
try { if (pur) pol = weiToPol((BigInt(pur.paidWei) * BigInt(pct) / 100n).toString()); buyer = await memberLabel(ev.buyerId); } catch (e) {}
|
|
let bc = 0; try { bc = (await chain.member(ev.skippedId)).buyerCount || 0; } catch (e) {}
|
|
const need = ev.tier === 3 ? 5 : 2, short = Math.max(0, need - bc);
|
|
const what = pol ? pol + ' POL' + usdShare(pur, pct) : 'a level-' + ev.tier + ' payout';
|
|
await tell(ev.skippedId, 'You missed ' + (pol ? pol + ' POL' : 'a payout') + ' on LinkSpin',
|
|
buyer + ' just bought an ad package on your level ' + ev.tier + '. Your share was ' + what + ', and it passed you by because level ' + ev.tier + ' is not open on your account yet. The contract paid it to the next qualified person above you.\n\n' +
|
|
'Level ' + ev.tier + ' opens at ' + need + ' qualifying buyers (people you referred who bought a $25 or larger package). You have ' + bc + (short ? ', so you are ' + short + ' buyer' + (short === 1 ? '' : 's') + ' away.' : '.') + '\n\n' +
|
|
'Two ways to close the gap: bring ' + (short || 1) + ' more buyer' + (short === 1 ? '' : 's') + ' from your My line page, or use Qualified Start under Buy packages to be your own buyer today. Every package on level ' + ev.tier + ' pays you ' + pct + ' percent once it is open, and the next one is coming whether you are ready or not.\n\n' +
|
|
'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
|
}
|
|
}
|
|
// payment-proof Telegram feed (same pattern as the RM Circle proof channel): one compact
|
|
// line per event, admin-configured under Settings > Site (telegramBotToken, telegramChatId,
|
|
// optional telegramTopicId, telegramEvents = payouts | payouts+purchases | all, telegramCtaUrl)
|
|
// A second target, telegramEchoChatId + telegramEchoTopicId (+ telegramEchoEvents), echoes
|
|
// the same lines into a shared cross-program payments topic that RM Circle also posts to,
|
|
// so every line there carries the program name.
|
|
async function telegramOnEvent(ev) {
|
|
const sc = siteConfig();
|
|
if (!sc.telegramBotToken || !ev) return;
|
|
if (!sc.telegramChatId && !sc.telegramEchoChatId) return;
|
|
const names = await accounts.namesForMembers([ev.recipientId, ev.buyerId, ev.sponsorId, ev.newBuyerId, ev.id, ev.toId].filter(Boolean)).catch(() => ({}));
|
|
const who = id => '#' + id + (names[id] ? ' @' + names[id] : '');
|
|
const cc = chain.getConfig();
|
|
const tx = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx;
|
|
const build = (mode) => {
|
|
let line = null;
|
|
if (ev.type === 'TierPaid') line = '\u{1F4B8} Level ' + ev.tier + ' payout: <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.recipientId);
|
|
else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has <b>' + ev.newCount + '</b> qualifying buyer' + (ev.newCount === 1 ? '' : 's') + (ev.newCount === 2 ? ' \u00b7 level 2 open' : ev.newCount === 5 ? ' \u00b7 level 3 open' : '');
|
|
else if (ev.type === 'Purchase' && mode !== 'payouts') line = '\u{1F9FE} ' + who(ev.buyerId) + ' bought a $' + Math.round(ev.priceCents / 100) + ' package';
|
|
else if (ev.type === 'AwardPaid') line = '\u{1F4B8} ' + (override.txInfo(ev.tx) ? 'Level 4 override' : launchweek.txInfo(ev.tx) ? 'Launch week contest prize' : 'Award payout') + ': <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.toId);
|
|
else if (ev.type === 'MemberActivated' && mode === 'all') line = '\u{1F91D} ' + who(ev.id) + ' switched on payouts';
|
|
if (!line) return null;
|
|
return line + ' \u00b7 <a href="' + tx + '">verify</a>' + (sc.telegramCtaUrl ? '\n<a href="' + sc.telegramCtaUrl + '">Join free</a>' : '');
|
|
};
|
|
if (sc.telegramChatId) { const t = build(String(sc.telegramEvents || 'payouts')); if (t) await telegramSend(sc.telegramChatId, t, sc.telegramTopicId); }
|
|
if (sc.telegramEchoChatId) { const t = build(String(sc.telegramEchoEvents || 'payouts')); if (t) await telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>LinkSpin</b> \u00b7 ' + t, sc.telegramEchoTopicId); }
|
|
}
|
|
// holding-tank arrivals -> one digest line in the shared payments topic (Marty, 2026-09-12): who is
|
|
// waiting for a sponsor, by username, so builders go adopt them. Runs every 15 min, posts only
|
|
// when someone new landed since the last check.
|
|
async function tankNotifyTick() {
|
|
const sc = siteConfig();
|
|
if (!sc.telegramBotToken || !sc.telegramEchoChatId) return;
|
|
const f = path.join(DATA_DIR, 'tank-notify.json');
|
|
let st = { last: 0 }; try { st = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {}
|
|
const since = st.last || (Date.now() - 24 * 3600 * 1000);
|
|
// sign-up grace (2026-11-07): announced when they can be adopted, 24 hours after sign-up, not when they arrive. graceFrom =
|
|
// the first run of this rule: anyone who joined before it was already announced at sign-up.
|
|
const graceFrom = st.graceFrom || (st.graceFrom = st.last || Date.now());
|
|
const fresh = [];
|
|
for (const w of tank.openedSince(await tank.waiting(), since)) if ((w.joined || 0) > graceFrom && await marks.claim('tankopen:' + w.email + ':' + (w.joined || 0))) fresh.push(w);
|
|
st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st));
|
|
if (!fresh.length) return;
|
|
const named = fresh.filter(w => w.username).map(w => '@' + w.username);
|
|
const who = named.length ? ': ' + named.slice(0, 8).join(', ') + (named.length > 8 ? ' and ' + (named.length - 8) + ' more' : '') : '';
|
|
const text = '\u{1FAA3} <b>LinkSpin</b> \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who
|
|
+ '\nAdopt from Team \u203a Waiting on a wallet: <a href="' + SITE_URL + '/team">' + SITE_HOST + '/team</a>';
|
|
await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId);
|
|
}
|
|
// ---- holding tank: network alignment, activation hold, 24-hour safety net (2026-10-27, ported from InstantAdPay) ----
|
|
const nrm = v => String(v || '').trim().toLowerCase();
|
|
// InstantAdPay's own facts for a few people (signed /api/partner/sponsor-facts, the same call the Sponsor check uses),
|
|
// cached 10 minutes, misses included; unreachable = 2 minutes without asking again. Map email -> row | null (no account
|
|
// there); an email missing from the map = unknown (never asked successfully).
|
|
const iapFactsCache = new Map(); let iapFactsDownUntil = 0;
|
|
async function iapFacts(emails, opts) {
|
|
const now = Date.now(); const want = [...new Set((emails || []).map(nrm).filter(Boolean))];
|
|
const miss = opts && opts.fresh ? want : want.filter(e => { const c = iapFactsCache.get(e); return !c || now - c.at > 10 * 60000; });
|
|
if (miss.length && now >= iapFactsDownUntil && String(process.env.LS_SYNC_SECRET || '').trim().length >= 32) {
|
|
try {
|
|
const got = new Map();
|
|
for (let i = 0; i < miss.length; i += 2000) {
|
|
const r = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-facts', { emails: miss.slice(i, i + 2000) }, (opts && opts.timeout) || 3000);
|
|
for (const x of (r && r.rows) || []) got.set(nrm(x.email), x);
|
|
}
|
|
if (iapFactsCache.size > 20000) iapFactsCache.clear();
|
|
for (const e of miss) iapFactsCache.set(e, { at: now, row: got.get(e) || null });
|
|
} catch (e) { iapFactsDownUntil = now + 2 * 60000; console.log('tank: InstantAdPay sponsor-facts unreachable:', e.message); }
|
|
}
|
|
const out = new Map(); for (const e of want) { const c = iapFactsCache.get(e); if (c) out.set(e, c.row); }
|
|
return out;
|
|
}
|
|
// the network sponsor for a LinkSpin tank member: the registry rows InstantAdPay sent (same email, else same wallet),
|
|
// else InstantAdPay asked directly. Read only; tank.alignToNetwork decides whether it may be used.
|
|
async function networkSponsor(email, address) {
|
|
const e = nrm(email); if (!e) return null;
|
|
const r = await registry.get(e);
|
|
if (r && r.sponsorEmail && nrm(r.sponsorEmail) !== e) return { sponsorEmail: nrm(r.sponsorEmail), via: 'same email' };
|
|
const row = (await iapFacts([e])).get(e);
|
|
if (row && row.sponsorEmail && nrm(row.sponsorEmail) !== e) return { sponsorEmail: nrm(row.sponsorEmail), via: 'InstantAdPay sponsor' };
|
|
const w = nrm(address);
|
|
if (/^0x[0-9a-f]{40}$/.test(w)) for (const x of await registry.all()) if (nrm(x.wallet) === w && x.sponsorEmail && nrm(x.email) !== e && nrm(x.sponsorEmail) !== e) return { sponsorEmail: nrm(x.sponsorEmail), via: 'same wallet' };
|
|
return null;
|
|
}
|
|
// the double-assign guard: is this person waiting in InstantAdPay's OWN tank (a real account there, no sponsor, not a
|
|
// member there, wallet linked there)? Then InstantAdPay's 24-hour safety net assigns them and the adoption follows here;
|
|
// LinkSpin's does not. InstantAdPay unreachable: the registry decides (first seen on InstantAdPay and no sponsor = theirs).
|
|
async function iapOwnsTank(email, opts) {
|
|
const e = nrm(email); const m = await iapFacts([e], { fresh: !!(opts && opts.fresh), timeout: 5000 });
|
|
if (m.has(e)) {
|
|
const r = m.get(e); if (!r) return false;
|
|
const shell = r.joinedVia === 'linkspin' && !r.lastSeen && !(Number(r.memberId) > 0); // a waiting copy of a LinkSpin account: never in its tank
|
|
return !shell && !r.sponsorRef && !(Number(r.memberId) > 0) && !!r.wallet;
|
|
}
|
|
const reg = await registry.get(e);
|
|
return !!(reg && reg.firstProperty === 'instantadpay' && !reg.sponsorEmail);
|
|
}
|
|
// a held member got a sponsor (adopted, the 24-hour rotation, aligned, followed from InstantAdPay): the engine switches
|
|
// their payouts on now under THAT sponsor (carry.activateAssigned: strict, never the fallback; Marty approved 2026-10-27)
|
|
async function tankLifted(email) {
|
|
if (followStore.pendingFor(email)) return { error: 'a sponsor follow is still settling', retry: true }; // afterResolve / the next tick
|
|
const r = await carry.activateAssigned(email);
|
|
if (r && r.id && r.tx) console.log('tank lift: payouts on for', email, 'member #' + r.id, 'under #' + r.sponsorId, r.tx);
|
|
else if (r && r.error) console.log('tank lift: not yet for', email, '(' + r.error + ')');
|
|
return r;
|
|
}
|
|
// a holding-tank pickup: the live feed + one line in the shared payments topic (manual adoptions since 2026-09-12;
|
|
// the 24-hour safety net says "(auto-assigned)", 2026-10-27)
|
|
function tankPickupPost(adopterName, adopteeName, auto) {
|
|
pushFeed({ type: 'Adopted', sponsor: adopterName, member: adopteeName, ts: Date.now() });
|
|
try {
|
|
const sc = siteConfig();
|
|
const clean = t => String(t || '').replace(/[<>&]/g, '');
|
|
if (sc.telegramBotToken && sc.telegramEchoChatId)
|
|
telegramSend(sc.telegramEchoChatId, '\u{1F91D} <b>LinkSpin</b> \u00b7 <b>' + clean(adopterName) + '</b> picked up <b>' + clean(adopteeName) + '</b> from the holding tank and is now their sponsor' + (auto ? ' (auto-assigned)' : ''), sc.telegramEchoTopicId).catch(() => {});
|
|
} catch (e) {}
|
|
}
|
|
// admin-only channel (never a member-visible topic: it names an email)
|
|
async function tankAdminAlert(text) {
|
|
const sc = siteConfig(); const html = String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
if (sc.telegramBotToken && sc.telegramAdminChatId) return telegramSend(sc.telegramAdminChatId, html);
|
|
if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'LinkSpin: holding tank needs an adopter', text);
|
|
console.log('tank: no admin channel configured, alert not sent:', text);
|
|
}
|
|
// every 15 min: align members the network already knows, start the 24-hour clock for anyone who linked a wallet, run the
|
|
// safety net, and tell the shared payments topic once per member who became ready (members InstantAdPay holds in its own
|
|
// tank are announced by InstantAdPay, not twice)
|
|
async function tankReadyTick() {
|
|
const r = await tank.readyTick();
|
|
if (r.aligned || r.assigned.length || r.held || r.deferred || r.fresh.length) console.log('tank ready tick', JSON.stringify({ fresh: r.fresh.length, aligned: r.aligned, assigned: r.assigned.length, held: r.held, deferred: r.deferred }));
|
|
const sc = siteConfig();
|
|
if (!r.fresh.length || !sc.telegramBotToken || !sc.telegramEchoChatId) return r;
|
|
const clean = t => String(t || '').replace(/[<>&]/g, '');
|
|
const link = SITE_URL + '/tools#line';
|
|
if (r.fresh.length <= 3) {
|
|
for (const w of r.fresh) await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} <b>LinkSpin</b> \u00b7 ' + (w.username ? '@' + clean(w.username) : 'A new member') + ' linked a wallet and is ready to switch on payouts. Adopt them from the holding tank in the next ' + tank.leftText(w.until - Date.now()) + ': ' + link, sc.telegramEchoTopicId).catch(() => {});
|
|
} else { // first run after deploy (the members already linked) or a busy quarter hour: one digest, not a wall of posts
|
|
const named = r.fresh.filter(w => w.username).map(w => '@' + clean(w.username));
|
|
await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} <b>LinkSpin</b> \u00b7 ' + r.fresh.length + ' members linked a wallet and are ready to switch on payouts' + (named.length ? ': ' + named.slice(0, 12).join(', ') + (named.length > 12 ? ' and ' + (named.length - 12) + ' more' : '') : '') + '. Adopt them from the holding tank in the next ' + tank.leftText(Math.min(...r.fresh.map(w => w.until)) - Date.now()) + ': ' + link, sc.telegramEchoTopicId).catch(() => {});
|
|
}
|
|
return r;
|
|
}
|
|
// one sendMessage call; never throws, never logs the token
|
|
async function telegramSend(chatId, text, threadId) {
|
|
const sc = siteConfig();
|
|
if (!sc.telegramBotToken || !chatId) return;
|
|
const body = JSON.stringify(Object.assign({ chat_id: chatId, text, parse_mode: 'HTML', disable_web_page_preview: true }, threadId ? { message_thread_id: Number(threadId) } : {}));
|
|
await new Promise((resolve) => {
|
|
const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendMessage', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 10000 }, r => { r.resume(); r.on('end', resolve); });
|
|
rq.on('error', () => resolve()); rq.on('timeout', () => { rq.destroy(); resolve(); }); rq.end(body);
|
|
});
|
|
}
|
|
|
|
// photo post (multipart) for the achievement badges (Marty, 2026-09-13); same bot, sendPhoto only
|
|
async function telegramSendPhoto(chatId, jpeg, caption, threadId) {
|
|
const sc = siteConfig();
|
|
if (!sc.telegramBotToken || !chatId || !jpeg) return false;
|
|
const B = '----iapbadge' + crypto.randomBytes(8).toString('hex');
|
|
const field = (n, v) => Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="' + n + '"\r\n\r\n' + v + '\r\n');
|
|
const parts = [field('chat_id', String(chatId)), field('caption', caption), field('parse_mode', 'HTML')];
|
|
if (threadId) parts.push(field('message_thread_id', String(Number(threadId))));
|
|
parts.push(Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="photo"; filename="badge.jpg"\r\nContent-Type: image/jpeg\r\n\r\n'), jpeg, Buffer.from('\r\n--' + B + '--\r\n'));
|
|
const body = Buffer.concat(parts);
|
|
return new Promise((resolve) => {
|
|
const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendPhoto', method: 'POST', headers: { 'Content-Type': 'multipart/form-data; boundary=' + B, 'Content-Length': body.length }, timeout: 20000 }, res => {
|
|
let out = ''; res.on('data', c => out += c); res.on('end', () => resolve(res.statusCode === 200));
|
|
});
|
|
rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body);
|
|
});
|
|
}
|
|
const BADGE_META = { founder: ['Founder', 'signed in before LinkSpin launched'], payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'] };
|
|
const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json');
|
|
// every badge a member holds: the chain milestones plus the stored Founder flag (2026-11-05)
|
|
async function badgesHeld(email) { const out = []; try { out.push(...await ads.milestonesOf(email)); } catch (e) {} try { const a = await accounts.byEmail(email); if (a && a.founder) out.push('founder'); } catch (e) {} return out; }
|
|
function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } }
|
|
|
|
// ---- live feed (SSE) ----
|
|
const feedClients = new Set();
|
|
function pushFeed(ev) {
|
|
const line = 'data: ' + JSON.stringify(ev) + '\n\n';
|
|
for (const res of feedClients) { try { res.write(line); } catch (e) { feedClients.delete(res); } }
|
|
}
|
|
|
|
// ---- short link domains (LinkSpin): each domain in siteConfig().linkDomains is a small real site ----
|
|
function reqHost(req) { return String(req.headers['x-forwarded-host'] || req.headers.host || '').split(',')[0].trim().toLowerCase().replace(/:\d+$/, '').replace(/^www\./, ''); }
|
|
function pagesHost() { return String(siteConfig().pagesDomain || '').trim().toLowerCase().replace(/^www\./, '') || null; }
|
|
function isPagesHost(req) { const h = pagesHost(); return !!h && reqHost(req) === h; }
|
|
function isLinkHost(req) { const h = reqHost(req); if (!h) return false; return String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean).includes(h); }
|
|
function linkSitePage(host, page) {
|
|
const esc = t => String(t).replace(/&/g, '&').replace(/</g, '<');
|
|
const H = esc(host || 'this site'); const brand = 'LinkSpin'; const year = new Date().getFullYear();
|
|
const nav = '<nav><a href="/">Home</a><a href="/disclosure">Disclosure</a><a href="/terms">Terms</a><a href="/privacy">Privacy</a><a href="/abuse">Report a link</a></nav>';
|
|
const bodies = {
|
|
home: '<h1>' + H + '</h1><p>This domain is a link forwarding service operated by ' + brand + ', a member advertising network. Links on this domain forward visitors in one step to pages published by our members and their partners.</p><p>We do not host the pages you land on, and we do not collect payment information here. If a link forwarded you somewhere you did not expect, or to content that looks unsafe, tell us on the <a href="/abuse">report page</a> and we will pull the link.</p><h2>What we record</h2><p>When a link is followed we record the day, the country, the referring site, the device type and a one-day anonymous visitor token. We do not store your IP address or any personal data. Details are in the <a href="/privacy">privacy policy</a>.</p>',
|
|
disclosure: '<h1>Affiliate and advertising disclosure</h1><p>Links forwarded through ' + H + ' may be affiliate links or paid advertisements. The member who published a link may earn a commission or advertising credit if you buy something or sign up on the page you land on. This never changes the price you pay.</p><p>' + brand + ' itself is an advertising platform. Members buy ad packages and earn commissions when people they referred buy ad packages. No income is guaranteed to anyone; results depend on effort, and any earnings examples on member pages are illustrations, not promises.</p><p>The pages you are forwarded to belong to their publishers. We are not responsible for their claims, and we remove links that are reported and found to violate our <a href="/terms">terms</a>.</p>',
|
|
terms: '<h1>Terms of use</h1><p>By following a link on ' + H + ' you agree to these terms.</p><h2>The service</h2><p>' + H + ' forwards visitors to destinations chosen by ' + brand + ' members. We provide the forwarding only. We do not endorse, verify or control the destination pages, and we are not a party to any transaction you make there.</p><h2>Acceptable use</h2><p>Members may not forward visitors to content that is illegal, deceptive, malicious, adult, or that impersonates another business. Links that violate this are removed and the member\'s account is closed. Automated access to this domain is not permitted except by search engines.</p><h2>No warranty</h2><p>The service is provided as is. We do not guarantee that any link will be available, and we are not liable for the content, availability or conduct of destination sites.</p><h2>Contact</h2><p>Questions about these terms: <a href="https://linkspin.co">linkspin.co</a>.</p>',
|
|
privacy: '<h1>Privacy policy</h1><p>This policy covers ' + H + ' and the link forwarding service on it.</p><h2>What we collect</h2><p>When you follow a link we record the date, your country (derived from your network address and then discarded), the site that referred you, whether you are on a phone or a computer, and an anonymous visitor token that changes every day and cannot be traced back to you. We do not store your IP address, your name, your email address or any account information on this domain.</p><h2>Click ids</h2><p>If the member who owns the link tracks goals, or you arrived from an ad, the page you are forwarded to gets a random click id in its address (<code>lsclk</code>). The site you land on may keep it for 30 days to count whether the visit led to a sign-up or a sale. It identifies the click, not you.</p><h2>Cookies</h2><p>This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.</p><h2>Why we collect it</h2><p>So members can see how many people followed their links and from where. Counts are shown to the member who published the link, in aggregate, and to nobody else.</p><h2>Retention</h2><p>Link statistics are kept for up to thirteen months and then deleted.</p><h2>Your rights</h2><p>Because we hold no personal data on this domain there is nothing to access or delete here. For anything involving a ' + brand + ' member account, contact us through <a href="https://linkspin.co">linkspin.co</a>.</p>',
|
|
abuse: '<h1>Report a link</h1><p>If a link on ' + H + ' forwarded you to a page that is deceptive, unsafe, adult, or impersonates a business, tell us. We review every report and pull the link first, then ask questions.</p><p>Send the full link you clicked (it starts with https://' + H + '/r/ or https://' + H + '/c/) and what you saw, or the address of a banner image you want reviewed, to the support contact on <a href="https://linkspin.co">linkspin.co</a>. Reports are usually handled the same day.</p>',
|
|
gone: '<h1>That link is not active</h1><p>The link you followed has been removed or has expired. Nothing was recorded. If you were expecting a specific page, ask the person who shared the link for a fresh one.</p>'
|
|
};
|
|
return '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + H + '</title><meta name="robots" content="noindex,follow"><style>body{margin:0;font:16px/1.6 system-ui,Segoe UI,Roboto,sans-serif;color:#1b1f1e;background:#fbfbf9}main{max-width:680px;margin:0 auto;padding:40px 22px 60px}nav{display:flex;gap:16px;flex-wrap:wrap;font-size:14px;margin-bottom:28px}nav a{color:#0f766e;text-decoration:none}h1{font-size:26px;margin:0 0 12px}h2{font-size:17px;margin:22px 0 6px}p{margin:0 0 12px}footer{margin-top:40px;font-size:13px;color:#6b7370;border-top:1px solid #e3e3dd;padding-top:12px}</style></head><body><main>' + nav + (bodies[page] || bodies.gone) + '<footer>© ' + year + ' ' + brand + ' link service. <a href="/disclosure">Disclosure</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a></footer></main></body></html>';
|
|
}
|
|
|
|
// ---- server ----
|
|
// ---- the curtain ----------------------------------------------------------
|
|
// Work in progress is not for passers-by. CURTAIN=<secret> puts a contentless holding page
|
|
// in front of every request; ?k=<secret> sets a cookie that lifts it for that browser.
|
|
const CURTAIN = String(process.env.CURTAIN || '').trim();
|
|
const CURTAIN_PAGE = `<!doctype html><html lang="en"><head><meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow">
|
|
<title>Coming soon</title><style>
|
|
*{margin:0;padding:0;box-sizing:border-box}
|
|
html,body{height:100%}
|
|
body{display:flex;align-items:center;justify-content:center;padding:24px;
|
|
background:#0d1117;color:#e6edf3;font:16px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
.card{max-width:420px;text-align:center}
|
|
h1{font-size:clamp(28px,7vw,44px);font-weight:700;letter-spacing:-.5px;margin-bottom:14px}
|
|
p{color:#8b949e}
|
|
</style></head><body><div class="card"><h1>Coming soon</h1><p>This site is still being built.</p></div></body></html>`;
|
|
|
|
function curtained(req, res, u) {
|
|
if (!CURTAIN) return false;
|
|
if (isLinkHost(req) || isPagesHost(req)) return false; // the short link domains and the pages domain stay public: spin links must redirect and the mini-site must answer while the main site is covered (Marty 2026-10-07: test traffic before launch)
|
|
if (u.searchParams.get('k') === CURTAIN) {
|
|
u.searchParams.delete('k');
|
|
res.writeHead(302, {
|
|
'Set-Cookie': 'ls.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax; Secure',
|
|
Location: u.pathname + (u.searchParams.toString() ? '?' + u.searchParams : ''),
|
|
'Cache-Control': 'no-store'
|
|
});
|
|
res.end();
|
|
return true;
|
|
}
|
|
const pass = /(?:^|;\s*)ls\.pass=([^;]*)/.exec(req.headers.cookie || '');
|
|
if (pass && decodeURIComponent(pass[1]) === CURTAIN) return false;
|
|
res.writeHead(503, {
|
|
'Content-Type': 'text/html; charset=utf-8',
|
|
'Cache-Control': 'no-store',
|
|
'X-Robots-Tag': 'noindex, nofollow'
|
|
});
|
|
res.end(req.method === 'HEAD' ? '' : CURTAIN_PAGE);
|
|
return true;
|
|
}
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
{ const t0 = Date.now(); res.on('finish', () => { const ms = Date.now() - t0; if (ms > 3000) console.warn('slow request', req.method, String(req.url || '').split('?')[0].slice(0, 80), ms + 'ms', res.statusCode); }); } // visibility for member-felt delays (2026-10-12)
|
|
try {
|
|
const u = new URL(req.url, 'http://x');
|
|
const p = u.pathname;
|
|
// zone endpoints run on other people's sites and show only ad creatives, so they pass the curtain
|
|
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p === '/t.js' || p === '/t.gif' || p === '/cv.gif' || p === '/cv.js' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18)
|
|
// support must reach everyone, invited or not (2026-10-16): someone locked out or not yet let in is exactly who needs it
|
|
if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
|
|
|
|
// -- the rotator redirect: one hop, recorded, on any host (LinkSpin)
|
|
let rm = /^\/r\/([a-z0-9]{4,12})$/i.exec(p);
|
|
if (rm && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
const hit = await rotator.resolve(rm[1], req);
|
|
if (hit && hit.lsid) await markOwnClick(hit.lsid, hit.rotation && hit.rotation.owner, req);
|
|
if (hit && hit.url) { res.writeHead(302, { Location: hit.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); }
|
|
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone'));
|
|
}
|
|
// -- Banner Spin (2026-10-18): /i/<code>.gif the image (a fresh pick on every load, never cached), /c/<code> the click,
|
|
// /s/<code>.js the script embed (banner + its own click link). Any host, any origin, like /r/.
|
|
{ const bm = /^\/(i|c|s)\/([a-z0-9]{5,12})(\.gif|\.js)?$/.exec(p);
|
|
if (bm && (req.method === 'GET' || req.method === 'HEAD') && ((bm[1] === 'i' && bm[3] === '.gif') || (bm[1] === 'c' && !bm[3]) || (bm[1] === 's' && bm[3] === '.js'))) {
|
|
const fresh = { 'Cache-Control': 'no-store, no-cache, must-revalidate, private, max-age=0', Pragma: 'no-cache', Expires: '0', ETag: '"' + crypto.randomBytes(8).toString('hex') + '"', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff', 'X-Robots-Tag': 'noindex' };
|
|
const host = reqHost(req) || SITE_HOST;
|
|
if (bm[1] === 'i') {
|
|
const xq = u.searchParams.get('x'); const im = await bannerspin.image(bm[2], req, xq != null && /^\d{1,4}$/.test(xq) ? Number(xq) : null);
|
|
if (!im) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end(); }
|
|
if (im.url) { res.writeHead(302, Object.assign({}, fresh, { Location: im.url, 'Referrer-Policy': 'no-referrer' })); return res.end(); }
|
|
let body = null, type = 'image/png';
|
|
if (im.local) { const f = bannerspin.readImage(im.local); if (f) { body = f.buf; type = f.mime; } }
|
|
if (!body) body = bannerspin.blankPng(im.size[0], im.size[1]);
|
|
res.writeHead(200, Object.assign({}, fresh, { 'Content-Type': type, 'Content-Length': String(body.length), 'Content-Disposition': 'inline' })); return res.end(req.method === 'HEAD' ? '' : body);
|
|
}
|
|
if (bm[1] === 's') {
|
|
const js = await bannerspin.script(bm[2], req, (IS_PROD ? 'https' : 'http') + '://' + (req.headers.host || host));
|
|
if (!js) { res.writeHead(404, { 'Content-Type': 'application/javascript' }); return res.end('/* not found */'); }
|
|
res.writeHead(200, Object.assign({}, fresh, { 'Content-Type': 'application/javascript; charset=utf-8' })); return res.end(req.method === 'HEAD' ? '' : js);
|
|
}
|
|
const ck = await bannerspin.click(bm[2], req, host);
|
|
if (ck && ck.lsid) await markOwnClick(ck.lsid, ck.owner, req);
|
|
if (ck && ck.url) { res.writeHead(302, { Location: ck.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade', 'X-Robots-Tag': 'noindex' }); return res.end(); }
|
|
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(host, 'gone'));
|
|
} }
|
|
// -- ad zones on members' sites: the tag, the ad, the viewable beacon, the click. Any origin may call these.
|
|
if (p === '/z.js') { const zf = path.join(PUBLIC_DIR, 'z.js'); try { const body = fs.readFileSync(zf); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); return res.end(body); } catch (e) {} }
|
|
if (p === '/api/zone/serve' && req.method === 'GET') {
|
|
const am = audiences.matcher(req); // ls.vid cookie (when the browser sends it cross-site) + soft key
|
|
const ad = await zones.serve(u.searchParams.get('z'), req, Object.assign(viewerGeo(req), am));
|
|
const h = Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, corsCreds(req));
|
|
if (!am.vid) h['Set-Cookie'] = audiences.cookieHeader(audiences.newVid(), IS_PROD);
|
|
res.writeHead(200, h); return res.end(JSON.stringify({ ad }));
|
|
}
|
|
// -- conversion pixel (2026-10-23): /t.js the landing tag, /t.gif its beacon, /cv.gif + /cv.js the goal pixel. Any origin,
|
|
// never cached, always a 1x1 gif (the member's page never sees an error). X-LS-Result says what happened (tests, debugging).
|
|
if ((p === '/t.js' || p === '/cv.js') && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
try { let body = fs.readFileSync(path.join(PUBLIC_DIR, p.slice(1))); if (p === '/t.js') body = String(body).replace(/\/\*ls-net\*\/.*?\/\*ls-net\*\//, JSON.stringify(networkHosts())); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff' }); return res.end(req.method === 'HEAD' ? '' : body); } catch (e) { res.writeHead(404); return res.end(); }
|
|
}
|
|
if ((p === '/t.gif' || p === '/cv.gif') && req.method === 'GET') {
|
|
const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length), 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'X-LS-Result', 'X-Robots-Tag': 'noindex' };
|
|
const px = String(u.searchParams.get('px') || '');
|
|
try {
|
|
if (p === '/t.gif') {
|
|
const id = convtrack.isPx(px) ? convtrack.landing(px, String(u.searchParams.get('c') || ''), req) : null;
|
|
if (id) h['Set-Cookie'] = clickCookie(id); h['X-LS-Result'] = id ? 'stored' : 'ignored';
|
|
} else if (convtrack.isPx(px)) {
|
|
const r = convtrack.record({ px, goal: u.searchParams.get('goal'), value: u.searchParams.get('value'), c: String(u.searchParams.get('c') || u.searchParams.get('lsclk') || u.searchParams.get('lsid') || u.searchParams.get('clickid') || refClickId(req) || ''), m: u.searchParams.get('m'), test: u.searchParams.get('test') === '1' }, req, parseCookies(req));
|
|
h['X-LS-Result'] = r.result + (r.method ? ';' + r.method : '') + (r.conv && r.conv.self ? ';self' : ''); // ;self = the owner's own click, kept as a test
|
|
if (r.result === 'counted' && !r.conv.self) postbacks.fire(r.conv.owner, r.conv.goal, Object.assign(convtrack.postbackCtx(r), { goal: true })).catch(e => console.error('goal postback', e.message));
|
|
} else h['X-LS-Result'] = 'unknown';
|
|
} catch (e) { console.error('conversion pixel', e.message); h['X-LS-Result'] = 'error'; }
|
|
res.writeHead(200, h); return res.end(PIXEL_GIF);
|
|
}
|
|
// audience pixel: 1x1 gif, sets/refreshes the visitor cookie, records the hit (30-day membership)
|
|
if (p === '/p.gif' && req.method === 'GET') {
|
|
const a = String(u.searchParams.get('a') || ''); const vid = audiences.cookieVid(req); const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length) };
|
|
// no cookie came in: offer one, but count this hit under the soft key only (2026-10-22). A browser that blocks the
|
|
// cookie would otherwise add a fresh 30-day visitor on every hit and inflate the audience size.
|
|
if (!vid) h['Set-Cookie'] = audiences.cookieHeader(audiences.newVid(), IS_PROD);
|
|
if (audiences.isId(a)) audiences.hit(a, vid, audiences.softKey(req), audiences.cleanEvent(u.searchParams.get('e')));
|
|
res.writeHead(200, h); return res.end(PIXEL_GIF);
|
|
}
|
|
if (p === '/p.js') { try { const body = fs.readFileSync(path.join(PUBLIC_DIR, 'p.js')); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(body); } catch (e) { res.writeHead(404); return res.end(); } }
|
|
if (p === '/z/nas' && req.method === 'GET') { // the frame a Network Ad Space fallback renders in
|
|
const html = zones.nasFrame(String(u.searchParams.get('s') || ''));
|
|
if (!html) { res.writeHead(404); return res.end(); }
|
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src https://www.networkadspace.com https://networkadspace.com 'unsafe-inline'; img-src https: http: data:; style-src 'unsafe-inline'; frame-src https: http:; frame-ancestors *; base-uri 'none'", 'Referrer-Policy': 'no-referrer' }); return res.end(html);
|
|
}
|
|
if (p === '/api/zone/seen' && (req.method === 'GET' || req.method === 'POST')) { await zones.seen(u.searchParams.get('i'), req); res.writeHead(204, corsCreds(req)); return res.end(); }
|
|
{ const zm = /^\/api\/zone\/click\/([a-f0-9]{12})$/.exec(p); if (zm && req.method === 'GET') { let ck = null; const target = await zones.click(zm[1], async (camp, url) => { const t = await adClickTarget(camp, url, req, { placement: 'zone' }); ck = t.cookie; return t.url; }); const zh = { Location: target || '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }; if (ck) zh['Set-Cookie'] = ck; res.writeHead(302, zh); return res.end(); } }
|
|
// -- publisher program (2026-10-10): the public offer for site owners who carry zones, and its live "Network right now"
|
|
// strip (7-day totals from zones.js, cached a minute). App host only; the link and pages domains stay single-purpose.
|
|
// Today's POL price in US dollars for the member pages (Marty, 2026-10-22, same as InstantAdPay): the contract's own package
|
|
// rate (Chainlink POL/USD), cached 5 minutes here, so browsers never call an outside price service.
|
|
if (p === '/api/public/polusd' && req.method === 'GET') {
|
|
if (!(polUsdC.at && Date.now() - polUsdC.at < 300000 && polUsdC.v > 0)) { try { const cat = await chain.catalog(); const pk = (cat.products || cat).find(x => x.costWei); const v = pk ? (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18) : 0; if (v > 0) { polUsdC.v = v; polUsdC.at = Date.now(); } } catch (e) {} }
|
|
return json(res, 200, { usd: polUsdC.v || 0, at: polUsdC.at || Date.now() }, { 'Cache-Control': 'public, max-age=60' });
|
|
}
|
|
if (p === '/api/public/publishers' && req.method === 'GET') return json(res, 200, zones.publisherPublic(), { 'Cache-Control': 'public, max-age=60' });
|
|
if (p === '/publishers' && (req.method === 'GET' || req.method === 'HEAD') && !isPagesHost(req) && !isLinkHost(req)) return sendFile(res, path.join(PUBLIC_DIR, 'publishers.html'));
|
|
{ const wm = /^\/welcome\/([a-f0-9]{48})$/.exec(p); if (wm && (req.method === 'GET' || req.method === 'POST')) { // one-time tester sign-in link
|
|
const t = inviteTokens.get(wm[1]);
|
|
if (!t || t.exp < Date.now()) { inviteTokens.delete(wm[1]); res.writeHead(410, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('<!doctype html><meta charset="utf-8"><title>Link used</title><p style="font:15px system-ui;padding:24px">That sign-in link was already used or has expired. Ask for a fresh one.</p>'); }
|
|
// GET only shows a button: link-preview fetchers and in-app browsers prefetch links, and a prefetch must not spend the token
|
|
if (req.method === 'GET') {
|
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' });
|
|
return res.end('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in to LinkSpin</title></head><body style="margin:0;min-height:100vh;display:grid;place-items:center;background:#0B1424;font-family:Manrope,\'Segoe UI\',system-ui,sans-serif;color:#EEF3FA"><form method="post" style="background:#101D33;border:1px solid #1E2E4A;border-radius:12px;padding:28px 26px;width:min(420px,92vw);text-align:center"><div style="width:34px;height:34px;border-radius:50%;border:3px solid #1F6FEB;border-right-color:transparent;margin:0 auto 14px"></div><div style="font:700 11px monospace;letter-spacing:.14em;color:#8CA2C4">LINKSPIN TEST APP</div><h1 style="font:700 24px/1.2 \'Segoe UI\',system-ui;margin:8px 0 6px">Sign in as</h1><div style="font:500 14px monospace;color:#8CC8FF;margin-bottom:20px">' + String(t.email).replace(/&/g, '&').replace(/</g, '<') + '</div><button type="submit" style="font:700 15px \'Segoe UI\',system-ui;letter-spacing:.06em;text-transform:uppercase;background:linear-gradient(180deg,#FF7A32,#FF6A1A);color:#fff;border:1px solid #D9530A;border-radius:8px;padding:12px 22px;cursor:pointer;width:100%">Sign me in</button><p style="font-size:12px;color:#8CA2C4;margin:14px 0 0">One use. Good for 24 hours from when it was made.</p></form></body></html>');
|
|
}
|
|
inviteTokens.delete(wm[1]);
|
|
const acct = await accounts.byEmail(t.email); let memberId = 0; if (acct && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} }
|
|
const token = await auth.mintSession({ email: t.email, address: (acct && acct.address) || null, memberId });
|
|
res.writeHead(302, { 'Set-Cookie': auth.sessionCookie(token), Location: t.next || '/ads', 'Cache-Control': 'no-store' }); return res.end();
|
|
} }
|
|
// -- member pages: /p/<slug> on the app host and on every link domain; the lead form and the hit beacon live beside it
|
|
// -- the pages domain: only pages live here. / -> the app; /<slug> and /p/<slug> -> the page; everything else 404
|
|
if (isPagesHost(req)) {
|
|
if (p === '/') { res.writeHead(302, { Location: 'https://' + SITE_HOST + '/', 'Cache-Control': 'no-store' }); return res.end(); }
|
|
if (p === '/robots.txt') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nAllow: /\n'); }
|
|
if (p === '/assets/pt.js') return sendFile(res, path.join(PUBLIC_DIR, 'assets', 'pt.js'));
|
|
// page-builder media on the pages host (2026-10-30, Neville's lookfirst.page link): builder pages reference the niche
|
|
// library and member uploads by relative path, so both are served here with the main host's strict patterns and nothing else
|
|
let pim = /^\/niches\/([a-z0-9-]{1,80}\.(?:jpg|jpeg|png|webp|gif))$/.exec(p);
|
|
if (pim && (req.method === 'GET' || req.method === 'HEAD')) return sendFile(res, path.join(PUBLIC_DIR, 'niches', pim[1]));
|
|
pim = /^\/uploads\/([a-z0-9]{24}\.(?:png|jpg|webp|gif|mp4|webm))$/.exec(p);
|
|
if (pim && (req.method === 'GET' || req.method === 'HEAD')) return sendFile(res, path.join(UPLOADS_DIR, pim[1]));
|
|
if (!/^\/p\/[a-z0-9-]{3,60}(\/lead)?$/i.test(p) && !/^\/api\/p\//.test(p) && !/^\/[a-z0-9-]{3,60}$/i.test(p)) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
|
|
}
|
|
let pm = /^\/p\/([a-z0-9-]{3,60})$/i.exec(p) || (isPagesHost(req) ? /^\/([a-z0-9-]{3,60})$/i.exec(p) : null);
|
|
if (pm && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
const pg = pages.bySlug(pm[1]);
|
|
const preview = u.searchParams.get('preview') === '1';
|
|
if (!pg || (pg.status !== 'published' && !preview)) { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(isLinkHost(req) ? linkSitePage(reqHost(req), 'gone') : '<!doctype html><title>Not found</title><p style="font-family:system-ui;padding:40px">That page is not live.</p>'); }
|
|
if (preview) { if (!isAdmin(req)) { const sess = await auth.fromRequest(req); if (!sess || !sess.email || String(sess.email).toLowerCase() !== pg.owner) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } } } // the owner, or the admin (Member content); a preview is never counted
|
|
else pages.view(pg, req, 'view');
|
|
const lsid = String(u.searchParams.get('lsid') || '');
|
|
const hdr = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin',
|
|
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src 'self' https: data:; form-action https: http:; base-uri 'none'; frame-ancestors *; connect-src 'self'" };
|
|
if (/^[a-z0-9]{6,20}$/i.test(lsid)) hdr['Set-Cookie'] = 'ls.click=' + lsid + '; Path=/; SameSite=Lax; Max-Age=2592000' + (IS_PROD ? '; Secure' : '');
|
|
// the visitor's click id goes into the built-in form at render (2026-10-22): from ?lsid, else the ls.click cookie a
|
|
// spin-link visit left earlier, so a lead counts as the rotator's 'lead' conversion even when the script never runs
|
|
const formLsid = /^[a-z0-9]{6,20}$/i.test(lsid) ? lsid : (/^[a-z0-9]{6,20}$/i.test(String(parseCookies(req)['ls.click'] || '')) ? parseCookies(req)['ls.click'] : '');
|
|
res.writeHead(200, hdr); return res.end(pages.html(pg, { leadUrl: '/p/' + pg.slug + '/lead', lsid: formLsid, trackSrc: '/assets/pt.js?v=2', footerLink: 'https://' + SITE_HOST + '/', footerText: 'Made with LinkSpin', pixel: 'https://' + SITE_HOST + '/p.gif?a=' + audiences.defaultFor(pg.owner) + '&e=page' }));
|
|
}
|
|
pm = /^\/p\/([a-z0-9-]{3,60})\/lead$/i.exec(p);
|
|
if (pm && req.method === 'POST') {
|
|
const raw = await new Promise(r => { let d = ''; req.on('data', c => { d += c; if (d.length > 20000) req.destroy(); }); req.on('end', () => r(d)); });
|
|
const b = {}; try { const ct = String(req.headers['content-type'] || ''); if (/json/.test(ct)) Object.assign(b, JSON.parse(raw)); else for (const [k, v] of new URLSearchParams(raw)) b[k] = v; } catch (e) {}
|
|
if (!/^[a-z0-9]{6,20}$/i.test(String(b.lsid || ''))) { const lc = String(parseCookies(req)['ls.click'] || ''); if (/^[a-z0-9]{6,20}$/i.test(lc)) b.lsid = lc; } // form posted no click id: the cookie from the page visit
|
|
const r = await pages.lead(pm[1], b, req);
|
|
if (r.error) { res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('<!doctype html><title>Try again</title><p style="font-family:system-ui;padding:40px">' + r.error + ' <a href="javascript:history.back()">Go back</a></p>'); }
|
|
if (r.owner && r.lsid) { try { postbacks.bindClick(String(b.email || '').toLowerCase(), r.lsid); const hit = await rotator.convert(r.lsid, 'lead', {}); if (hit) postbacks.fire(hit.owner, 'lead', Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: r.lsid, code: hit.code, sourceId: hit.sourceId || '' })).catch(() => {}); } catch (e) {} }
|
|
res.writeHead(302, { Location: r.next || '/', 'Cache-Control': 'no-store' }); return res.end();
|
|
}
|
|
if (p.startsWith('/api/p/') && req.method === 'POST' && /\/hit$/.test(p)) { const sl = p.split('/')[3]; const pg = pages.bySlug(sl); if (pg) pages.view(pg, req, 'cta'); res.writeHead(204); return res.end(); }
|
|
if (p === '/assets/pt.js' && isLinkHost(req)) return sendFile(res, path.join(PUBLIC_DIR, 'assets', 'pt.js'));
|
|
// -- short link domains: a real small site (home, disclosure, terms, privacy, abuse) so the domain never looks parked
|
|
if (isLinkHost(req)) {
|
|
// page-builder media (2026-10-30, Neville: images showed in Preview on linkspin.app but not on the live lookfirst.page link):
|
|
// a builder page is served on the link domain with relative image paths, so the niche library and member uploads must be
|
|
// reachable here too; same strict patterns as the main host, nothing else from public/ or the volume
|
|
let im = /^\/niches\/([a-z0-9-]{1,80}\.(?:jpg|jpeg|png|webp|gif))$/.exec(p);
|
|
if (im && (req.method === 'GET' || req.method === 'HEAD')) return sendFile(res, path.join(PUBLIC_DIR, 'niches', im[1]));
|
|
im = /^\/uploads\/([a-z0-9]{24}\.(?:png|jpg|webp|gif|mp4|webm))$/.exec(p);
|
|
if (im && (req.method === 'GET' || req.method === 'HEAD')) return sendFile(res, path.join(UPLOADS_DIR, im[1]));
|
|
const page = { '/': 'home', '/disclosure': 'disclosure', '/terms': 'terms', '/privacy': 'privacy', '/abuse': 'abuse', '/robots.txt': 'robots' }[p];
|
|
if (!page) { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone')); }
|
|
if (page === 'robots') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nDisallow: /r/\nDisallow: /c/\nDisallow: /s/\n'); }
|
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(linkSitePage(reqHost(req), page));
|
|
}
|
|
|
|
// -- traffic log: public page views by referring domain (admin > Traffic)
|
|
if (req.method === 'GET' && (TRAFFIC_PAGES.has(p) || /^\/(join|from|wall|blog)\/[^/]+$/.test(p))) traffic.hit(p.startsWith('/blog/') ? '/blog/*' : p, req.headers.referer, req.headers['user-agent']);
|
|
// -- join links: /join/<memberId or share code> — LAST-touch cookie (Marty,
|
|
// 2026-09-10): the link a visitor opened most recently is the sponsor shown
|
|
// and used, and it locks the moment the account is created (accounts.ensure
|
|
// never changes an existing account's sponsor; the contract binds the buyer at
|
|
// their first purchase). Codes resolve LATE (at buy time) to whatever chain id
|
|
// the referrer has by then, so free members refer from day one.
|
|
let m = /^\/join\/([A-Za-z0-9_]{1,20})$/.exec(p);
|
|
if (m && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
// lead-capture page: email first, wallet later. ?v=<angle> picks the hook
|
|
// copy and is remembered so the account records which angle converted.
|
|
// partner placement: <host>/join/company (or /top) places the visitor directly under
|
|
// member #1, the company position, with no sponsor in between (Marty, 2026-09-12 partner kit)
|
|
const tok = JOIN_ALIASES[m[1].toLowerCase()] || m[1].toLowerCase();
|
|
const cookies = parseCookies(req);
|
|
const angle = String(u.searchParams.get('v') || '').toLowerCase();
|
|
const ang = JOIN_ANGLES[angle] || null;
|
|
if (req.method === 'GET') coach.recordView(tok, ang ? angle : '', req.headers.referer); // link stats per angle + source
|
|
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') || u.searchParams.get('lsclk') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution); lsclk is what the landing tag carries from a bridge page (2026-11-07)
|
|
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
|
|
return serveJoinPage(res, tok, ang ? angle : '', ang, set);
|
|
}
|
|
// -- legacy bridge: /from/faucetwave | /from/tieroneads [?seg=advertiser]. Same squeeze page
|
|
// with brand copy, NO sponsor (the sponsor cookie is cleared so they land in the holding
|
|
// tank for adoption), the angle remembered so the welcome-back grant fires at signup, and
|
|
// a forced first-touch source so link stats / admin can see the legacy arrivals.
|
|
// /from/btc4hits (2026-11-11): the closed BTC4Hits rotator site. Its members were imported as waiting accounts, so the
|
|
// page is mostly a sign-in; angle 'b4h' is outside the fw/t1 grant rule, so no welcome-back credits are ever granted.
|
|
m = /^\/from\/(faucetwave|tieroneads|btc4hits)$/.exec(p);
|
|
if (m && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
const brand = m[1];
|
|
const key = brand === 'btc4hits' ? 'b4h' : (brand === 'faucetwave' ? 'fw' : 't1') + (String(u.searchParams.get('seg') || '').toLowerCase().startsWith('adv') ? '-adv' : '-earn');
|
|
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`;
|
|
const src = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9.\-]/g, '').slice(0, 40); // e.g. the old domain's splash page
|
|
const set = ['iap.sponsor=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : ''), 'iap.angle=' + key + cookieTail, 'iap.ref=' + encodeURIComponent('legacy:' + brand + (src ? ':' + src : '')) + cookieTail];
|
|
return serveJoinPage(res, '', key, JOIN_ANGLES[key], set);
|
|
}
|
|
if (p === '/unsubscribe' && req.method === 'GET') {
|
|
const r = await drip.unsubscribe(u.searchParams.get('e'), u.searchParams.get('t'));
|
|
const msg = r.error ? r.error : 'Done. You will not get any more follow-up emails from LinkSpin. Your account is unchanged.';
|
|
res.writeHead(r.error ? 400 : 200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }));
|
|
return res.end('<!doctype html><html' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><title>LinkSpin</title>' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=ls20261101t"></head><body><div class="wrap" style="max-width:560px;padding:80px 22px"><a href="/"><img src="/logo.png" alt="LinkSpin" style="height:34px"></a><h1 style="font-size:30px;margin:26px 0 12px">' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '</h1><p>' + msg + '</p><p><a class="btn small sec" href="/links">Member area</a></p></div></body></html>');
|
|
}
|
|
|
|
// -- public API
|
|
if (p === '/api/config' && req.method === 'GET') {
|
|
const c = chain.getConfig();
|
|
// public copy of the site settings: never anything that looks like a credential
|
|
const pubSite = {};
|
|
for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k)) pubSite[k] = v;
|
|
return json(res, 200, Object.assign({ contract: c.contract, chainId: c.chainId,
|
|
chainName: c.chainName, explorer: c.explorer, rpc: c.rpcs[0],
|
|
emailAuth: (mailer.hasKey() || !IS_PROD) && SIGNUPS_OPEN,
|
|
signupsOpen: SIGNUPS_OPEN }, pubSite));
|
|
}
|
|
if (p === '/api/catalog' && req.method === 'GET') {
|
|
// five live quotes per call: serve a 20-second cache so pages that load the
|
|
// ladder (join, home, buy) are not waiting on the RPC every time
|
|
// stale-while-revalidate (2026-10-20, same as InstantAdPay): serve the cached ladder at once, refresh in the background
|
|
const age = catalogCache.at ? Date.now() - catalogCache.at : Infinity;
|
|
if (age > 20000 && !catalogCache.busy) catalogCache.busy = chain.catalog().then(pr => { catalogCache.products = pr; catalogCache.at = Date.now(); }).catch(e => console.error('catalog refresh', e.message)).finally(() => { catalogCache.busy = null; });
|
|
if (!catalogCache.products || age > 120000) { try { await catalogCache.busy; } catch (e) {} if (!catalogCache.products) throw new Error('catalog unavailable'); }
|
|
return json(res, 200, { products: catalogCache.products });
|
|
}
|
|
if (p === '/api/feed' && req.method === 'GET') {
|
|
return json(res, 200, { events: await attachNames(chain.recentEvents(Number(u.searchParams.get('n')) || 100)) });
|
|
}
|
|
if (p === '/api/feed/live' && req.method === 'GET') {
|
|
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' }));
|
|
res.write(': connected\n\n');
|
|
feedClients.add(res);
|
|
req.on('close', () => feedClients.delete(res));
|
|
return;
|
|
}
|
|
m = /^\/api\/tx\/(0x[0-9a-fA-F]{64})$/.exec(p);
|
|
if (m && req.method === 'GET') {
|
|
// tx relay so the browser never talks to the RPC directly (CSP stays 'self').
|
|
// Serves both the wallet's waitTx poll (found/status) and the built-in
|
|
// /tx/<hash> viewer (full details + decoded events).
|
|
try {
|
|
const r = await chain.rpc('eth_getTransactionReceipt', [m[1]]);
|
|
if (!r) return json(res, 200, { found: false });
|
|
const out = { found: true, status: r.status, blockNumber: r.blockNumber, gasUsed: r.gasUsed };
|
|
try {
|
|
const t = await chain.rpc('eth_getTransactionByHash', [m[1]]);
|
|
if (t) { out.from = t.from; out.to = t.to; out.valueWei = BigInt(t.value || '0x0').toString(); }
|
|
} catch (e) {}
|
|
try {
|
|
const blk = await chain.rpc('eth_getBlockByNumber', [r.blockNumber, false]);
|
|
if (blk) out.ts = blk.timestamp;
|
|
} catch (e) {}
|
|
try {
|
|
out.events = await attachNames((r.logs || []).map(chain.decodeLog).filter(Boolean)
|
|
.map(ev => Object.assign(ev, { tx: m[1] })));
|
|
} catch (e) { out.events = []; }
|
|
return json(res, 200, out);
|
|
} catch (e) { return json(res, 200, { found: false, rpcError: true }); }
|
|
}
|
|
if (p === '/api/sponsor' && req.method === 'GET') {
|
|
// The account's stored sponsor is authoritative — it persists across
|
|
// devices, cleared cookies, and return visits. Fall back to the first-touch
|
|
// cookie only for anonymous visitors with no account sponsor yet. (Reading
|
|
// the cookie alone was orphaning buyers to root when the cookie was absent.)
|
|
const s = await auth.fromRequest(req);
|
|
let acct = s && s.email ? await accounts.byEmail(s.email) : null;
|
|
let tok = (acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor'] || '';
|
|
let spd = await resolveSponsorDetailed(tok); let sponsorId = spd.id;
|
|
// LinkSpin carry-over: a sponsor with a wallet is activated on this contract by the engine before the
|
|
// member's first transaction. A purchase is NEVER held (Marty, 2026-10-15): no wallet / unknown sponsor
|
|
// walks up to the nearest ancestor with a wallet, else the company. intent=buy commits the move + notices.
|
|
const intentBuy = u.searchParams.get('intent') === 'buy';
|
|
const intentActivate = u.searchParams.get('intent') === 'activate'; // the free Switch on payouts button (2026-10-27)
|
|
// holding tank (2026-10-27): no sponsor, no member number, no resolvable cookie -> the network sponsor first (every
|
|
// intent, buys included). Nobody known: a plain activation is held for an adopter; a purchase goes ahead under the
|
|
// fallback as before (Marty: "I would never want to hold up a purchase ... they'll just pay number one").
|
|
let tankHold = null;
|
|
if (acct && !acct.sponsorRef && !(Number(acct.memberId) > 0) && !sponsorId) {
|
|
try {
|
|
const h = await tank.holdFor(acct, { noLift: intentBuy || intentActivate });
|
|
if (h && h.aligned) { acct = (await accounts.byEmail(acct.email)) || acct; tok = acct.sponsorRef || tok; spd = await resolveSponsorDetailed(tok); sponsorId = spd.id; }
|
|
else if (h && h.hold) tankHold = h.hold;
|
|
} catch (e) { console.error('tank hold', e.message); }
|
|
}
|
|
let sponsorRouted = null;
|
|
if (acct && !sponsorId) {
|
|
try {
|
|
const cr = await carry.resolveForChain(acct, spd, { commit: intentBuy });
|
|
if (cr && cr.sponsorId) { sponsorId = cr.sponsorId; spd.reason = 'ok'; }
|
|
if (cr && cr.routed) { sponsorRouted = cr.routed; spd.reason = 'ok'; }
|
|
} catch (e) {}
|
|
}
|
|
let sponsorBlocked = null; // only a momentary chain lookup failure: the client says "try again in a minute", nothing is charged
|
|
if (acct && acct.sponsorRef && !sponsorId && spd.reason === 'rpc') sponsorBlocked = 'rpc';
|
|
if (tankHold && intentActivate && !sponsorId) sponsorBlocked = 'tankHold'; // the free activation only, never a purchase
|
|
if (sponsorRouted && intentBuy) sponsorBlockedAlert(acct.email, Object.assign({ tok, routedTo: sponsorRouted.to }, spd));
|
|
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; }
|
|
// orphan fallback: an unresolvable/absent sponsor (dead link, no link) lands
|
|
// the new member under the configured catch position (#1) instead of root
|
|
if (!sponsorId && sponsorBlocked !== 'tankHold' && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1;
|
|
// a brand-new contract has no catch position yet: the first member joins with sponsor 0 and BECOMES #1 (Marty's reverted
|
|
// activate(1) on 2026-10-08: 'Unknown sponsor' because memberCount was 0)
|
|
if (sponsorId) { try { if (sponsorId > await chain.memberCount()) { console.log('sponsor', sponsorId, 'not on chain yet, using 0'); sponsorId = 0; } } catch (e) {} }
|
|
let name = null, avatarUrl = null, own = false;
|
|
// the join page names the owner of the LINK it was opened with (?ref=token), not the visitor's own
|
|
// sponsor: a member previewing their own invite page was seeing their upline's name (Jim, 2026-09-13)
|
|
let showTok = String(u.searchParams.get('ref') || '').trim().toLowerCase();
|
|
if (showTok && JOIN_ALIASES[showTok]) showTok = JOIN_ALIASES[showTok];
|
|
const nameTok = showTok || tok;
|
|
if (nameTok) {
|
|
const t = nameTok.toLowerCase();
|
|
let a = await accounts.byCode(t); if (!a) a = await accounts.byUsername(t);
|
|
if (!a && /^\d+$/.test(nameTok)) a = await accounts.byMemberId(Number(nameTok));
|
|
if (a) { name = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : null); avatarUrl = a.avatarUrl || null; own = !!(acct && a.email === acct.email); var bio = null, cobrand = false; try { cobrand = (await ads.milestonesOf(a.email)).includes('level3'); if (cobrand && await hasBought(a)) bio = a.bio ? String(a.bio).slice(0, 220) : null; } catch (e) {} }
|
|
}
|
|
return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, tankHold: intentBuy ? null : tankHold, sponsorName: spd.name || null, invited: !!(tok || showTok), name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand });
|
|
}
|
|
if (p === '/api/stats' && req.method === 'GET') {
|
|
let members = 0; try { members = await chain.memberCount(); } catch (e) {}
|
|
return json(res, 200, Object.assign({ onchainMembers: members, siteAccounts: await accounts.count(), servedToday: rotator.servedToday(), rotations: rotator.totals().rotations }, chain.totals()));
|
|
}
|
|
// -- home-page demo: a working spin link with no account (2026-10-07). One per browser (ls.demo cookie),
|
|
// five per IP per hour, 24 h unless the visitor signs in (the email door then claims it).
|
|
if (p === '/api/demo/spin' && req.method === 'POST') {
|
|
const ip = clientIp(req); const now = Date.now();
|
|
const dl = demoLimits.get(ip) || []; const recent = dl.filter(t => now - t < 3600000);
|
|
if (recent.length >= 5) return json(res, 429, { error: 'That is plenty of demo links for one hour. Sign in to make more.' });
|
|
const b = await readBody(req);
|
|
const urls = Array.isArray(b.urls) ? b.urls.map(x => String(x || '').trim()).filter(Boolean) : [];
|
|
let token = String(parseCookies(req)['ls.demo'] || '').replace(/[^a-f0-9]/g, '').slice(0, 32);
|
|
if (token.length < 16) token = crypto.randomBytes(12).toString('hex');
|
|
const r = await rotator.createDemo(token, urls);
|
|
if (r.error) return json(res, 400, r);
|
|
recent.push(now); demoLimits.set(ip, recent);
|
|
const hosts = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(x => x && !x.startsWith('www.'));
|
|
const host = hosts[0] || SITE_HOST;
|
|
return json(res, 200, { ok: true, code: r.rotation.code, url: 'https://' + host + '/r/' + r.rotation.code, destinations: r.rotation.destinations.length, expiresIn: 24 * 3600 },
|
|
{ 'Set-Cookie': 'ls.demo=' + token + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : '') });
|
|
}
|
|
|
|
// -- 24/7 assistant
|
|
if (p === '/api/chat' && req.method === 'POST') {
|
|
const ip = req.socket.remoteAddress || 'x';
|
|
if (chatLimited(ip)) return json(res, 429, { error: 'Give it a minute, then ask again.' });
|
|
const b = await readBody(req);
|
|
const r = await chatbot.answer(b.message, b.history);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/chat/kb-stamp' && req.method === 'GET') { // the newest knowledge-base edit by a person (Central day) and the entry count
|
|
return json(res, 200, await kb.stamp(), { 'Cache-Control': 'no-store' });
|
|
}
|
|
// -- the assistant's knowledge base, admin side (2026-10-20, kb.js): list, search, add, edit, delete, try a question
|
|
if (p === '/api/admin/kb' && (req.method === 'GET' || req.method === 'POST')) {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
if (req.method === 'GET') return json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }, { 'Cache-Control': 'no-store' });
|
|
const r = await kb.create(await readBody(req));
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/kb/test' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
return json(res, 200, await kb.test(b.question));
|
|
}
|
|
const kbm = /^\/api\/admin\/kb\/([a-z0-9-]{1,64})$/.exec(p);
|
|
if (kbm) {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
if (req.method === 'GET') { const e = await kb.get(kbm[1]); return e ? json(res, 200, { entry: e }) : json(res, 404, { error: 'Entry not found.' }); }
|
|
if (req.method === 'PUT') { const r = await kb.update(kbm[1], await readBody(req)); return json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); }
|
|
if (req.method === 'DELETE') { const r = await kb.remove(kbm[1]); return json(res, r.error ? 404 : 200, r); }
|
|
return json(res, 405, { error: 'method' });
|
|
}
|
|
|
|
// -- help desk (2026-10-16, helpdesk.js): the tickets live on InstantAdPay's one shared desk; these routes check the
|
|
// person (session or the support guard) and proxy. Public side first: the /support form, the private ticket link,
|
|
// the chat hand-off. All three pass the curtain (supportOpen above).
|
|
if (p === '/api/support' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
const s = await auth.fromRequest(req);
|
|
const acct = s && s.email ? await accounts.byEmail(s.email) : null; // signed in: the ticket is theirs, whatever was typed
|
|
const email = acct ? acct.email : String(b.email || '').trim().toLowerCase();
|
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'That email address does not look right.' });
|
|
if (!acct) { const iss = await newEmailIssue(email); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); } // replies must reach them
|
|
if (!acct) { const mo = await memberOnlyTicket(email); if (mo) return json(res, mo.status, mo.body); }
|
|
const guard = supportGuard(req, b, email);
|
|
if (guard) return json(res, guard.status, guard.body);
|
|
const r = await helpdesk.call('create', { source: 'public', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, subject: b.subject, category: b.category, body: b.body });
|
|
if (r.status !== 200) return json(res, r.status, r.data);
|
|
helpdesk.forget(email);
|
|
return json(res, 200, { ok: true, ref: r.data.ref, token: r.data.token, member: !!acct });
|
|
}
|
|
m = /^\/api\/support\/t\/([A-Za-z0-9_.-]{20,80})(\/reply)?$/.exec(p);
|
|
if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) {
|
|
if (req.method === 'GET') { const r = await helpdesk.call('token', { token: m[1] }); return json(res, r.status, r.data); }
|
|
const b = await readBody(req);
|
|
if (supportFlood('tk:' + m[1], 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' });
|
|
const r = await helpdesk.call('token-reply', { token: m[1], body: b.body });
|
|
return json(res, r.status, r.data);
|
|
}
|
|
if (p === '/api/support/chatbot' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
const s = await auth.fromRequest(req);
|
|
const acct = s && s.email ? await accounts.byEmail(s.email) : null;
|
|
const email = acct ? acct.email : String(b.email || '').trim().toLowerCase();
|
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'Add your email so Marty can reply.', needEmail: true });
|
|
if (acct) { if (supportFlood('em:' + email, 5, 3600000)) return json(res, 429, { error: 'You have sent several tickets in the last hour. Open Help in your Control Room to add to one.' }); }
|
|
else { const mo = await memberOnlyTicket(email); if (mo) return json(res, mo.status, mo.body); const guard = supportGuard(req, b, email); if (guard) return json(res, guard.status, guard.body); }
|
|
const tr = Array.isArray(b.transcript) ? b.transcript : [];
|
|
const turns = tr.slice(-8).map(x => ((x && x.who === 'me') ? 'Me: ' : 'Assistant: ') + String((x && x.text) || '').replace(/\s+/g, ' ').trim().slice(0, 600)).filter(x => x.length > 6);
|
|
const firstQ = tr.find(x => x && x.who === 'me' && String(x.text || '').trim());
|
|
const note = String(b.note || '').trim().slice(0, 2000);
|
|
const body = (note ? note + '\n\n' : '') + (turns.length ? 'From the chat assistant:\n' + turns.join('\n') : '(sent from the chat assistant)');
|
|
const r = await helpdesk.call('create', { source: 'chatbot', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, category: 'Other',
|
|
subject: 'Chat: ' + (firstQ ? String(firstQ.text).replace(/\s+/g, ' ').trim().slice(0, 100) : 'question for support'), body });
|
|
if (r.status !== 200) return json(res, r.status, r.data);
|
|
helpdesk.forget(email);
|
|
return json(res, 200, { ok: true, ref: r.data.ref, member: !!acct, link: acct ? '/help#t=' + r.data.ref : '/support/t/' + r.data.token });
|
|
}
|
|
// member side: the Help screen lists, opens and answers this member's LinkSpin tickets; the rail badge reads /unread
|
|
if (p === '/api/my/support/unread' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 200, { unread: 0 });
|
|
return json(res, 200, { unread: await helpdesk.unread(s.email) });
|
|
}
|
|
if (p === '/api/my/support' && (req.method === 'GET' || req.method === 'POST')) {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const email = String(s.email).toLowerCase();
|
|
if (req.method === 'GET') { const r = await helpdesk.call('list', { email }); return json(res, r.status, r.data); }
|
|
const b = await readBody(req);
|
|
if (supportFlood('em:' + email, 5, 3600000)) return json(res, 429, { error: 'You have opened several tickets in the last hour. Add to one of those instead.' });
|
|
const a = await accounts.byEmail(email);
|
|
const r = await helpdesk.call('create', { source: 'form', email, name: (a && a.username) || '', username: a && a.username, subject: b.subject, category: b.category, body: b.body });
|
|
if (r.status !== 200) return json(res, r.status, r.data);
|
|
return json(res, 200, { ok: true, ref: r.data.ref });
|
|
}
|
|
m = /^\/api\/my\/support\/(LS-\d{4,9})(\/reply)?$/.exec(p);
|
|
if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const email = String(s.email).toLowerCase();
|
|
helpdesk.forget(email); // opening or answering a ticket changes the badge
|
|
if (req.method === 'GET') { const r = await helpdesk.call('view', { ref: m[1], email }); return json(res, r.status, r.data); }
|
|
const b = await readBody(req);
|
|
if (supportFlood('tk:' + m[1], 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' });
|
|
const r = await helpdesk.call('reply', { ref: m[1], email, body: b.body });
|
|
return json(res, r.status, r.data);
|
|
}
|
|
|
|
// -- accounts: email + password is the normal join path (wallet comes
|
|
// out only at purchase / payout-activation time and gets linked then)
|
|
if (p === '/api/signup' && req.method === 'POST') {
|
|
if (!SIGNUPS_OPEN) return json(res, 403, SHUT);
|
|
const b = await readBody(req);
|
|
const ref = parseCookies(req)['iap.sponsor'] || ''; // last-touch attribution, locked at account creation
|
|
{ const iss = await newEmailIssue(String(b.email || '').trim().toLowerCase()); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); }
|
|
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
|
|
const token = await auth.mintSession({ email: r.account.email });
|
|
return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) });
|
|
}
|
|
if (p === '/api/login' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
const r = await accounts.login(b.email, b.password);
|
|
if (r.error) return json(res, 400, r);
|
|
let memberId = 0;
|
|
if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (e) {} }
|
|
const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId });
|
|
return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) });
|
|
}
|
|
|
|
// -- passwordless: email code sign-in (signup and login are the same act)
|
|
if (p === '/api/auth/email/start' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
const e = String(b.email || '').trim().toLowerCase();
|
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' });
|
|
// closed sign-ups shut the door to NEW accounts only; members already here (incl. imported shells) still get their code
|
|
const acct0 = await accounts.byEmail(e);
|
|
if (!SIGNUPS_OPEN && !acct0) return json(res, 403, SHUT);
|
|
if (!acct0) { const iss = await newEmailIssue(e); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); }
|
|
if (!isTester(e, acct0)) return json(res, 403, TESTING);
|
|
const prev = emailCodes.get(e);
|
|
if (prev && Date.now() < prev.nextAt) { console.log('signup-guard cooldown', clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }); }
|
|
const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited
|
|
if (guard) return json(res, guard.status, guard.body);
|
|
const code = String(Math.floor(100000 + Math.random() * 900000));
|
|
emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 });
|
|
if (mailer.hasKey()) {
|
|
try { await mailer.sendCode(e, code); } catch (err) {
|
|
console.error('sendCode failed', err.message);
|
|
return json(res, 502, { error: 'Could not send the email. Try again in a minute.' });
|
|
}
|
|
return json(res, 200, { ok: true, sent: true });
|
|
}
|
|
if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code });
|
|
return json(res, 503, { error: 'Email sign-in is not configured yet.' });
|
|
}
|
|
if (p === '/api/auth/email/verify' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
const e = String(b.email || '').trim().toLowerCase();
|
|
const rec = emailCodes.get(e);
|
|
if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' });
|
|
rec.tries += 1;
|
|
if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); }
|
|
if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' });
|
|
emailCodes.delete(e);
|
|
const ref = parseCookies(req)['iap.sponsor'] || '';
|
|
const via = parseCookies(req)['iap.angle'] || '';
|
|
const joinedRef = decodeURIComponent(parseCookies(req)['iap.ref'] || '') || null;
|
|
// the code door creates an account on first use, so it is a sign-up door too
|
|
if (!SIGNUPS_OPEN && !(await accounts.byEmail(e))) return json(res, 403, SHUT);
|
|
if (!isTester(e, await accounts.byEmail(e))) return json(res, 403, TESTING);
|
|
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(() => {}); } }
|
|
{ const dm = String(parseCookies(req)['ls.demo'] || '').replace(/[^a-f0-9]/g, ''); if (dm.length >= 16) rotator.claim('demo:' + dm, e).catch(() => {}); } // the home-page demo spin becomes theirs
|
|
// 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:
|
|
// adopt that wallet into the email account so member #, purchases and
|
|
// payouts stay attached, then retire the wallet-only session
|
|
const prior = await auth.fromRequest(req);
|
|
if (prior && prior.address && !prior.email) {
|
|
const lr = await accounts.linkWallet(e, prior.address);
|
|
if (lr.error) return json(res, 400, lr);
|
|
r.account = lr.account || await accounts.byEmail(e);
|
|
await auth.logout(req);
|
|
}
|
|
if (r.created) { sendWelcome(e, ref).catch(() => {}); } // sponsor notified at username set (/api/my/profile)
|
|
// partner promo code carried on the join link: redeem once per account (ignored if invalid/used)
|
|
try {
|
|
const pc = parseCookies(req)['iap.promo'];
|
|
if (pc) { const g = await promos.redeem(pc, e, 'link'); if (g.ok) { if (g.funder && g.funder !== e) { if (await ads.spendEarned(g.funder, g.credits)) { await ads.addEarned(e, g.credits); console.log('promo redeemed (member-funded)', g.code, g.credits, e, 'by', g.funder); } else console.log('promo funder short', g.code, g.funder); } else { await ads.addEarned(e, g.credits); console.log('promo redeemed', g.code, g.credits, e); } } }
|
|
} catch (err) { console.error('promo redeem', err.message); }
|
|
// legacy bridge: a listed former Faucet Wave / Tier One Ads member gets welcome-back credits once
|
|
if (r.created && /^(fw|t1)-(adv|earn)$/.test(via)) {
|
|
try { const g = legacy.grant(e, siteConfig()); if (g) { await ads.addEarned(e, g.credits); console.log('legacy grant', g.brand, g.seg, g.credits, e); } }
|
|
catch (err) { console.error('legacy grant', err.message); }
|
|
}
|
|
if (r.created && b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent, new joins only
|
|
let memberId = 0;
|
|
if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} }
|
|
const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId });
|
|
return json(res, 200, { ok: true, account: r.account, created: !!r.created }, { 'Set-Cookie': auth.sessionCookie(token) });
|
|
}
|
|
|
|
// -- wallet auth: link-to-account when an email session exists, or
|
|
// wallet-first sign-in (no UI door since 2026-09-09; a wallet-only session
|
|
// is walked to the email card, which adopts the wallet on verify)
|
|
if (p === '/api/auth/challenge' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
const r = auth.makeChallenge(b.address);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/position-attempt' && req.method === 'POST') { // browser-side steps of Add a position (support diagnostics)
|
|
const s = await auth.fromRequest(req).catch(() => null); const b = await readBody(req).catch(() => ({}));
|
|
const stage = String(b.stage || '').replace(/[^a-z0-9-]/gi, '').slice(0, 30); if (!stage) return json(res, 400, { error: 'stage' });
|
|
posLog({ email: s && s.email, stage: 'client-' + stage, detail: String(b.detail || '').slice(0, 300), ua: String(b.ua || '').slice(0, 160), wallet: !!b.wallet, mm: !!b.mm });
|
|
return json(res, 200, { ok: true });
|
|
}
|
|
if (p === '/api/admin/position-attempts' && (req.method === 'GET' || req.method === 'POST')) {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
let a = []; try { a = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'position-attempts.json'), 'utf8')); } catch (e) {}
|
|
const em = String(u.searchParams.get('email') || '').toLowerCase(); if (em) a = a.filter(x => x.email === em);
|
|
return json(res, 200, { attempts: a.slice(-200).reverse() });
|
|
}
|
|
if (p === '/api/auth/verify' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
const r = await auth.verifyChallenge(b.address, b.signature);
|
|
if (r.error) { if (b.asPosition) { const s0 = await auth.fromRequest(req).catch(() => null); posLog({ email: s0 && s0.email, stage: 'server-verify', detail: r.error, address: b.address }); } return json(res, 400, r); }
|
|
let memberId = 0;
|
|
try { memberId = await chain.memberIdByAccount(r.address); } catch (e) {}
|
|
const s = await auth.fromRequest(req);
|
|
if (b.asPosition && !(s && s.email)) posLog({ stage: 'server-no-session', detail: 'position sign-in without a signed-in account', address: r.address });
|
|
if (s && s.email && b.asPosition) {
|
|
const jsonP = (code, body) => { posLog({ email: s.email, stage: code === 200 ? 'server-added' : 'server-refused', detail: body.error || '', address: r.address, memberId }); return json(res, code, body); };
|
|
// Qualified Start: a second (third…) wallet on the same account. It becomes
|
|
// its own on-chain member under this member's id when it buys; the session
|
|
// stays on the main wallet.
|
|
// policy (Marty, 2026-09-10): positions exist to qualify, so at most five per account, and a
|
|
// wallet that is already registered on-chain under anything other than this account's main
|
|
// member is refused (a position-under-position chain would recapture 70% of a self-buy)
|
|
const MAX_POS = 5;
|
|
const have = await accounts.positions(s.email);
|
|
if (!have.find(p => p.address === r.address.toLowerCase()) && have.length >= MAX_POS)
|
|
return jsonP(400, { error: 'You can link up to ' + MAX_POS + ' positions, which is everything Qualified Start needs. Once qualified, buy from your main wallet so your sponsor is paid in full.' });
|
|
if (memberId) {
|
|
const mainId = await auth.refreshMemberId(s);
|
|
let mm = null; try { mm = await chain.member(memberId); } catch (e) {}
|
|
if (mm && mainId && mm.sponsorId !== mainId)
|
|
return jsonP(400, { error: 'That wallet is already registered on-chain under ' + (mm.sponsorId ? 'member #' + mm.sponsorId : 'no sponsor') + ', not under your main member #' + mainId + '. Only positions registered directly under you can be linked.' });
|
|
}
|
|
const pr = await accounts.addPosition(s.email, r.address);
|
|
if (pr.error) return jsonP(400, pr);
|
|
if (memberId) await accounts.setPositionMember(r.address, memberId);
|
|
return jsonP(200, { ok: true, position: true, address: r.address, memberId });
|
|
}
|
|
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 });
|
|
}
|
|
const acct = await accounts.byAddress(r.address);
|
|
if (!acct && await accounts.positionOwner(r.address))
|
|
return json(res, 400, { error: 'That wallet is a linked position on an account. Sign in with that account\'s email instead.' });
|
|
const token = await auth.mintSession({ email: acct ? acct.email : null, address: r.address, memberId });
|
|
return json(res, 200, { ok: true, address: r.address, memberId },
|
|
{ 'Set-Cookie': auth.sessionCookie(token) });
|
|
}
|
|
if (p === '/api/auth/logout' && req.method === 'POST') {
|
|
await auth.logout(req);
|
|
return json(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie() });
|
|
}
|
|
if (p === '/api/gas' && req.method === 'GET') {
|
|
try {
|
|
const fees = await chain.suggestedFees();
|
|
const from = u.searchParams.get('from'), to = u.searchParams.get('to'), data = u.searchParams.get('data'), value = u.searchParams.get('value');
|
|
if (/^0x[0-9a-fA-F]{40}$/.test(from || '') && /^0x[0-9a-fA-F]{40}$/.test(to || '') && /^0x[0-9a-fA-F]*$/.test(data || '')) { const call = { from, to, data: data || '0x' }; if (/^0x[0-9a-fA-F]+$/.test(value || '')) call.value = value; fees.gas = await chain.estimateGas(call); }
|
|
return json(res, 200, fees);
|
|
}
|
|
catch (e) { return json(res, 200, {}); }
|
|
}
|
|
|
|
if (p === '/api/me' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s) return json(res, 200, { signedIn: false });
|
|
const memberId = await auth.refreshMemberId(s);
|
|
let acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
|
|
// Who the member sees as their sponsor (2026-11-02, Orlando saw a stranger): a member who is on the chain shows the sponsor the
|
|
// contract bound, never the referral cookie from the last link they clicked; the cookie only speaks for accounts not on chain yet.
|
|
let spdMe = await sponsorByChain(acct && acct.memberId); if (!spdMe) spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || (!(acct && Number(acct.memberId) > 0) ? parseCookies(req)['iap.sponsor'] : '')); let sponsorId = spdMe.id;
|
|
// holding tank (2026-10-27): the network sponsor first; nobody known = tankHold (the Switch on payouts button waits
|
|
// for an adopter, 24 h at most). sponsorId keeps today's fallback so a purchase is never held.
|
|
let tankHold = null;
|
|
if (acct && !acct.sponsorRef && !(Number(acct.memberId) > 0) && !memberId && !sponsorId) {
|
|
try {
|
|
const h = await tank.holdFor(acct);
|
|
if (h && h.aligned) { acct = (await accounts.byEmail(acct.email)) || acct; spdMe = await resolveSponsorDetailed(acct.sponsorRef); sponsorId = spdMe.id; }
|
|
else if (h && h.hold) tankHold = h.hold;
|
|
} catch (e) { console.error('tank hold', e.message); }
|
|
}
|
|
const sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason === 'rpc') ? 'rpc' : null; // never hold: the buy/activate paths resolve through /api/sponsor?intent=buy (carry walk-up)
|
|
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0;
|
|
const _defSpon = Number(siteConfig().defaultSponsorId) || 1;
|
|
if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor)
|
|
if (sponsorId) { try { if (sponsorId > await chain.memberCount()) sponsorId = 0; } catch (e) {} } // fresh contract: no catch position exists yet, the first member becomes #1
|
|
if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {});
|
|
const out = { signedIn: true, sponsorBlocked, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
|
|
address: s.address || (acct && acct.address) || null, memberId,
|
|
username: (acct && acct.username) || null, theme: (acct && acct.theme) || null,
|
|
inviteAsk: !memberId && acct ? tank.inviteAsk(acct) : null, // the Who invited you card (2026-11-07)
|
|
refCode: (acct && acct.code) || null, sponsorId, tankHold,
|
|
// profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned)
|
|
avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null,
|
|
socials: (acct && acct.socials) || null,
|
|
wallOffers: parseWallOffers(acct),
|
|
lineBannerUrl: (acct && acct.lineBannerUrl) || null, lineTargetUrl: (acct && acct.lineTargetUrl) || null };
|
|
if (memberId) {
|
|
try {
|
|
const mm = await chain.member(memberId);
|
|
out.buyerCount = mm.buyerCount;
|
|
out.onchainSponsorId = mm.sponsorId;
|
|
const bal = await ads.balances((await myMemberIds(s)).ids, s.email);
|
|
out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available;
|
|
} catch (e) { out.chainReadError = true; }
|
|
}
|
|
return json(res, 200, out);
|
|
}
|
|
|
|
if (p === '/api/my/dashboard' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s) return json(res, 401, { error: 'Sign in first.' });
|
|
const memberId = await auth.refreshMemberId(s);
|
|
const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
|
|
if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {});
|
|
let tankWaiting = null; // top of every Overview: people waiting for a sponsor (Marty, 2026-09-12)
|
|
try {
|
|
if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() };
|
|
const tw = tank.adoptableOf(tankWaitCache.list); // only people who can be adopted right now (sign-up grace, 2026-11-07)
|
|
tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok, ready: tw.filter(w => w.ready).length };
|
|
} catch (e) {}
|
|
const sc0 = siteConfig();
|
|
const out = { memberId, tankWaiting, email: s.email || (acct && acct.email) || null,
|
|
pipeline: { live: pipeline.visible(sc0.pipelineMode, s.email || (acct && acct.email), ADMIN_EMAIL), mode: sc0.pipelineMode || 'off', eta: sc0.pipelineEta || '' },
|
|
address: s.address || (acct && acct.address) || null,
|
|
username: (acct && acct.username) || null,
|
|
refCode: (acct && acct.code) || null, lineBannerUrl: (acct && acct.lineBannerUrl) || null, /* the launch checklist mark reads it (was 7 of 8 with a banner set, 2026-09-14) */ credits: 0, buyerCount: 0,
|
|
earnedWei: '0', earnCount: 0, referrals: [], welcomeCredits: 0 };
|
|
if (out.email) {
|
|
// welcome credits unlock via the welcome tour when an upline with a
|
|
// line banner exists; members with no tour to walk get them instantly
|
|
const welcomed = await ads.welcomeGranted(out.email);
|
|
const tour = welcomed ? [] : (await uplineSlides(out.email)).filter(a => a.lineTargetUrl);
|
|
if (welcomed || !tour.length) { await ads.grantWelcome(out.email); out.welcomeCredits = ads.rates().welcomeCredits || 0; } // the welcome amount itself; the rest of the earned pool is viewing rewards, milestones and credits we add
|
|
else { out.welcomeCredits = 0; out.gauntletPending = true; }
|
|
}
|
|
if (out.email) out.inboxUnread = await ads.unreadCount(out.email); // delivers pending solos too
|
|
if (out.email) { // sponsor chat: presence heartbeat + unread + my availability + direct sponsor
|
|
accounts.touchSeen(out.email).catch(() => {});
|
|
out.chatUnread = await messages.chatUnread(out.email);
|
|
out.chatAvailable = (acct && acct.chatAvailable !== false);
|
|
const spon = await accounts.sponsorOf(out.email);
|
|
if (spon && spon.email) out.sponsor = {
|
|
email: spon.email,
|
|
name: spon.username ? '@' + spon.username : (spon.memberId ? 'member #' + spon.memberId : 'your sponsor'),
|
|
online: (Date.now() - (spon.lastSeen || 0)) < 60000,
|
|
available: spon.chatAvailable !== false };
|
|
}
|
|
if (out.email) { // unmissable login modal when the upline sent a message
|
|
const un = await messages.newestUnread(out.email);
|
|
if (un) {
|
|
const nm = un.fromMember ? await accounts.namesForMembers([un.fromMember]) : {};
|
|
out.sponsorMsg = { id: un.id, subject: un.subject, body: un.body,
|
|
fromName: (un.fromMember && nm[un.fromMember]) ? '@' + nm[un.fromMember] : (un.fromMember ? 'member #' + un.fromMember : 'your sponsor') };
|
|
}
|
|
}
|
|
if (memberId) {
|
|
try {
|
|
const mm = await chain.member(memberId);
|
|
out.buyerCount = mm.buyerCount;
|
|
const mine = await myMemberIds(s);
|
|
// linked positions are the member's own: their qualifying buyers count toward the account (Jim, 2026-09-14)
|
|
out.buyerCountMain = mm.buyerCount; out.buyerCountPositions = 0;
|
|
for (const id of mine.ids) if (id && id !== memberId) { try { out.buyerCountPositions += (await chain.member(id)).buyerCount || 0; } catch (e) {} }
|
|
out.buyerCountAll = out.buyerCountMain + out.buyerCountPositions; // badges count every position; levels the contract pays #main on depend on buyerCount alone
|
|
const bal = await ads.balances(mine.ids, s.email);
|
|
out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available;
|
|
} catch (e) { out.chainReadError = true; }
|
|
let earned = 0n, n = 0;
|
|
for (const ev of chain.recentEvents(600)) {
|
|
if ((ev.type === 'TierPaid' && ev.recipientId === memberId) || (ev.type === 'AwardPaid' && ev.toId === memberId)) {
|
|
earned += BigInt(ev.amountWei); n += 1;
|
|
}
|
|
}
|
|
out.earnedWei = earned.toString();
|
|
out.earnCount = n;
|
|
}
|
|
// achievement milestones (same ladder as the Overview stepper) + one-time credit
|
|
// bonuses — computed AFTER buyerCount is read from chain above (else always 0)
|
|
{
|
|
const bc = out.buyerCountAll != null ? out.buyerCountAll : (out.buyerCount || 0);
|
|
const reached = [];
|
|
if (out.memberId) reached.push('payouts');
|
|
if (bc >= 1) reached.push('firstBuyer');
|
|
if (bc >= 2) reached.push('level2');
|
|
if (bc >= 5) reached.push('level3');
|
|
try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned
|
|
out.milestonesReached = reached;
|
|
try { const fs0 = launchweek.founderState(acct || await accounts.byEmail(out.email)); out.founder = fs0.founder; out.founderPending = fs0.pending; } catch (e) {} // Founder badge: cosmetic, never in milestonesReached (no credits)
|
|
if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached);
|
|
}
|
|
// who joined through this member: their invite link uses username when set,
|
|
// else code, and the numeric id once on-chain — match all three
|
|
const refs = [];
|
|
if (acct && acct.code) refs.push(acct.code);
|
|
if (acct && acct.username) refs.push(acct.username);
|
|
if (memberId) refs.push(String(memberId));
|
|
const joined = await accounts.listByReferrer(refs);
|
|
out.referrals = joined.map(r => ({
|
|
name: r.username || r.email.replace(/^(.).*(@.*)$/, '$1***$2'), // username, else privacy mask
|
|
joined: r.created,
|
|
status: r.address ? 'wallet linked' : 'joined free'
|
|
}));
|
|
out.isAdmin = !!(ADMIN_EMAIL && out.email && String(out.email).toLowerCase() === ADMIN_EMAIL); // shows the Admin link
|
|
out.wallUnlocked = wallUnlockedFor(out.buyerCount || 0); // how many wall positions are the member's own
|
|
return json(res, 200, out);
|
|
}
|
|
// -- linked positions (Qualified Start): list, refresh from chain, unlink
|
|
if (p === '/api/my/positions' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const acct = await accounts.byEmail(s.email);
|
|
const mainId = await auth.refreshMemberId(s);
|
|
const list = await accounts.positions(s.email);
|
|
const out = [];
|
|
const posIds = [mainId, ...list.map(p => p.memberId)].filter(Boolean);
|
|
let balPer = {}, credited = 0; try { const bb = await ads.balances(posIds, s.email); credited = bb.credited; for (const p of bb.per) balPer[p.memberId] = p.avail; } catch (e) {}
|
|
// every position's chain reads run side by side (2026-10-20: one after another took 3-8 s, same fix as InstantAdPay)
|
|
out.push(...await Promise.all(list.map(async pos => {
|
|
let id = pos.memberId;
|
|
if (!id) { try { id = await chain.memberIdByAccount(pos.address); if (id) await accounts.setPositionMember(pos.address, id); } catch (e) {} }
|
|
const row = { address: pos.address, memberId: id || 0, buyerCount: 0, counted: false, credits: 0, created: pos.created };
|
|
if (id) {
|
|
const [mm, blocked] = await Promise.all([chain.member(id).catch(() => null), payoutChainBlocked(id, 3).catch(() => false)]);
|
|
if (mm) { row.buyerCount = mm.buyerCount; row.counted = mm.countedAsBuyer; row.sponsorId = mm.sponsorId; }
|
|
row.credits = balPer[id] != null ? balPer[id] : 0;
|
|
row.noPayout = blocked; // linkage only: a buy from here would pay a listed wallet
|
|
}
|
|
return row;
|
|
})));
|
|
const main = { address: (acct && acct.address) || null, memberId: mainId, credits: 0, buyerCount: 0 };
|
|
if (mainId) {
|
|
main.credits = balPer[mainId] != null ? balPer[mainId] : 0;
|
|
try { main.buyerCount = (await chain.member(mainId)).buyerCount; } catch (e) {}
|
|
main.noPayout = await payoutChainBlocked(mainId, 3);
|
|
}
|
|
// live POL balances (the link signature proved the wallet is theirs) + a POL/USD rate from the catalog
|
|
const bal = async a => { try { return BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { return null; } };
|
|
if (main.address) main.balanceWei = await bal(main.address);
|
|
for (const row of out) row.balanceWei = await bal(row.address);
|
|
let polUsd = 0; try { const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {}
|
|
return json(res, 200, { main, positions: out, polUsd, totalCredits: main.credits + out.reduce((n, r) => n + r.credits, 0), credited });
|
|
}
|
|
if (p === '/api/my/positions/remove' && 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 = await accounts.removePosition(s.email, b.address);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- coaching: every direct's ladder rung, stalled flag, and what to say
|
|
// -- holding tank: waiting members, my adoptions, adopt, release (pay it forward)
|
|
// -- promo code typed on the dashboard
|
|
if (p === '/api/my/promo/redeem' && 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 g = await promos.redeem(b.code, s.email, 'dashboard');
|
|
if (g.error) return json(res, 400, g);
|
|
await ads.addEarned(s.email, g.credits);
|
|
return json(res, 200, { ok: true, credits: g.credits, code: g.code, partner: g.partner });
|
|
}
|
|
// -- admin: member card. GET ?q= resolves email / @username / #id / share code / wallet;
|
|
// PATCH edits username, sponsor, main wallet or grants credits; DELETE removes a free account (2026-09-13)
|
|
if (p === '/api/admin/member' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const q = u.searchParams.get('q') || u.searchParams.get('email') || '';
|
|
const a = await adminMember.resolve(q);
|
|
if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' });
|
|
return json(res, 200, await adminMember.view(a.email));
|
|
}
|
|
// admin-made tracked links for a member (2026-11-03, Marty: a standalone copy of the games page needs LinkSpin tracking
|
|
// on every outbound link, built while he was away from his sign-in). POST { email, sourceId? | source?: { name, site },
|
|
// links: [{ name, url, label }] } -> one rotation per link on that member's account, one destination each, attached to the
|
|
// source when one is given or created. The same route serves partner placements later (one spin link per site).
|
|
if (p === '/api/admin/rotations' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req, 2e6); const a = await adminMember.resolve(String(b.email || ''));
|
|
if (!a) return json(res, 404, { error: 'No member matches that email.' });
|
|
const host = String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(h => h && !h.startsWith('www.'))[0] || SITE_HOST;
|
|
let sourceId = String(b.sourceId || '').trim();
|
|
if (!sourceId && b.source && b.source.name) { const s = await sources.create(a.email, { template: 'custom', name: String(b.source.name), site: String(b.source.site || '') }); if (s.error) return json(res, 400, { error: 'source: ' + s.error }); sourceId = s.source.id; }
|
|
const out = [];
|
|
for (const l of (Array.isArray(b.links) ? b.links : []).slice(0, 25)) {
|
|
const c = await rotator.create(a.email, { name: String(l.name || ''), fallback: String(l.url || '') }); if (c.error) { out.push({ name: l.name, error: c.error }); continue; }
|
|
// several destinations (2026-11-11, BTC4Hits rotators): l.urls = [{ url, label }] at equal weight, up to the rotator's own cap of 25
|
|
const list = Array.isArray(l.urls) && l.urls.length ? l.urls.map(x => typeof x === 'string' ? { url: x } : x) : [{ url: l.url, label: l.label }];
|
|
if (l.fallback) await rotator.update(a.email, c.rotation.id, { fallback: String(l.fallback) });
|
|
const maxDests = Math.max(25, Math.min(2000, Number(b.maxDests) || 25)); // the import may go past the member cap of 25 (BTC4Hits rotators)
|
|
let added = 0; const destErrors = []; for (const x of list) { const d = await rotator.addDest(a.email, c.rotation.id, { url: String(x.url || ''), label: String(x.label || ''), weight: 1 }, { max: maxDests, defer: true }); if (d.error) destErrors.push({ url: String(x.url || '').slice(0, 120), error: d.error }); else added++; }
|
|
await rotator.update(a.email, c.rotation.id, {}); // one save for the whole batch of destinations
|
|
if (!added) { await rotator.remove(a.email, c.rotation.id); out.push({ name: l.name, error: (destErrors[0] || {}).error || 'no destination' }); continue; }
|
|
if (sourceId) { const up = await rotator.update(a.email, c.rotation.id, { sourceId }); if (up && up.error) out.push({ name: l.name, warn: 'source not attached: ' + up.error }); }
|
|
out.push({ name: l.name, id: c.rotation.id, code: c.rotation.code, url: 'https://' + host + '/r/' + c.rotation.code, to: list[0].url, dests: added, destErrors });
|
|
}
|
|
return json(res, 200, { ok: true, email: a.email, sourceId: sourceId || null, links: out });
|
|
}
|
|
// a member's spin links + traffic sources (2026-11-11, BTC4Hits import: makes the admin route above idempotent), and removing one
|
|
if (p === '/api/admin/rotations' && (req.method === 'GET' || req.method === 'DELETE')) {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const a = await adminMember.resolve(String(u.searchParams.get('email') || ''));
|
|
if (!a) return json(res, 404, { error: 'No member matches that email.' });
|
|
if (req.method === 'DELETE') { const r = await rotator.remove(a.email, u.searchParams.get('id')); console.log('admin removed rotation', a.email, u.searchParams.get('id')); return json(res, r.error ? 404 : 200, r); }
|
|
const host = String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(h => h && !h.startsWith('www.'))[0] || SITE_HOST;
|
|
return json(res, 200, { email: a.email, linkBase: 'https://' + host + '/r/', rotations: await rotator.list(a.email), sources: (await sources.list(a.email)).sources }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/admin/member' && req.method === 'PATCH') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const e = String(b.email || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e);
|
|
if (!acct) return json(res, 404, { error: 'No such member.' });
|
|
if (b.username !== undefined) {
|
|
const un = String(b.username || '').trim().toLowerCase();
|
|
if (!/^[a-z0-9_]{3,20}$/.test(un)) return json(res, 400, { error: 'Username: 3 to 20 letters, numbers or underscore.' });
|
|
const r = await accounts.setUsername(e, un); if (r.error) return json(res, 400, r);
|
|
console.log('admin username', e, un);
|
|
}
|
|
if (b.sponsorRef !== undefined) { const r = await follow.setDeliberate(e, String(b.sponsorRef || '').trim(), 'admin', 'admin member card'); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); } // deliberate: follows to InstantAdPay until bound
|
|
if (b.address !== undefined) {
|
|
const a = String(b.address || '').trim().toLowerCase();
|
|
if (a && !/^0x[0-9a-f]{40}$/.test(a)) return json(res, 400, { error: 'That is not a wallet address.' });
|
|
const r = await accounts.adminSetAddress(e, a || null); if (r.error) return json(res, 400, r);
|
|
let mid = 0; if (a) { try { mid = Number(await chain.memberIdByAccount(a)) || 0; } catch (x) {} }
|
|
await accounts.setMemberId(e, mid);
|
|
if (db.enabled()) await db.q('UPDATE sessions SET address=?, member_id=? WHERE email=?', [a || null, mid || null, e]).catch(() => {});
|
|
console.log('admin wallet swap', e, a || '(none)', 'member', mid);
|
|
}
|
|
if (b.grantCredits !== undefined) {
|
|
const n = Math.round(Number(b.grantCredits));
|
|
if (!(n > 0) || n > 100000) return json(res, 400, { error: 'Credits: a whole number from 1 to 100,000.' });
|
|
await ads.addEarned(e, n);
|
|
console.log('admin credits', e, n, String(b.note || '').slice(0, 100));
|
|
}
|
|
return json(res, 200, await adminMember.view(e));
|
|
}
|
|
// -- link-farm scan (2026-10-30): last result + allowlist, run now (no Telegram), allow / unallow an email
|
|
if (p === '/api/admin/spamscan' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, spamscan.view()); }
|
|
if (p === '/api/admin/spamscan/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); await spamscan.run({ manual: true, quiet: true }); return json(res, 200, spamscan.view()); }
|
|
if (p === '/api/admin/spamscan/allow' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'Which email?' });
|
|
spamscan.setAllow(e, !b.remove); console.log('spamscan allowlist', b.remove ? 'removed' : 'added', e);
|
|
return json(res, 200, spamscan.view());
|
|
}
|
|
if (p === '/api/admin/member' && req.method === 'DELETE') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const e = String(u.searchParams.get('email') || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e);
|
|
if (!acct) return json(res, 404, { error: 'No such member.' });
|
|
if (acct.memberId) return json(res, 400, { error: 'Member #' + acct.memberId + ' is registered on-chain and cannot be deleted.' });
|
|
const pos = await accounts.positions(e); if (pos.some(x => x.memberId)) return json(res, 400, { error: 'This account owns a registered position and cannot be deleted.' });
|
|
const r = await accounts.removeAccount(e); if (r.error) return json(res, 400, r);
|
|
if (db.enabled()) await db.q('DELETE FROM sessions WHERE email=?', [e]).catch(() => {});
|
|
console.log('admin removed account', e);
|
|
return json(res, 200, { ok: true });
|
|
}
|
|
// -- release notes + roadmap (public read; admin write) (Marty, 2026-09-14)
|
|
if (p === '/api/releases' && req.method === 'GET') return json(res, 200, releases.publicView());
|
|
// -- promo toolkit: tiers by badge + the AI Copy Engine (Surge+), credits beyond the free allowance
|
|
if (p === '/api/my/toolkit' && 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, await toolkit.status(s.email));
|
|
}
|
|
if (p === '/api/my/toolkit/generate' && 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 = await toolkit.generate(s.email, String(b.kind || ''), String(b.brief || ''), String(b.angle || 'plain'));
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/toolkit/template' && req.method === 'POST') { // Spark: one-tap campaign aimed at the member's link
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const b = await readBody(req); const memberId = await auth.refreshMemberId(s);
|
|
const r = await toolkit.template(s.email, memberId, (await myMemberIds(s)).ids, String(b.kind || ''), Number(b.budget) || 0);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/toolkit/split' && req.method === 'GET') { // Circuit: per-angle views/joins/buyers for the member's link
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
return json(res, 200, await toolkit.split(s.email));
|
|
}
|
|
if (p === '/api/my/toolkit/videos' && req.method === 'GET') { // Circuit: Video Maker list
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
return json(res, 200, await toolkit.videos(s.email));
|
|
}
|
|
if (p === '/api/my/toolkit/video' && 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 = await toolkit.makeVideo(s.email, String(b.slug || ''));
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/toolkit/team' && req.method === 'GET') { // Nexus: Leader Ops
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
return json(res, 200, await toolkit.team(s.email));
|
|
}
|
|
if (p === '/api/my/toolkit/nudge' && 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 memberId = await auth.refreshMemberId(s);
|
|
const r = await toolkit.nudge(s.email, memberId, String(b.email || ''), String(b.text || ''));
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/toolkit/grant' && 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 = await toolkit.grant(s.email, String(b.email || ''), Number(b.credits) || 0);
|
|
if (r.ok) pushFeed({ type: 'Grant', from: r.fromName, to: r.toName, credits: r.credits, ts: Date.now() });
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/toolkit/promo' && 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 = await toolkit.partnerCode(s.email, String(b.code || ''), Number(b.credits) || 0);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/toolkit' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, await toolkit.adminUsage());
|
|
}
|
|
if (p === '/api/launch-week' && req.method === 'GET') { // public: launch moment + whether the contest panel is live (for /launch)
|
|
return json(res, 200, await launchweek.publicView());
|
|
}
|
|
if (p === '/api/leaderboard' && req.method === 'GET') { // public standings; signed-in members also get their own row
|
|
const s = await auth.fromRequest(req);
|
|
const period = ['week', 'month', 'all', 'lastweek', 'lastmonth'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week';
|
|
return json(res, 200, await leaderboard.view(period, s && s.email ? s.email : null));
|
|
}
|
|
if (p === '/api/admin/updates' && req.method === 'GET') { // member update emails: notes, audiences, log
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const since = updates.lastSentAt();
|
|
return json(res, 200, Object.assign({ notes: releases.notes().map(n => ({ id: n.id, title: n.title, date: n.date, fresh: !since || (n.created || 0) > since || (n.date && new Date(n.date + 'T12:00:00Z').getTime() > since) })), audiences: updates.AUDIENCES, counts: await updates.counts(), mailer: mailer.hasKey(), lastSentAt: since, draft: updates.draft() }, updates.status()));
|
|
}
|
|
if (p === '/api/admin/updates/draft' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { ok: true, draft: updates.saveDraft(await readBody(req)) });
|
|
}
|
|
if (p === '/api/admin/updates/preview' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
return json(res, 200, updates.compose({ subject: b.subject, intro: b.intro, closing: b.closing, noteIds: (b.noteIds || []).map(String) }, { email: ADMIN_EMAIL, username: 'you' }));
|
|
}
|
|
if (p === '/api/admin/updates/send' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const r = await updates.send({ subject: b.subject, intro: b.intro, closing: b.closing, noteIds: (b.noteIds || []).map(String), audience: b.audience, to: Array.isArray(b.to) ? b.to.slice(0, 5000) : null }, { test: !!b.test });
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/releases' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { notes: releases.notes(), roadmap: releases.roadmap(), tags: releases.TAGS, statuses: releases.STATUSES });
|
|
}
|
|
if (p === '/api/admin/releases' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const r = b.kind === 'roadmap' ? releases.saveRoadmap(b) : releases.saveNote(b);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/releases' && req.method === 'DELETE') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, releases.remove(u.searchParams.get('kind'), String(u.searchParams.get('id') || '')));
|
|
}
|
|
// -- admin: blog (list all incl. drafts, save/create, delete) (Marty, 2026-09-12)
|
|
if (p === '/api/admin/blog' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const slug = u.searchParams.get('slug');
|
|
if (slug) { const post = await blog.get(slug); return post ? json(res, 200, { post }) : json(res, 404, { error: 'No such post.' }); }
|
|
return json(res, 200, { syndication: syndicate.enabled(), posts: (await blog.listAll()).map(x => ({ slug: x.slug, title: x.title, status: x.status, tags: x.tags, publishedAt: x.publishedAt, updated: x.updated, views: x.views, excerpt: x.excerpt, cover: x.cover, syndicated: syndicate.statusOf(x.slug) })) });
|
|
}
|
|
if (p === '/api/admin/blog' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const before = b.existingSlug ? await blog.get(b.existingSlug) : null;
|
|
const r = await blog.save(b, b.existingSlug || null);
|
|
if (r.ok && r.post.status === 'published' && (!before || before.status !== 'published') && !b.noSyndicate) {
|
|
// first time this article goes live: push it to X + Instagram (never repeated for the same slug)
|
|
syndicate.publish(r.post).catch(e => console.error('syndication', e.message));
|
|
r.syndicating = syndicate.enabled();
|
|
}
|
|
r.syndicated = syndicate.statusOf(r.post.slug);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/blog/syndicate' && req.method === 'POST') { // manual: post (or retry) a published article
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const post = await blog.get(String(b.slug || ''));
|
|
if (!post) return json(res, 404, { error: 'No such post.' });
|
|
if (post.status !== 'published') return json(res, 400, { error: 'Publish the article first.' });
|
|
if (!syndicate.enabled()) return json(res, 400, { error: 'No Blotato key on the server.' });
|
|
const st = await syndicate.publish(post, { force: !!b.force });
|
|
return json(res, 200, { ok: true, syndicated: st });
|
|
}
|
|
if (p === '/api/admin/blog' && req.method === 'DELETE') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const slug = u.searchParams.get('slug'); if (!slug) return json(res, 400, { error: 'slug' });
|
|
return json(res, 200, await blog.remove(slug));
|
|
}
|
|
// -- admin: promo codes (create/update, switch on/off, redemptions)
|
|
if (p === '/api/admin/promos' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, await promos.adminView());
|
|
}
|
|
if (p === '/api/admin/promos' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const r = await promos.create(b);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/promos' && req.method === 'PATCH') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const r = await promos.setActive(b.code, !!b.active);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- username suggestion for the required first step (Marty, 2026-09-12): email prefix, cleaned, unique
|
|
if (p === '/api/my/username-suggest' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
let base = String(s.email).split('@')[0].toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 18);
|
|
if (!/[a-z]/.test(base)) base = 'member' + base;
|
|
if (base.length < 3) base = (base + 'xyz').slice(0, 3);
|
|
let pick = base;
|
|
for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i;
|
|
return json(res, 200, { suggest: pick });
|
|
}
|
|
// the menu item (2026-11-11): may this member adopt, how many can be adopted right now, the at-one-time cap. Cheap: the waiting
|
|
// list is the same 60-second cache the Overview notice uses; the full list stays on /api/my/tank.
|
|
if (p === '/api/my/tank/summary' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() };
|
|
const el = await tank.eligibility(s.email);
|
|
return json(res, 200, { adopter: !!(el.ok || el.full), eligible: !!el.ok, full: !!el.full, held: el.held != null ? el.held : null, cap: tank.capOpen(), waiting: tank.adoptableOf(tankWaitCache.list).length }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/my/tank' && 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, await tank.view(s.email));
|
|
}
|
|
// -- achievement badge -> Telegram (payments topic + the main group), once per badge per member.
|
|
// The browser composes the personalised image (canvas, same as Share) and posts it here.
|
|
if (p === '/api/my/badge-post' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const key = String(u.searchParams.get('key') || '');
|
|
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
|
|
if (key === 'founder') return json(res, 400, { error: 'The Founder badge is not posted to Telegram.' }); // launch week: no mass badge posts (Marty 2026-11-05)
|
|
if (!/^image\/jpeg/.test(String(req.headers['content-type'] || ''))) return json(res, 400, { error: 'Send the badge as a JPEG.' });
|
|
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
|
|
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
|
|
const held = await ads.milestonesOf(s.email);
|
|
if (!held.includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' });
|
|
const log = badgeLog(); const mine = log[s.email] || {};
|
|
if (mine[key]) return json(res, 200, { ok: true, already: true });
|
|
// manual re-posts (the button) are Marty's only; members' badges go out automatically on unlock
|
|
if (u.searchParams.get('manual') === '1' && s.email !== ADMIN_EMAIL) return json(res, 403, { error: 'Badges post automatically when they unlock.' });
|
|
const a = await accounts.byEmail(s.email);
|
|
const who = a && a.username ? '@' + a.username : (a && a.memberId ? 'member #' + a.memberId : 'a member');
|
|
const link = a && a.username ? SITE_HOST + '/join/' + a.username : SITE_HOST;
|
|
const [label, sub] = BADGE_META[key];
|
|
const caption = '\u{1F3C6} <b>LinkSpin</b> \u00b7 <b>' + who.replace(/[<>&]/g, '') + '</b> unlocked <b>' + label + '</b>: ' + sub + '\n' + link;
|
|
const sc = siteConfig(); let sent = 0;
|
|
if (sc.telegramBotToken && sc.telegramEchoChatId) {
|
|
if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; // payments topic
|
|
if (String(sc.telegramBadgeGeneral || '1') !== '0' && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; // the main group (General)
|
|
}
|
|
mine[key] = { ts: Date.now(), sent }; log[s.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {}
|
|
pushFeed({ type: 'Badge', member: who, label, ts: Date.now() });
|
|
console.log('badge posted', s.email, key, 'sent', sent);
|
|
return json(res, 200, { ok: true, sent });
|
|
}
|
|
// -- member's own share: store the composed badge so a public page can carry it as the preview image
|
|
if (p === '/api/my/badge-image' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const key = String(u.searchParams.get('key') || '');
|
|
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
|
|
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
|
|
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
|
|
if (!(await badgesHeld(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' });
|
|
const a = await accounts.byEmail(s.email);
|
|
if (!a || !a.username) return json(res, 400, { error: 'Pick a username first; the share page carries it.' });
|
|
fs.writeFileSync(path.join(UPLOADS_DIR, 'badge-' + a.username + '-' + key + '.jpg'), jpeg);
|
|
return json(res, 200, { ok: true, page: SITE_URL + '/b/' + a.username + '/' + key, image: SITE_URL + '/badge-img/' + a.username + '/' + key + '.jpg' });
|
|
}
|
|
if (p === '/api/my/badge-posted' && req.method === 'GET') { // which of my badges are already on Telegram
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
return json(res, 200, { posted: Object.keys(badgeLog()[s.email] || {}), canPost: s.email === ADMIN_EMAIL });
|
|
}
|
|
if (p === '/api/my/tank/adopt' && 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 = await tank.adopt(s.email, b.who, b.note);
|
|
if (r.ok) tankPickupPost(r.adopterName, r.adopteeName, false); // tell the payments topic who picked whom up (Marty, 2026-09-12)
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// "Who invited you?" (Marty approved 2026-11-07): the signed-in member names their own sponsor. check: validate only.
|
|
if (p === '/api/my/tank/invited' && 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 = await tank.nameSponsor(s.email, b.who, { check: !!b.check });
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/tank/invited/dismiss' && req.method === 'POST') { // "Nobody invited me": hides the card, nothing else changes
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
return json(res, 200, tank.dismissInvite(s.email));
|
|
}
|
|
if (p === '/api/my/tank/release' && 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 = await tank.release(s.email, b.email);
|
|
if (r.ok) { // the feed shows releases too, so a pickup-and-drop is visible for what it is (Marty, 2026-09-13)
|
|
pushFeed({ type: 'Released', sponsor: r.ownerName, member: r.memberName, ts: Date.now() });
|
|
try {
|
|
const sc = siteConfig();
|
|
const clean = t => String(t || '').replace(/[<>&]/g, '');
|
|
if (sc.telegramBotToken && sc.telegramEchoChatId)
|
|
telegramSend(sc.telegramEchoChatId, '\u{1FAA3} <b>LinkSpin</b> \u00b7 <b>' + clean(r.ownerName) + '</b> returned <b>' + clean(r.memberName) + '</b> to the holding tank', sc.telegramEchoTopicId);
|
|
} catch (e) {}
|
|
}
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/tank/contacted' && req.method === 'POST') { // sponsor reached the lead off-site: reset the rescue clock
|
|
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 = await tank.markContacted(s.email, b.email);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/gift' && req.method === 'POST') { // PIF: log a wallet-to-wallet POL gift and tell the recipient
|
|
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 = await tank.recordGift(s.email, b.email, b.tx, b.pol);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/tank/grant' && req.method === 'POST') { // admin: assign N real BTC4Hits imports to an adopter on top of the cap (Marty 2026-11-11)
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req); const a = await adminMember.resolve(String(b.adopter || '')); if (!a) return json(res, 404, { error: 'No member matches that adopter.' });
|
|
tankWaitCache = null; return json(res, 200, await tank.grant(a.email, b.count));
|
|
}
|
|
if (p === '/api/admin/tank' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, await tank.adminView());
|
|
}
|
|
// -- admin Traffic tab: page views + join-page views + signups + $25 buyers, by referring
|
|
// domain / first-touch source, by landing page, by angle and by day (Marty, 2026-09-12)
|
|
if (p === '/api/admin/traffic' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const days = Math.min(365, Math.max(1, Number(u.searchParams.get('days')) || 30));
|
|
const since = Date.now() - days * 86400000, sinceDay = new Date(since).toISOString().slice(0, 10);
|
|
const hosts = {}, paths = {}, daily = {}, angles = {};
|
|
const H = k => (hosts[k] = hosts[k] || { source: k, hits: 0, joinViews: 0, signups: 0, registered: 0, buyers: 0 });
|
|
const Dy = k => (daily[k] = daily[k] || { day: k, hits: 0, signups: 0 });
|
|
for (const r of await traffic.rows(sinceDay)) { H(r.host).hits += r.n; paths[r.path] = (paths[r.path] || 0) + r.n; Dy(r.day).hits += r.n; }
|
|
for (const v of await coach.viewsSince(since)) { H(v.ref || 'direct').joinViews += 1; const a = angles[v.angle || 'plain'] = angles[v.angle || 'plain'] || { angle: v.angle || 'plain', views: 0, signups: 0 }; a.views += 1; }
|
|
const buyerIds = new Set(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'BuyerCounted' && ev.newBuyerId) buyerIds.add(ev.newBuyerId);
|
|
for (const a of await accounts.listAll(5000)) {
|
|
if (!a.created || a.created < since) continue;
|
|
const h = H(a.joinedRef || 'direct'); h.signups += 1; if (a.memberId) h.registered += 1; if (a.memberId && buyerIds.has(a.memberId)) h.buyers += 1;
|
|
Dy(new Date(a.created).toISOString().slice(0, 10)).signups += 1;
|
|
const k = a.joinedVia || 'plain'; angles[k] = angles[k] || { angle: k, views: 0, signups: 0 }; angles[k].signups += 1;
|
|
}
|
|
const sources = Object.values(hosts).sort((x, y) => (y.hits + y.joinViews + y.signups * 10) - (x.hits + x.joinViews + x.signups * 10));
|
|
return json(res, 200, { days, sources, paths: Object.entries(paths).map(([path, hits]) => ({ path, hits })).sort((x, y) => y.hits - x.hits),
|
|
angles: Object.values(angles).sort((x, y) => y.views - x.views), daily: Object.values(daily).sort((x, y) => x.day < y.day ? -1 : 1),
|
|
totals: { hits: sources.reduce((n, s) => n + s.hits, 0), joinViews: sources.reduce((n, s) => n + s.joinViews, 0), signups: sources.reduce((n, s) => n + s.signups, 0), buyers: sources.reduce((n, s) => n + s.buyers, 0) } });
|
|
}
|
|
if (p === '/api/my/coach' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const cv = await coach.coachView(s.email);
|
|
for (const d of cv.directs) if (d.free) { try { d.rescue = await tank.rescueInfo(s.email, await accounts.byEmail(d.email)); } catch (e) {} } // dormant-lead clock
|
|
return json(res, 200, cv);
|
|
}
|
|
// -- link stats: views, joins and buyers per angle link
|
|
if (p === '/api/my/linkstats' && 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, await coach.linkStats(s.email));
|
|
}
|
|
// -- prospects: the member's own follow-up list
|
|
// -- Pipeline: the follow-up board (stages from the ledger and the site; notes, follow-ups, tags from the sponsor)
|
|
if (p === '/api/my/pipeline' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const sc = siteConfig();
|
|
if (!pipeline.visible(sc.pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 200, { live: false, eta: sc.pipelineEta || '' });
|
|
const b = await pipeline.board(s.email);
|
|
return json(res, 200, Object.assign({ live: true }, b), { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/my/pipeline/note' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
if (!pipeline.visible(siteConfig().pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 403, { error: 'The Pipeline is not open yet.' });
|
|
const r = await pipeline.save(s.email, await readBody(req));
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- the rotator (LinkSpin core tool)
|
|
if (p === '/api/my/rotations' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const sc = siteConfig(); const hosts = String(sc.linkDomains || '').split(',').map(x => x.trim()).filter(Boolean);
|
|
return json(res, 200, { rotations: await rotator.list(s.email), hosts: hosts.length ? hosts : [SITE_HOST], tier: await toolTier(s.email) }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/my/rotations' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
{ const t = await toolTier(s.email); const have = (await rotator.list(s.email)).length; if (have >= t.max) return json(res, 400, { error: toolCapError('spin links', have, t), tier: t }); }
|
|
const r = await rotator.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/rotations\/(\d+)$/.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.remove ? await rotator.remove(s.email, m[1]) : await rotator.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/rotations\/(\d+)\/dest$/.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 r = await rotator.addDest(s.email, m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/rotations\/(\d+)\/dest\/(\d+)$/.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 r = await rotator.updateDest(s.email, m[1], m[2], await readBody(req)); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/rotations\/(\d+)\/stats$/.exec(p);
|
|
if (m && req.method === 'GET') {
|
|
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.' });
|
|
}
|
|
m = /^\/api\/my\/rotations\/(\d+)\/health$/.exec(p); // "Check now": fresh health states for every destination (once a minute per rotation)
|
|
if (m && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const r = await health.checkRotation(s.email, m[1]); return json(res, r.error ? (/No such/.test(r.error) ? 404 : 429) : 200, r, { 'Cache-Control': 'no-store' });
|
|
}
|
|
// -- Banner Spin builder (2026-10-18). Every route takes GET and POST: the shell's api() helper always POSTs.
|
|
if (p === '/api/my/bannerspins' && (req.method === 'GET' || req.method === 'POST')) {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const b = req.method === 'POST' ? await readBody(req) : {};
|
|
if (req.method === 'GET' || b.list || !b.name) {
|
|
const hs = domains.hosts();
|
|
return json(res, 200, { spins: await bannerspin.list(s.email), tier: await bannerspin.tierFor(s.email), tiers: bannerspin.TIERS, sizes: Object.keys(bannerspin.SIZES), maxBytes: bannerspin.MAX_BYTES, off: bannerspin.settings().off,
|
|
hosts: hs.length ? hs : [{ host: SITE_HOST, channel: 'social', label: 'Social', note: 'The app host (no link domains are live)' }] }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
const r = await bannerspin.create(s.email, b); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/bannerspins/upload' && req.method === 'POST') { // raw image body; JPG / PNG / GIF, 150 KB, counts against the 10 uploads a day
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const t = await bannerspin.tierFor(s.email); if (!t.ok) return json(res, 403, { error: t.reason });
|
|
const ct = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
|
|
const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' };
|
|
if (!EXT[ct]) return json(res, 400, { error: 'Use a JPG, PNG or GIF file.' });
|
|
const key = s.email + ':' + new Date().toISOString().slice(0, 10);
|
|
if (uploadCapHit(s.email, key)) return json(res, 400, { error: 'Upload limit for today reached (10 files).' });
|
|
let buf; try { buf = await readRaw(req, bannerspin.MAX_BYTES); } catch (e) { return json(res, 400, { error: 'That image is over 150 KB. Save it smaller (fewer colors or frames for a GIF) and try again.' }); }
|
|
const magicOk = buf.length > 16 && ((ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) || (ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) || (ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8'));
|
|
if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' });
|
|
const d = bannerspin.dims(buf, ct);
|
|
const name = crypto.randomBytes(12).toString('hex') + '.' + EXT[ct];
|
|
uploadCounts.set(key, (uploadCounts.get(key) || 0) + 1);
|
|
fs.writeFileSync(path.join(UPLOADS_DIR, name), buf);
|
|
content.noteUpload(name, s.email, buf.length, ct, ''); bannerspin.noteImage(s.email, name, d.w, d.h, buf.length, ct);
|
|
const want = bannerspin.SIZES[String(u.searchParams.get('size') || '')];
|
|
return json(res, 200, { ok: true, url: '/uploads/' + name, w: d.w, h: d.h, bytes: buf.length, warn: want && d.w && (d.w !== want[0] || d.h !== want[1]) ? 'This image is ' + d.w + 'x' + d.h + '; the Banner Spin is ' + want[0] + 'x' + want[1] + '. It will be stretched to fit.' : '', left: 10 - uploadCounts.get(key) });
|
|
}
|
|
m = /^\/api\/my\/bannerspins\/(\d+)(\/stats|\/banner(?:\/(\d+))?)?$/.exec(p);
|
|
if (m && (req.method === 'GET' || req.method === 'POST')) {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
if (m[2] === '/stats') { const r = await bannerspin.stats(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such Banner Spin.' }); }
|
|
if (req.method !== 'POST') return json(res, 405, { error: 'POST only.' });
|
|
const b = await readBody(req); let r;
|
|
if (m[3]) r = await bannerspin.updateBanner(s.email, m[1], m[3], b);
|
|
else if (m[2]) r = await bannerspin.addBanner(s.email, m[1], b);
|
|
else r = await bannerspin.update(s.email, m[1], b);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// admin: every Banner Spin; the feature switch + tier grants (POST /api/admin/bannerspins { off } | { email, grant }); one Banner Spin or one banner off / on
|
|
if (p === '/api/admin/bannerspins' && (req.method === 'GET' || req.method === 'POST')) {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
|
const b = req.method === 'POST' ? await readBody(req) : {};
|
|
if (b.off != null || b.grant) { const r = bannerspin.setGlobal(b); content.invalidate(); return json(res, r.error ? 400 : 200, r); }
|
|
return json(res, 200, { spins: bannerspin.adminAll(), settings: bannerspin.settings(), totals: bannerspin.totals() }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
// Banner Spin health checks now (phase 3, 2026-10-20): { id } for one Banner Spin, else all; auto-paused banners are re-checked at once
|
|
if (p === '/api/admin/bannerspins/health' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
|
const b = await readBody(req); const r = await health.checkBannerSpins({ id: Number(b.id) || 0 }); content.invalidate(); return json(res, r.error ? 429 : 200, r);
|
|
}
|
|
m = /^\/api\/admin\/bannerspins\/(\d+)$/.exec(p);
|
|
if (m && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
|
const r = bannerspin.adminSet(m[1], await readBody(req)); content.invalidate(); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/strip' && req.method === 'GET') { // status strip under every Control Room screen
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
let served = 0; try { served = (await rotator.summary(s.email, 1)).totals.served; } catch (e) {}
|
|
let zonesLive = 0; try { zonesLive = (await zones.list(s.email)).filter(z => z.active && z.status !== 'paused').length; } catch (e) {}
|
|
return json(res, 200, { ok: true, served, zones: zonesLive, network: nas.enabled() }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/my/zones' && 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, { zones: await zones.list(s.email), host: SITE_HOST, sizes: Object.keys(zones.SIZES), networkSizes: Array.from(zones.NAS_SIZES), tiers: zones.TIERS, rates: zones.settings(), warmup: zones.WARMUP, holdRatio: zones.HOLD_RATIO }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/my/zones' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const r = await zones.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/zones\/(ls-[a-f0-9]{6})$/.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 r = await zones.update(s.email, m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// tester invite: an admin-minted one-time sign-in link (24 h). Creates the account if needed, bypasses the sign-up
|
|
// gate and needs no email, which is what a curtained test app without outbound mail needs (2026-09-29)
|
|
if (p === '/api/admin/invite' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
|
const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase();
|
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'Which email?' });
|
|
const r = await accounts.ensure(e, '', '', null); if (r.error) return json(res, 400, r);
|
|
const token = crypto.randomBytes(24).toString('hex');
|
|
inviteTokens.set(token, { email: e, exp: Date.now() + 24 * 3600 * 1000, next: /^\/[a-z]/.test(String(b.next || '')) ? String(b.next) : '/ads' });
|
|
return json(res, 200, { ok: true, url: 'https://' + SITE_HOST + '/welcome/' + token, created: !!r.created });
|
|
}
|
|
// -- admin Member content (2026-10-18): every page, link, source, zone, ad, postback, upload, profile, broadcast, audience and
|
|
// video members made, newest first; read-only (rows point at the existing campaign / zone pause routes)
|
|
if (p === '/api/admin/content' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const sp = u.searchParams;
|
|
return json(res, 200, await content.query({ type: sp.get('type') || '', q: (sp.get('q') || '').slice(0, 200), from: sp.get('from') || '', to: sp.get('to') || '', flagged: sp.get('flagged') === '1', page: sp.get('page'), per: sp.get('per'), fresh: sp.get('fresh') === '1' }), { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/admin/zones' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
|
return json(res, 200, { zones: await zones.adminList(), totals: zones.totals(), publishers: zones.publisherTotals(7), rates: zones.settings(), tiers: zones.TIERS, warmup: zones.WARMUP, holdRatio: zones.HOLD_RATIO }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
// admin: pause/resume, note, and the publisher tier ({ tier: 'standard' | 'verified' }; /tier is an alias for the same update)
|
|
m = /^\/api\/admin\/zones\/(ls-[a-f0-9]{6})(\/tier)?$/.exec(p);
|
|
if (m && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
|
const r = await zones.adminSet(m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- hosted page images: /u/pages/<owner-hash>/<id>.<ext>, only files the pages index knows, a year of cache (2026-10-10)
|
|
m = /^\/u\/pages\/([a-f0-9]{16})\/([a-f0-9]{12})\.(png|jpg|webp)$/.exec(p);
|
|
if (m && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
const f = pages.imageFile(m[1], m[2], m[3]); if (!f) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
|
|
return fs.readFile(f.file, (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } res.writeHead(200, { 'Content-Type': f.mime, 'Content-Length': String(data.length), 'Cache-Control': 'public, max-age=31536000, immutable', 'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'inline', 'Access-Control-Allow-Origin': '*' }); res.end(req.method === 'HEAD' ? '' : data); });
|
|
}
|
|
// -- the link-domain pool for the member Links screen: live (not burned, not reserve) hosts with their channel
|
|
if (p === '/api/my/link-hosts' && (req.method === 'GET' || req.method === 'POST')) { // the shell's api() helper posts (2026-10-10)
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const hs = domains.hosts(); return json(res, 200, { hosts: hs.length ? hs : [{ host: SITE_HOST, channel: 'email', label: 'Email', note: 'The app host (no link domains are live)' }], channels: domains.CHANNELS }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/my/pages' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const hosts = domains.live(); // burned or reserve domains are never handed out for new pages
|
|
const ph = pagesHost(); const pageBase = ph ? 'https://' + ph + '/' : 'https://' + (hosts[0] || SITE_HOST) + '/p/';
|
|
return json(res, 200, { pages: await pages.list(s.email), hosts: ph ? [ph] : (hosts.length ? hosts : [SITE_HOST]), pageBase, types: pages.TYPES, styles: require('./pagestyle').catalog(), providers: pages.providers(), images: await pages.images(s.email), imageMax: pages.IMG_MAX, imageBytes: pages.IMG_BYTES , tier: await toolTier(s.email) }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/my/pages/upload' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const up = await pages.readUpload(req); if (up.error) return json(res, 400, up);
|
|
const r = await pages.uploadImage(s.email, up.buf, up.ct); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/pages\/images\/([a-f0-9]{12})$/.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); if (!b.remove) return json(res, 400, { error: 'Nothing to do.' });
|
|
const r = await pages.removeImage(s.email, m[1]); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- admin: the link-domain pool (channel per domain, last safety check, burned flag, check now / clear / pull)
|
|
if (p === '/api/admin/domains' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
|
return json(res, 200, { domains: domains.all(), channels: domains.CHANNELS, labels: domains.LABEL, notes: domains.NOTE, gsb: !!String(process.env.GSB_API_KEY || '').trim() }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/admin/domains' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
|
const b = await readBody(req); let r;
|
|
if (b.action === 'check') r = b.domain ? await domains.check(b.domain) : { ok: true, results: await domains.checkAll() };
|
|
else if (b.action === 'channel') r = domains.setChannel(b.domain, b.channel);
|
|
else if (b.action === 'clear') r = domains.clear(b.domain);
|
|
else if (b.action === 'burn') r = domains.burn(b.domain, b.reason);
|
|
else r = { error: 'Unknown action.' };
|
|
return json(res, r.error ? 400 : 200, Object.assign(r, { domains: domains.all() }));
|
|
}
|
|
if (p === '/api/my/pages' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
{ const t = await toolTier(s.email); const have = (await pages.list(s.email)).length; if (have >= t.max) return json(res, 400, { error: toolCapError('pages', have, t), tier: t }); }
|
|
const r = await pages.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/pages/scan' && 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 = await pages.scan(b.url); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/pages/leads' && 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, { leads: await pages.leads(s.email, u.searchParams.get('page') || null) }, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/my/pages/leads.csv' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const rows = await pages.leads(s.email, u.searchParams.get('page') || null);
|
|
res.writeHead(200, { 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="linkspin-leads.csv"', 'Cache-Control': 'no-store' }); return res.end(pages.csv(rows));
|
|
}
|
|
m = /^\/api\/my\/pages\/([a-f0-9]{10})(\/write)?$/.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 = m[2] ? await pages.write(s.email, m[1], b) : await pages.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
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));
|
|
// spins (the rotator summary, spread at the top level so older report screens keep working) + pages + zones (2026-10-10)
|
|
const [spins, pg, zn] = await Promise.all([rotator.summary(s.email, days), pages.summary(s.email, days), zonereport.summary(s.email, days)]);
|
|
// Banner Spins beside spin links (phase 3, 2026-10-20)
|
|
let bsum = null; try { bsum = await bannerspin.summary(s.email, days); } catch (e) { console.error('bannerspin summary', e.message); }
|
|
// one Conversions panel (2026-11-07): site + network events and goals, each once; the tiles follow the same counts
|
|
const uni = netconv.unified(s.email, days);
|
|
return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, bannerSpins: bsum, days: spins.days, range: days, conversions: uni.rows, totals: Object.assign({}, spins.totals, { joins: uni.joins, wallets: uni.wallets, purchases: uni.buyers, purchaseCount: uni.purchases, goals: uni.goals }) }), { 'Cache-Control': 'no-store' });
|
|
}
|
|
// -- conversion pixel (2026-10-23): goals, per-goal reports, CSV, test. GET and POST (the shell's api() always POSTs).
|
|
if (p === '/api/my/conversions' && (req.method === 'GET' || req.method === 'POST')) {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const b = req.method === 'POST' ? await readBody(req).catch(() => ({})) : {};
|
|
const days = Math.max(1, Math.min(365, Number(b.days || u.searchParams.get('days')) || 30));
|
|
const r = await convtrack.report(s.email, days, { sourceMeta: sources.meta ? sources.meta(s.email) : {} });
|
|
return json(res, 200, Object.assign(r, { host: SITE_HOST, base: (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, limits: convtrack.LIMITS, windowDays: 30, softHours: 24 }), { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/my/conversions/goals' && 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).catch(() => ({})); const r = convtrack.createGoal(s.email, b); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/conversions\/goals\/(px[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).catch(() => ({})); const r = b.test ? convtrack.testGoal(s.email, m[1]) : convtrack.updateGoal(s.email, m[1], b); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/conversions.csv' && 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));
|
|
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="linkspin-conversions-' + days + 'd.csv"', 'Cache-Control': 'no-store' }));
|
|
return res.end(convtrack.csv(s.email, days));
|
|
}
|
|
// -- traffic sources (2026-10-12). Every route takes GET and POST: the shell's api() helper always POSTs.
|
|
if (p === '/api/sources/catalog' && (req.method === 'GET' || req.method === 'POST')) return json(res, 200, { catalog: sources.catalog(), keys: sources.KEYS }, { 'Cache-Control': 'public, max-age=300' });
|
|
if (p === '/api/my/sources' && (req.method === 'GET' || req.method === 'POST')) {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const b = req.method === 'POST' ? await readBody(req) : {};
|
|
if (req.method === 'GET' || b.list || !Object.keys(b).length) return json(res, 200, await sources.list(s.email), { 'Cache-Control': 'no-store' });
|
|
const r = await sources.create(s.email, b); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/sources\/([a-f0-9]{10})(\/url)?$/.exec(p);
|
|
if (m && (req.method === 'GET' || req.method === 'POST')) {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const b = req.method === 'POST' ? await readBody(req) : {}; for (const [k, v] of u.searchParams) if (b[k] == null) b[k] = v;
|
|
if (m[2]) { const r = await sources.urlFor(s.email, m[1], b.rotationId); return json(res, r.error ? 400 : 200, r, { 'Cache-Control': 'no-store' }); }
|
|
if (req.method === 'GET' || !Object.keys(b).length) { const r = await sources.get(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such source.' }); }
|
|
const r = b.test ? await sources.test(s.email, m[1]) : await sources.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
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();
|
|
return json(res, 200, { engine: st.engine, claimDays: st.claimDays, claims: st.claims.filter(c => c.member === me || c.sponsor === me), registry: await registry.get(me) });
|
|
}
|
|
if (p === '/api/admin/carry' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, Object.assign(carry.status(), { registryCount: await registry.count(), rotator: rotator.totals() }));
|
|
}
|
|
if (p === '/api/admin/carry/seed' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req); return json(res, 200, await carry.seedAll(Number(b.limit) || 0));
|
|
}
|
|
// -- live registry sync from InstantAdPay (2026-10-08): signed rows (HMAC LS_SYNC_SECRET over ts + newline + raw body),
|
|
// upserted into the registry; new people become shell accounts with their line, existing shells pick up a username,
|
|
// wallet or sponsor they did not have. Only the posted rows are touched.
|
|
if (p === '/api/partner/registry' && req.method === 'POST') {
|
|
const secret = String(process.env.LS_SYNC_SECRET || '').trim(); if (secret.length < 32) return json(res, 503, { error: 'sync not configured' });
|
|
const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > 2e6) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); });
|
|
const ts = String(req.headers['x-ls-ts'] || ''), sig = String(req.headers['x-ls-sig'] || '');
|
|
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return json(res, 401, { error: 'stale' });
|
|
const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
|
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' });
|
|
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
|
|
const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : [];
|
|
// sponsor follow (2026-10-22): no engine activation may start for these people until the batch has settled their
|
|
// sponsor (carry.hold); wallets are linked LAST, after every sponsor decision, for the same reason
|
|
const held = rows.map(r => String(r.email || '').trim().toLowerCase()).filter(Boolean); carry.hold(held);
|
|
try {
|
|
const n = await registry.importRows(rows, 'instantadpay'); let shells = 0, updated = 0, followed = 0, kept = 0, wallets = [];
|
|
for (const r of rows) {
|
|
const e = String(r.email || '').trim().toLowerCase(); if (!e) continue;
|
|
let a = await accounts.byEmail(e);
|
|
const created = !a;
|
|
if (!a) { const x = await accounts.ensure(e, '', 'carried', r.origin === 'btc4hits' ? 'btc4hits' : 'network'); if (x.created) shells++; a = await accounts.byEmail(e); } // BTC4Hits imports keep their origin (tank mail wording)
|
|
if (!a) continue;
|
|
if (Object.prototype.hasOwnProperty.call(r, 'tank')) followStore.setRemote(e, r.tank); // network tank: InstantAdPay's own adoptions of them
|
|
if (created && SF.incomingOf(r)) { const inc = SF.incomingOf(r); followStore.record(e, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'instantadpay' }); } // a new shell carries the same record (no echo)
|
|
if (r.username && !a.username) { try { await accounts.setUsername(e, r.username); updated++; } catch (err) {} }
|
|
if (r.wallet && !a.address) wallets.push([e, r.wallet]);
|
|
if (r.profile && typeof r.profile === 'object') { // the InstantAdPay profile fills only what is still empty here; the member can change it on this side any time (Marty 2026-10-11)
|
|
const pf = r.profile, ok = v => /^https:[/][/][^ ]+$/i.test(v) && v.length <= 300;
|
|
// prohibited-content policy on ingest (2026-10-30): a bio with a link or a prohibited term, or a social carrying one, is dropped, not stored
|
|
const cp = prohibited.cleanProfile(pf, 'LinkSpin'); if (cp.dropped.length) console.log('registry profile dropped', String(e).replace(/^(.).*(@.*)$/, '$1***$2'), cp.dropped.join(','));
|
|
const av = String(pf.avatarUrl || '').trim(); const bio = cp.bio || ''; let soc = null;
|
|
if (cp.socials) { const c = {}; for (const k of ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']) { const v = String(cp.socials[k] || '').trim(); if (ok(v)) c[k] = v; } if (Object.keys(c).length) soc = JSON.stringify(c); }
|
|
const upd = [!a.avatarUrl && ok(av) ? av : undefined, !a.bio && bio ? bio : undefined, !a.socials && soc ? soc : undefined];
|
|
if (upd.some(x => x !== undefined)) { try { await accounts.setProfile(e, upd[0], upd[1], upd[2]); updated++; } catch (err) {} }
|
|
}
|
|
}
|
|
// sponsors in a second pass: a batch is newest-first, so a member's row usually comes BEFORE their sponsor's, whose
|
|
// shell did not exist yet in the first pass (the sponsor line was left empty until the next change, 2026-10-15)
|
|
for (const r of rows) {
|
|
const e = String(r.email || '').trim().toLowerCase(); if (!e) continue;
|
|
if (SF.incomingOf(r)) { // a DELIBERATE change on InstantAdPay: the follow rule decides (never on a member bound here)
|
|
try { const d = await follow.applyIncoming(e, r); if (d.apply) followed++; else if (d.action !== 'same' && d.action !== 'ordinary') kept++; } catch (err) { console.error('sponsor follow', e, err.message); }
|
|
continue; // decided by the follow rule (a refusal is logged for the Sponsor check), never by the fill-empty rule below
|
|
}
|
|
if (!r.sponsorEmail) continue;
|
|
const a = await accounts.byEmail(e); if (!a || a.sponsorRef) continue;
|
|
const pv = followStore.get(e); if (pv && SF.isDeliberate(pv.by) && !pv.sponsorEmail) continue; // emptied on purpose (released / rescued here): an ordinary row does not refill it
|
|
const sp = await accounts.byEmail(r.sponsorEmail); if (sp && sp.email !== a.email && (sp.username || sp.code)) { try { await accounts.setSponsorRef(e, sp.username || sp.code); updated++; } catch (err) {} }
|
|
}
|
|
for (const [e, w] of wallets) { try { const x = await accounts.linkWallet(e, w); if (x && !x.error) updated++; } catch (err) {} } // last: activation reads the settled sponsor
|
|
return json(res, 200, { ok: true, proto: SF.PROTO, rows: rows.length, imported: n, shells, updated, followed, followKept: kept, registry: await registry.count() });
|
|
} finally { carry.unhold(held); }
|
|
}
|
|
// -- conversion pixel, InstantAdPay side (2026-10-23): its ad clicks arrive here (signed, upsert by id), and its members'
|
|
// goals live on their LinkSpin account (same email): summary for the Campaigns rows, create / update / remove / test.
|
|
if (p === '/api/partner/clicks' && req.method === 'POST') {
|
|
const sg = await readPartnerSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
|
const owners = convtrack.importOwners(sg.body.owners); // InstantAdPay members' own soft keys first, so their own clicks import as tests
|
|
return json(res, 200, { ok: true, n: convtrack.importClicks(sg.body.clicks), owners });
|
|
}
|
|
// -- the Engine Room, partner side: LinkSpin's facts for one member (InstantAdPay builds its panel from them)
|
|
if (p === '/api/partner/engine' && req.method === 'POST') {
|
|
const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
|
const email = String(sg.body.email || '').trim().toLowerCase(); if (!email) return json(res, 400, { error: 'Which member?' });
|
|
return json(res, 200, { ok: true, facts: await engine.facts({ site: 'linkspin', adminMember, ads, coach, bannerspin, rotator, pages, convtrack }, email) });
|
|
}
|
|
if (p === '/api/partner/conv' && req.method === 'POST') {
|
|
const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
|
const b = sg.body; const email = String(b.email || '').trim().toLowerCase();
|
|
// InstantAdPay's sign-ups, wallet links and purchases on a LinkSpin click (2026-11-07, reporting only): one answer per event
|
|
if (b.op === 'events') { const results = []; for (const ev of (Array.isArray(b.events) ? b.events.slice(0, 200) : [])) { let r = { result: 'bad' }; try { r = await netconv.record(ev); } catch (e) { console.error('netconv', e.message); return json(res, 500, { error: 'not recorded' }); } results.push({ k: String(ev && ev.k || '').slice(0, 120), result: r.result }); } return json(res, 200, { ok: true, results }); }
|
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) || email.length > 190) return json(res, 400, { error: 'Which member?' });
|
|
let r;
|
|
if (b.op === 'summary') r = Object.assign(convtrack.partnerSummary(email, b.days), { host: SITE_HOST, network: netconv.partner(email, b.days) });
|
|
else if (b.op === 'create') r = convtrack.createGoal(email, { name: b.name, value: b.value });
|
|
else if (b.op === 'update') r = convtrack.updateGoal(email, b.px, { name: b.name, value: b.value === null ? 0 : b.value }); // null = clear the default (InstantAdPay sends it for an empty box)
|
|
else if (b.op === 'remove') r = convtrack.updateGoal(email, b.px, { remove: true });
|
|
else if (b.op === 'test') r = convtrack.testGoal(email, b.px);
|
|
else return json(res, 400, { error: 'op must be summary, create, update, remove or test' });
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- sponsor check between LinkSpin and InstantAdPay (2026-10-22, sponsorfollow.js). Partner side: InstantAdPay reads our
|
|
// facts and, on an admin's pick in ITS Sponsor check, asks us to apply a sponsor (refused when the member is bound here).
|
|
if (p === '/api/partner/sponsor-facts' && req.method === 'POST') {
|
|
const sg = await readPartnerSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
|
const emails = Array.isArray(sg.body.emails) ? sg.body.emails.slice(0, 5000) : null;
|
|
return json(res, 200, { ok: true, proto: SF.PROTO, platform: 'linkspin', rows: await follow.facts(emails), view: followStore.view() });
|
|
}
|
|
if (p === '/api/partner/sponsor-apply' && req.method === 'POST') {
|
|
const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
|
const b = sg.body; const r = await follow.adminApply(b.email, b.sponsorEmail || null, { note: String(b.note || 'Sponsor check on InstantAdPay').slice(0, 120) });
|
|
console.log('sponsor check (from InstantAdPay)', b.email, '->', b.sponsorEmail || '(tank)', r.error || 'ok');
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/sponsor-check' && (req.method === 'GET' || req.method === 'POST')) {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const mine = await follow.facts(); let peer = null, peerError = null;
|
|
try { peer = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-facts', { all: true }, 90000); } catch (e) { peerError = e.message; }
|
|
const mm = peer ? SF.mismatches(peer.rows || [], mine) : { shared: 0, same: 0, rows: [] };
|
|
return json(res, 200, Object.assign({ ok: true, at: Date.now(), here: 'linkspin', peerError, follow: followStore.view(), peerFollow: peer ? peer.view : null }, mm), { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/admin/sponsor-check/resolve' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req); const email = String(b.email || '').trim().toLowerCase();
|
|
if (!email) return json(res, 400, { error: 'Which member?' });
|
|
let r;
|
|
if (b.use === 'instantadpay') { // InstantAdPay's sponsor, applied HERE (refused when bound here)
|
|
const peer = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-facts', { emails: [email] }, 30000).catch(e => ({ error: e.message }));
|
|
if (peer.error) return json(res, 502, { error: 'Could not read InstantAdPay: ' + peer.error });
|
|
const row = (peer.rows || [])[0]; if (!row) return json(res, 404, { error: email + ' has no InstantAdPay account.' });
|
|
r = await follow.adminApply(email, row.sponsorEmail || null, { note: "Sponsor check: used InstantAdPay's sponsor" });
|
|
} else if (b.use === 'linkspin') { // our sponsor, applied ON INSTANTADPAY (InstantAdPay refuses when bound there)
|
|
const row = (await follow.facts([email]))[0]; if (!row) return json(res, 404, { error: email + ' has no LinkSpin account.' });
|
|
r = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-apply', { email, sponsorEmail: row.sponsorEmail || null, note: "Sponsor check on LinkSpin: used LinkSpin's sponsor" }, 30000).catch(e => ({ error: e.message }));
|
|
} else return json(res, 400, { error: 'use must be instantadpay or linkspin' });
|
|
console.log('sponsor check resolve', email, b.use, r.error || 'ok');
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/iapsync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, iapsync.adminView()); }
|
|
if (p === '/api/admin/iapsync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await iapsync.tick(!!(b && b.force))); }
|
|
if (p === '/api/admin/registry/import' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req); const n = await registry.importRows(b.rows || [], b.property || 'instantadpay');
|
|
// every registry row with a sponsor becomes a site account too, so lines exist before anyone signs in
|
|
let shells = 0;
|
|
if (b.shells) for (const r of await registry.all()) { const a = await accounts.byEmail(r.email); if (!a) { const x = await accounts.ensure(r.email, '', 'carried', 'network'); if (x.created) shells++; if (r.username) { try { await accounts.setUsername(r.email, r.username); } catch (e) {} } if (r.wallet) { try { await accounts.linkWallet(r.email, r.wallet); } catch (e) {} } } }
|
|
if (b.shells) for (const r of await registry.all()) { if (!r.sponsorEmail) continue; const a = await accounts.byEmail(r.email); const sp = await accounts.byEmail(r.sponsorEmail); if (a && sp && !a.sponsorRef) await accounts.setSponsorRef(r.email, sp.username || sp.code); }
|
|
return json(res, 200, { ok: true, imported: n, shells, registry: await registry.count() });
|
|
}
|
|
if (p === '/api/my/prospects' && 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, { prospects: await coach.prospects(s.email), statuses: coach.STATUSES });
|
|
}
|
|
if (p === '/api/my/prospects' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const r = await coach.saveProspect(s.email, await readBody(req));
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/prospects/remove' && 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 = await coach.removeProspect(s.email, b.id);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/profile' && 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 before = await accounts.byEmail(s.email);
|
|
// appearance (2026-11-01): theme auto | light | dark rides the same save path; a theme-only save never touches the username
|
|
if (b.theme !== undefined) {
|
|
const t = ['auto', 'light', 'dark'].includes(String(b.theme)) ? String(b.theme) : null;
|
|
const rt = await accounts.setTheme(s.email, t);
|
|
if (b.username === undefined) return json(res, rt.error ? 400 : 200, rt);
|
|
}
|
|
// a username is permanent once set: the invite link, the public wall and every
|
|
// banner already printed carry it (Marty, 2026-09-10)
|
|
if (before && before.username && String(b.username || '').trim().toLowerCase() !== String(before.username).toLowerCase())
|
|
return json(res, 400, { error: 'Your username is locked. Your invite link, your public page and any banners you shared all carry @' + before.username + '. Contact support (' + SITE_URL + '/support) if it truly has to change.' });
|
|
const r = await accounts.setUsername(s.email, b.username);
|
|
// First time a username is set (onboarding): now there's a real name to
|
|
// show, so notify the sponsor here rather than at signup (where it'd just
|
|
// say "a new member"). Fires once — only on the empty→set transition.
|
|
if (!r.error && before && !before.username && b.username) {
|
|
const acct = await accounts.byEmail(s.email);
|
|
notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {});
|
|
// everyone's dashboard: "@name just joined" (and whether they are waiting in the tank)
|
|
if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() });
|
|
}
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- earn credits by viewing ads (attention-gated daily claim)
|
|
if (p === '/api/my/earn' && 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, await ads.viewStatus(s.email));
|
|
}
|
|
// fraud-guarded view flow: the server issues a single-use token when it
|
|
// serves the ad, and only counts the view if the dwell elapsed on the
|
|
// SERVER clock. Client-side focus tracking pauses the countdown; this is
|
|
// the floor a script cannot cheat past.
|
|
if (p === '/api/my/earnview' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const status = await ads.viewStatus(s.email);
|
|
if (status.views >= status.target || status.claimed) return json(res, 200, { ad: null, status });
|
|
const type = String(u.searchParams.get('type') || 'banner');
|
|
// members never see (or earn from) their own campaigns in the viewer
|
|
const want = type === 'text' ? 'text' : 'banner', vopts = Object.assign({ excludeEmail: s.email }, viewerGeo(req), audiences.matcher(req));
|
|
// the type is a preference, not a filter: the viewer alternates banner/text, so with only one type live every
|
|
// second press said "no member ads" (tester, 2026-10-18). Fall back to the other type before saying none.
|
|
const ad = (await ads.serve(want, vopts)) || (await ads.serve(want === 'text' ? 'banner' : 'text', vopts));
|
|
if (!ad) return json(res, 200, { ad: null, status });
|
|
const token = crypto.randomBytes(16).toString('hex');
|
|
// the viewer tab frames the advertiser's REAL url (no click counted for a paid view)
|
|
earnTokens.set(s.email, { token, ts: Date.now(), adId: ad.id,
|
|
targetUrl: await ads.targetOf(ad.id), adName: ad.title || ad.name || null });
|
|
return json(res, 200, { ad, token, viewUrl: '/view/' + token, status });
|
|
}
|
|
// the viewer tab asks where to point the frame (does not consume the token)
|
|
if (p === '/api/my/viewinfo' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const t = earnTokens.get(s.email);
|
|
if (!t || t.token !== String(u.searchParams.get('token') || ''))
|
|
return json(res, 400, { error: 'That view is no longer open. Head back to the dashboard and load the next ad.' });
|
|
return json(res, 200, { targetUrl: t.targetUrl, adName: t.adName || null,
|
|
dwell: ads.rates().viewDwellSeconds || 10 });
|
|
}
|
|
// human check: handed out only once the dwell has elapsed on the SERVER clock
|
|
if (p === '/api/my/viewchallenge' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const t = earnTokens.get(s.email);
|
|
if (!t || t.token !== String(u.searchParams.get('token') || ''))
|
|
return json(res, 400, { error: 'That view is no longer open.' });
|
|
const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000;
|
|
const age = Date.now() - t.ts;
|
|
if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) });
|
|
if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); }
|
|
const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5);
|
|
const answer = Math.floor(Math.random() * pick.length);
|
|
t.challenge = { answer };
|
|
return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) });
|
|
}
|
|
if (p === '/api/my/adview' && 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 t = earnTokens.get(s.email);
|
|
const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000;
|
|
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That view did not check out. Load the next ad and let it finish.' });
|
|
const age = Date.now() - t.ts;
|
|
if (age < dwellMs - 400) return json(res, 400, { error: 'Watch the full ad first.' });
|
|
if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); }
|
|
// the human check must be solved on the same token
|
|
if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true });
|
|
if (Number(b.answer) !== t.challenge.answer) {
|
|
t.attempts = (t.attempts || 0) + 1;
|
|
t.challenge = null; // force a fresh challenge for the next try
|
|
if (t.attempts >= 3) { earnTokens.delete(s.email); return json(res, 400, { error: 'Three misses — that view is void. Head back and load the next ad.' }); }
|
|
return json(res, 400, { error: 'Wrong pick.', retry: true });
|
|
}
|
|
earnTokens.delete(s.email); // single use
|
|
return json(res, 200, await ads.recordView(s.email));
|
|
}
|
|
if (p === '/api/my/claim' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const r = await ads.claimDaily(s.email);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- downline lineage: 3 levels, usernames+IDs; email only for directs
|
|
if (p === '/api/my/line' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const levels = await accounts.downline(s.email, 3);
|
|
// what each person has paid THIS member so far: sum of TierPaid events where
|
|
// this member is the recipient and that person is the buyer (all indexed events)
|
|
// ...counting payouts to every position this account owns (main id + linked positions)
|
|
const myId = await auth.refreshMemberId(s);
|
|
const own = (await accounts.positions(s.email)).filter(p => p.memberId);
|
|
const myIds = new Set([myId, ...own.map(p => p.memberId)].filter(Boolean));
|
|
const earnedBy = {};
|
|
const qualified = new Set(); // members the contract counted as this account's qualifying buyers ($25+)
|
|
if (myIds.size) {
|
|
for (const ev of chain.recentEvents(1e9)) {
|
|
if (ev.type === 'TierPaid' && myIds.has(ev.recipientId) && ev.buyerId)
|
|
earnedBy[ev.buyerId] = (BigInt(earnedBy[ev.buyerId] || '0') + BigInt(ev.amountWei)).toString();
|
|
if (ev.type === 'BuyerCounted' && myIds.has(ev.sponsorId) && ev.newBuyerId) qualified.add(ev.newBuyerId);
|
|
}
|
|
}
|
|
// who sponsored each person (Marty, 2026-09-14): resolve sponsorRef tokens (username, share code or member id) against the line itself
|
|
const meAcct = await accounts.byEmail(s.email); const byTok = {};
|
|
const label = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member');
|
|
for (const a of [meAcct, ...levels.flatMap(L => L.members)].filter(Boolean)) { const n = label(a); if (a.username) byTok[String(a.username).toLowerCase()] = n; if (a.code) byTok[String(a.code).toLowerCase()] = n; if (a.memberId) byTok[String(a.memberId)] = n; }
|
|
const sponsorOf = m => { const t = String(m.sponsorRef || '').toLowerCase(); if (!t) return null; if (meAcct && (t === String(meAcct.username || '').toLowerCase() || t === String(meAcct.code || '').toLowerCase() || t === String(meAcct.memberId || ''))) return 'you'; return byTok[t] || ('@' + t); };
|
|
// a member's linked positions are theirs too: a qualifying buy from one of them lights their chip
|
|
const posIds = {}; for (const m of levels.flatMap(L => L.members)) { try { posIds[m.email] = (await accounts.positions(m.email)).map(p => p.memberId).filter(Boolean); } catch (e) { posIds[m.email] = []; } }
|
|
const idsOf = m => [m.memberId, ...(posIds[m.email] || [])].filter(Boolean);
|
|
// Clinton's ask (2026-09-14): on levels 2 and 3 show who has made their $25+ buy (counted for their own
|
|
// sponsor) and how many qualifying buyers of their own they have, so a leader can see who is one short
|
|
const onchain = {};
|
|
for (const m of levels.flatMap(L => L.members)) { let bought = false, buyers = 0; for (const id of idsOf(m)) { const mm = await cachedMember(id); if (mm) { if (mm.countedAsBuyer) bought = true; buyers += mm.buyerCount || 0; } } onchain[m.email] = { bought, buyers }; }
|
|
const out = levels.map(L => ({ level: L.level, members: L.members.map(m => ({
|
|
bought: onchain[m.email].bought, buyers: onchain[m.email].buyers,
|
|
memberId: m.memberId || 0,
|
|
sponsor: sponsorOf(m),
|
|
name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member',
|
|
founder: !!m.founder, // Founder badge (cosmetic)
|
|
ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels
|
|
email: L.level === 1 ? m.email : null, // directs only
|
|
joined: m.created,
|
|
qualified: idsOf(m).some(id => qualified.has(id)),
|
|
earnedWei: idsOf(m).reduce((n, id) => n + BigInt(earnedBy[id] || '0'), 0n).toString() })) }));
|
|
// the member's own linked positions sit on level 1 too, labelled as theirs
|
|
if (own.length) {
|
|
if (!out.find(L => L.level === 1)) out.unshift({ level: 1, members: [] });
|
|
const L1 = out.find(L => L.level === 1);
|
|
own.forEach((p, i) => L1.members.push({ memberId: p.memberId, name: 'You · position ' + (i + 2), own: true,
|
|
email: null, joined: p.created, earnedWei: earnedBy[p.memberId] || '0' }));
|
|
}
|
|
return json(res, 200, { levels: out, counts: out.map(L => L.members.length) });
|
|
}
|
|
// -- who is working: one downline member's activity, any of the three levels (Clinton, 2026-09-14)
|
|
if (p === '/api/my/line/activity' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const ref = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40);
|
|
const a = ref ? await accounts.byCode(ref) : null;
|
|
if (!a || !(await accounts.isDownlineOf(s.email, a.email, 3))) return json(res, 404, { error: 'Not in your line.' });
|
|
const now = Date.now();
|
|
const out = { name: a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'), joined: a.created, lastSeen: a.lastSeen || 0, quietDays: Math.floor((now - Math.max(a.created || 0, a.lastSeen || 0)) / 86400000), wallet: !!a.address, memberId: a.memberId || 0 };
|
|
try { const c = await coach.describe(a, now); out.rung = c.label; out.next = c.next; out.stalled = c.stalled; out.buyerCount = c.buyerCount || 0; } catch (e) {}
|
|
try { const v = await ads.viewStatus(a.email); out.viewsToday = v.views; out.target = v.target; out.claimedToday = v.claimed; out.streakDay = v.claimed ? v.streakDay : Math.max(0, v.streakDay - 1); } catch (e) {}
|
|
try { const cs = await ads.listCampaigns(a.email); out.campaigns = cs.length; out.campaignsActive = cs.filter(c => c.status === 'active').length; out.imps = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0); } catch (e) {}
|
|
try { const ls = await coach.linkStats(a.email); out.linkViews30 = (ls.angles || []).reduce((n, r) => n + (r.views30 || 0), 0); out.linkViews = ls.totalViews || 0; out.joins = ls.totalJoins || 0; } catch (e) {}
|
|
try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; }
|
|
out.badges = await badgesHeld(a.email); // chain milestones + Founder
|
|
try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; }
|
|
return json(res, 200, out);
|
|
}
|
|
// -- broadcast a message to your downline (1/day), on-site inbox + email
|
|
if (p === '/api/my/broadcast' && 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 subject = String(b.subject || '').trim().slice(0, 160);
|
|
const body = ads.sanitizeRich(b.body);
|
|
const plain = body.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
|
|
if (!subject) return json(res, 400, { error: 'Give your message a subject.' });
|
|
if (plain.length < 10) return json(res, 400, { error: 'Write a message first.' });
|
|
const last = await messages.lastBroadcastAt(s.email);
|
|
if (Date.now() - last < 24 * 3600 * 1000)
|
|
return json(res, 429, { error: 'You can send one broadcast a day. Try again in ' + Math.ceil((24 * 3600 * 1000 - (Date.now() - last)) / 3600000) + 'h.' });
|
|
const depth = b.scope === 'direct' ? 1 : 3;
|
|
const levels = await accounts.downline(s.email, depth);
|
|
const recipients = [...new Set(levels.flatMap(L => L.members.map(m => m.email)).filter(Boolean))];
|
|
if (!recipients.length) return json(res, 400, { error: 'No one in your line to message yet.' });
|
|
const memberId = s.memberId || await auth.refreshMemberId(s);
|
|
await messages.deliver(memberId, s.email, recipients, subject, body);
|
|
// email each recipient too (best-effort; never blocks the on-site delivery)
|
|
if (mailer.hasKey()) {
|
|
const who = (await accounts.byEmail(s.email));
|
|
const from = who && who.username ? '@' + who.username : 'your sponsor';
|
|
for (const to of recipients) {
|
|
mailer.send(to, 'Message from ' + from + ': ' + subject,
|
|
plain + '\n\n— sent via your LinkSpin upline. Read it in your dashboard: ' + SITE_URL + '/tools#line')
|
|
.catch(() => {});
|
|
}
|
|
}
|
|
return json(res, 200, { ok: true, sent: recipients.length });
|
|
}
|
|
// -- sponsor messages: this member's inbox from their upline
|
|
if (p === '/api/my/messages' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const items = await messages.inbox(s.email);
|
|
const names = await accounts.namesForMembers([...new Set(items.map(i => i.fromMember).filter(Boolean))]);
|
|
for (const i of items) i.fromName = (i.fromMember && names[i.fromMember]) ? '@' + names[i.fromMember]
|
|
: i.fromMember ? 'member #' + i.fromMember : 'your upline';
|
|
return json(res, 200, { items, unread: items.filter(i => !i.read).length });
|
|
}
|
|
m = /^\/api\/my\/messages\/(\d+)\/read$/.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.' });
|
|
return json(res, 200, await messages.markRead(s.email, m[1]));
|
|
}
|
|
|
|
// ── SPONSOR CHAT (two-way): presence-aware 1:1 threads up/down the line ──
|
|
const chatOnline = ts => (Date.now() - (ts || 0)) < 60000;
|
|
const chatName = a => !a ? 'member' : (a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'));
|
|
// lightweight presence heartbeat (called on a timer while the dashboard is open)
|
|
if (p === '/api/my/ping' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 200, { ok: true, chatUnread: 0 });
|
|
accounts.touchSeen(s.email).catch(() => {});
|
|
return json(res, 200, { ok: true, chatUnread: await messages.chatUnread(s.email) });
|
|
}
|
|
// training center content (admin-curated via data/training.json)
|
|
if (p === '/api/training' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s) return json(res, 401, { error: 'Sign in first.' });
|
|
let items = [];
|
|
try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'training.json'), 'utf8')); if (Array.isArray(j)) items = j; } catch (e) {}
|
|
// a card with feature:'pipeline' waits for the switch, so the video can be ready before the tab opens (Marty, 2026-09-15)
|
|
// built-in lessons shipped with the code (catalog/training.json, Banner Spin 2026-10-20): appended unless the volume list already has the same id
|
|
try { const extra = JSON.parse(fs.readFileSync(path.join(__dirname, 'catalog', 'training.json'), 'utf8')); if (Array.isArray(extra)) for (const it of extra) if (it && it.id && !items.some(x => x && x.id === it.id)) items.push(it); } catch (e) {}
|
|
const scT = siteConfig(); items = items.filter(it => !it.feature || (it.feature === 'pipeline' && pipeline.visible(scT.pipelineMode, s.email, ADMIN_EMAIL)));
|
|
if (!items.length) items = [{ title: 'Getting started with LinkSpin',
|
|
desc: 'How the platform works, how every payout splits on-chain to real wallets, and how to build your line.',
|
|
docUrl: SITE_URL + '/' }];
|
|
return json(res, 200, { items });
|
|
}
|
|
// daily login bonus (once/day, gentle streak) — granted after the login flow
|
|
if (p === '/api/my/login-bonus' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
return json(res, 200, await ads.grantLoginBonus(s.email));
|
|
}
|
|
// -- rehearsal test-POL faucet: top a connected wallet up to 10 test-POL
|
|
// (anvil_setBalance, no key needed). Rehearsal-only, rate-limited.
|
|
if (p === '/api/my/faucet' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s) return json(res, 401, { error: 'Sign in first.' });
|
|
if (!siteConfig().rehearsal) return json(res, 400, { error: 'The faucet is only open during the rehearsal.' });
|
|
const b = await readBody(req);
|
|
const addr = String(b.address || '').trim().toLowerCase();
|
|
if (!/^0x[0-9a-f]{40}$/.test(addr)) return json(res, 400, { error: 'Connect your wallet first.' });
|
|
// Amoy is a public testnet: testers fund their own connected wallet from
|
|
// the public Amoy faucet (no server-minted balance). We just echo the
|
|
// address + faucet link; the client copies the address and opens it.
|
|
let balHex = '0x0'; try { balHex = await chain.rpc('eth_getBalance', [addr, 'latest']); } catch (e) {}
|
|
return json(res, 200, { ok: true, faucetUrl: 'https://faucet.polygon.technology/', address: addr, balanceWei: BigInt(balHex || '0x0').toString() });
|
|
}
|
|
// -- report an ad (auto-approved ads need a safety valve): store + notify admin
|
|
if (p === '/api/report-ad' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
if (!Number(b.campaignId)) return json(res, 400, { error: 'Which ad?' });
|
|
const s = await auth.fromRequest(req);
|
|
const who = (s && s.email) || '';
|
|
const rec = await reports.add(b.campaignId, who, b.reason, b.note);
|
|
try {
|
|
const adminEmail = process.env.ADMIN_EMAIL || ''; // private env only — siteConfig is exposed via /api/config
|
|
if (adminEmail && mailer.hasKey()) {
|
|
mailer.send(adminEmail, 'Ad reported on LinkSpin (campaign #' + rec.campaignId + ')',
|
|
'A member flagged an ad.\n\nCampaign: #' + rec.campaignId + '\nReason: ' + rec.reason
|
|
+ '\nReported by: ' + (who || 'anonymous') + '\nNote: ' + (String(b.note || '').slice(0, 500) || '(none)')
|
|
+ '\n\nPause or review it from the admin.').catch(() => {});
|
|
}
|
|
} catch (e) {}
|
|
return json(res, 200, { ok: true });
|
|
}
|
|
if (p === '/api/my/chat/send' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const me = s.email.toLowerCase();
|
|
const b = await readBody(req);
|
|
const to = String(b.to || '').trim().toLowerCase();
|
|
const text = String(b.body || '').replace(/<[^>]*>/g, '').replace(/\s+$/, '').slice(0, 2000).trim();
|
|
if (!to || to === me) return json(res, 400, { error: 'Pick who to message.' });
|
|
if (!text) return json(res, 400, { error: 'Write a message first.' });
|
|
const target = await accounts.byEmail(to);
|
|
if (!target) return json(res, 404, { error: 'No such member.' });
|
|
// authorize: existing thread, my direct sponsor, or someone in my downline
|
|
let ok = (await messages.thread(me, to, 0, 1)).length > 0;
|
|
if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === to); }
|
|
if (!ok) ok = await accounts.isDownlineOf(me, to);
|
|
if (!ok) return json(res, 403, { error: 'You can only message your direct sponsor or someone in your line.' });
|
|
if ((await accounts.getMutes(to)).map(x => String(x).toLowerCase()).includes(me))
|
|
return json(res, 403, { error: 'They are not accepting messages from you right now.' });
|
|
const memberId = s.memberId || await auth.refreshMemberId(s);
|
|
const msg = await messages.sendChat(memberId, me, to, text);
|
|
// email only when they are offline AND I have not messaged them in ~10 min (no mid-chat spam)
|
|
try {
|
|
if (mailer.hasKey() && !chatOnline(target.lastSeen)) {
|
|
const mine = (await messages.thread(me, to, 0, 400)).filter(x => x.id !== msg.id && String(x.fromEmail).toLowerCase() === me);
|
|
const lastMineTs = mine.length ? mine[mine.length - 1].sent : 0;
|
|
if (Date.now() - lastMineTs > 10 * 60 * 1000) {
|
|
const who = await accounts.byEmail(me);
|
|
const from = who && who.username ? '@' + who.username : 'someone in your LinkSpin line';
|
|
mailer.send(to, 'New message from ' + from,
|
|
text.slice(0, 400) + '\n\n— reply in your dashboard: ' + SITE_URL + '/tools').catch(() => {});
|
|
}
|
|
}
|
|
} catch (e) {}
|
|
return json(res, 200, { ok: true, message: { id: msg.id, sent: msg.sent, fromMe: true, body: text } });
|
|
}
|
|
if (p === '/api/my/chat/thread' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const me = s.email.toLowerCase();
|
|
const other = String(u.searchParams.get('with') || '').trim().toLowerCase();
|
|
const after = Number(u.searchParams.get('after')) || 0;
|
|
if (!other) return json(res, 400, { error: 'Who with?' });
|
|
// may view a thread I'm party to (existing), or one I'm allowed to start
|
|
let ok = (await messages.thread(me, other, 0, 1)).length > 0;
|
|
if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === other); }
|
|
if (!ok) ok = await accounts.isDownlineOf(me, other);
|
|
if (!ok) return json(res, 403, { error: 'Not your conversation.' });
|
|
const msgs = await messages.thread(me, other, after, 300);
|
|
await messages.markChatRead(me, other);
|
|
accounts.touchSeen(me).catch(() => {});
|
|
const oa = await accounts.byEmail(other);
|
|
const iMute = (await accounts.getMutes(me)).map(x => String(x).toLowerCase()).includes(other);
|
|
const theyMuteMe = (await accounts.getMutes(other)).map(x => String(x).toLowerCase()).includes(me);
|
|
return json(res, 200, {
|
|
messages: msgs.map(x => ({ id: x.id, fromMe: String(x.fromEmail).toLowerCase() === me, body: x.body, sent: x.sent })),
|
|
otherName: chatName(oa), online: oa ? chatOnline(oa.lastSeen) : false,
|
|
available: oa ? oa.chatAvailable !== false : true, iMute, blocked: theyMuteMe,
|
|
canMute: await accounts.isDownlineOf(me, other) });
|
|
}
|
|
if (p === '/api/my/chat/threads' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const list = await messages.threadList(s.email.toLowerCase());
|
|
for (const t of list) {
|
|
const a = await accounts.byEmail(t.email);
|
|
t.name = chatName(a); t.online = a ? chatOnline(a.lastSeen) : false;
|
|
}
|
|
list.sort((x, y) => (y.last.sent || 0) - (x.last.sent || 0));
|
|
const meAcct = await accounts.byEmail(s.email);
|
|
return json(res, 200, { threads: list, available: meAcct ? meAcct.chatAvailable !== false : true });
|
|
}
|
|
if (p === '/api/my/chat/available' && 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);
|
|
return json(res, 200, await accounts.setChatAvailable(s.email, !!b.available));
|
|
}
|
|
if (p === '/api/my/chat/mute' && 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 target = String(b.email || '').trim().toLowerCase();
|
|
if (!target) return json(res, 400, { error: 'Who?' });
|
|
const allowed = (await accounts.isDownlineOf(s.email, target)) || (await messages.thread(s.email.toLowerCase(), target, 0, 1)).length > 0;
|
|
if (!allowed) return json(res, 403, { error: 'You can only mute someone in your line.' });
|
|
return json(res, 200, await accounts.setMute(s.email, target, !!b.muted));
|
|
}
|
|
// -- featured rotation: the live featured links + dilution stats
|
|
if (p === '/api/featured' && req.method === 'GET') {
|
|
const items = await ads.serveFeatured(viewerGeo(req));
|
|
try { const sv = await auth.fromRequest(req); ads.noteFeaturedViews(items, (sv && sv.email) || clientIp(req)).catch(() => {}); } catch (e) {} // count the view (per viewer per hour)
|
|
const names = await accounts.namesForMembers([...new Set(items.map(i => i.memberId).filter(Boolean))]);
|
|
for (const i of items) i.by = (i.memberId && names[i.memberId]) ? '@' + names[i.memberId] : (i.memberId ? 'member #' + i.memberId : null);
|
|
return json(res, 200, { items });
|
|
}
|
|
if (p === '/api/featured/stats' && req.method === 'GET') {
|
|
return json(res, 200, await ads.featuredStats());
|
|
}
|
|
// -- QR code (SVG) for any LinkSpin URL — used on bio/wall pages
|
|
if (p === '/api/qr' && req.method === 'GET') {
|
|
const data = String(u.searchParams.get('d') || '').slice(0, 300);
|
|
if (!QR || !data) { res.writeHead(404, baseHeaders()); return res.end(); }
|
|
try {
|
|
const svg = await QR.toString(data, { type: 'svg', margin: 1, width: 240,
|
|
color: { dark: '#0e7d5f', light: '#f2fbf8' } }); // mint-green modules, still high-contrast for reliable scanning
|
|
res.writeHead(200, baseHeaders({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600' }));
|
|
return res.end(svg);
|
|
} catch (e) { res.writeHead(500, baseHeaders()); return res.end(); }
|
|
}
|
|
// -- profile: avatar + bio
|
|
if (p === '/api/my/profile-details' && 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 avatar = b.avatarUrl === undefined ? undefined : String(b.avatarUrl || '').trim();
|
|
if (avatar && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(avatar))
|
|
return json(res, 400, { error: 'Avatar must be an uploaded image or an https image URL.' });
|
|
const bio = b.bio === undefined ? undefined : String(b.bio || '').trim().slice(0, 600);
|
|
// socials: {platform: url}; keep only known platforms with valid https urls
|
|
let socials, cleanSoc = null;
|
|
if (b.socials !== undefined) {
|
|
const PLAT = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video'];
|
|
const clean = {};
|
|
for (const p of PLAT) {
|
|
const v = String((b.socials && b.socials[p]) || '').trim();
|
|
if (v && /^https:\/\/[^\s]+$/i.test(v) && v.length <= 300) clean[p] = v;
|
|
}
|
|
// intro video on the public wall: a YouTube, Vimeo or direct .mp4/.webm link only
|
|
if (clean.video && !/^https:\/\/((www\.|m\.)?youtube\.com\/(watch\?|shorts\/|embed\/)|youtu\.be\/|(www\.)?vimeo\.com\/\d+|player\.vimeo\.com\/video\/\d+|[^\s]+\.(mp4|webm)(\?|$))/i.test(clean.video))
|
|
return json(res, 400, { error: 'The intro video needs to be a YouTube link, a Vimeo link, or a direct .mp4 link.' });
|
|
socials = Object.keys(clean).length ? JSON.stringify(clean) : null;
|
|
cleanSoc = clean;
|
|
}
|
|
// prohibited-content policy (2026-10-30): gambling, adult, pharma, weapons and link-selling terms are refused in the bio and the social URLs
|
|
{ const pr = prohibited.checkFields(Object.assign({ bio }, cleanSoc || {}), 'LinkSpin', { profile: true }); if (pr.error) { prohibited.logRefusal('profile-details', s.email, pr); return json(res, 400, { error: pr.error }); } }
|
|
// a bio is not a backlink: links go in the social fields. Exception, the quarantine rule: a brand-new free account (no wallet,
|
|
// no sponsor, under 24 h) whose first save plants a link is saved with profileQuarantined and never rendered publicly
|
|
const acct = await accounts.byEmail(s.email);
|
|
const quarantine = spamscan.shouldQuarantine(acct, bio, cleanSoc) ? true : undefined;
|
|
if (bio && prohibited.hasUrl(bio) && !quarantine) { prohibited.logRefusal('profile-details', s.email, { field: 'bio', reason: 'url' }); return json(res, 400, { error: prohibited.BIO_LINK_MSG }); }
|
|
const r = await accounts.setProfile(s.email, avatar, bio, socials, quarantine);
|
|
if (quarantine && !r.error) { console.log('profile quarantined', String(s.email).replace(/^(.).*(@.*)$/, '$1***$2'), prohibited.hasUrl(bio) ? 'bio-url' : 'social-link'); r.quarantined = true; r.notice = spamscan.QUARANTINE_NOTICE; }
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- wall positions 2 & 3: the member's own offers, unlocked at 2 / 5 qualifying buyers
|
|
if (p === '/api/my/wall-offers' && 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 src = Array.isArray(b.offers) ? b.offers.slice(0, 2) : [];
|
|
const out = [];
|
|
for (let i = 0; i < 2; i++) {
|
|
const o = src[i] || {};
|
|
const targetUrl = String(o.targetUrl || '').trim();
|
|
const bannerUrl = String(o.bannerUrl || '').trim();
|
|
const title = String(o.title || '').trim().slice(0, 60);
|
|
if (targetUrl && !/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': the link must start with https://' });
|
|
if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': banner must be an uploaded image or an https image URL.' });
|
|
{ const pr = prohibited.checkFields({ title, targetUrl }, 'LinkSpin'); if (pr.error) { prohibited.logRefusal('wall-offers', s.email, pr); return json(res, 400, { error: pr.error }); } }
|
|
out.push(targetUrl ? { title: title || null, bannerUrl: bannerUrl || null, targetUrl } : null);
|
|
}
|
|
const r = await accounts.setWallOffers(s.email, out.some(Boolean) ? JSON.stringify(out) : null);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- line banner: the member's viral slot on welcome tours + their wall
|
|
if (p === '/api/my/linebanner' && 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 target = String(b.targetUrl || '').trim();
|
|
if (!/^https?:\/\/[^\s]+$/i.test(target)) return json(res, 400, { error: 'Destination URL must start with http(s)://' });
|
|
{ const pr = prohibited.checkFields({ targetUrl: target }, 'LinkSpin'); if (pr.error) { prohibited.logRefusal('linebanner', s.email, pr); return json(res, 400, { error: pr.error }); } }
|
|
const fc = await frameCheck(target); // welcome tours frame it full screen
|
|
if (!fc.ok) return json(res, 400, { error: fc.reason });
|
|
const banner = String(b.bannerUrl || '').trim();
|
|
if (banner && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(banner))
|
|
return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL.' });
|
|
const r = await accounts.setLineBanner(s.email, banner || null, target);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- welcome tour (gauntlet): meet the 3-level upline, then unlock welcome credits
|
|
if (p === '/api/my/gauntlet' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
if (await ads.welcomeGranted(s.email)) return json(res, 200, { pending: false });
|
|
const slides = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl)
|
|
.map((a, i) => ({ name: a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member',
|
|
bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl }));
|
|
if (!slides.length) return json(res, 200, { pending: false });
|
|
const token = crypto.randomBytes(16).toString('hex');
|
|
gauntletTokens.set(s.email, { token, ts: Date.now(), n: slides.length });
|
|
return json(res, 200, { pending: true, slides, dwell: 10, token });
|
|
}
|
|
if (p === '/api/my/gauntlet/complete' && 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 t = gauntletTokens.get(s.email);
|
|
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That tour is no longer open. Reload and try again.' });
|
|
if (Date.now() - t.ts < t.n * 10 * 1000 - 1500) return json(res, 400, { error: 'Give each site its ten seconds first.' });
|
|
gauntletTokens.delete(s.email);
|
|
await ads.grantWelcome(s.email);
|
|
return json(res, 200, { ok: true, credited: ads.rates().welcomeCredits || 0 });
|
|
}
|
|
// -- public banner wall
|
|
m = /^\/api\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p);
|
|
if (m && req.method === 'GET') {
|
|
const tok = m[1].toLowerCase();
|
|
let a = await accounts.byUsername(tok);
|
|
if (!a) a = await accounts.byCode(tok);
|
|
if (!a) return json(res, 404, { error: 'No wall under that name.' });
|
|
const ownName = a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member';
|
|
let bc = 0;
|
|
if (a.memberId) { try { bc = (await chain.member(a.memberId)).buyerCount || 0; } catch (e) {} }
|
|
const unlocked = wallUnlockedFor(bc);
|
|
const offers = parseWallOffers(a);
|
|
// uplines with a live banner, in order (an upline with nothing set is skipped, not shown empty)
|
|
const ups = (await uplineSlides(a.email, 2)).filter(x => x.lineTargetUrl)
|
|
.map(x => ({ name: x.username ? '@' + x.username : x.memberId ? 'member #' + x.memberId : 'a member',
|
|
bannerUrl: x.lineBannerUrl || null, targetUrl: x.lineTargetUrl, upline: true }));
|
|
const adAds = getAdminWallAds(); let ai = 0;
|
|
const houseAd = () => { if (!adAds.length) return null; const ad = adAds[ai++ % adAds.length]; return { name: ad.name || 'LinkSpin', bannerUrl: ad.bannerUrl || null, targetUrl: ad.targetUrl || SITE_URL + '/', admin: true }; };
|
|
const ladder = [{ name: ownName, bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl || null, own: true }];
|
|
for (let i = 1; i < 3; i++) {
|
|
const o = offers[i - 1];
|
|
if (i < unlocked && o && o.targetUrl) { ladder.push({ name: (o.title || ownName), bannerUrl: o.bannerUrl || null, targetUrl: o.targetUrl, own: true }); continue; }
|
|
const u = ups.shift(); if (u) { ladder.push(u); continue; }
|
|
const h = houseAd(); if (h) ladder.push(h);
|
|
}
|
|
const finalLadder = ladder.slice(0, 3);
|
|
// the wall owner's achievement badge (their highest reached tier)
|
|
let badge = null;
|
|
if (a.memberId) {
|
|
const t = bc >= 5 ? ['nexus', 'Nexus'] : bc >= 2 ? ['circuit', 'Circuit'] : bc >= 1 ? ['surge', 'Surge'] : ['spark', 'Spark'];
|
|
badge = { img: '/badges/badge-' + t[0] + '.jpg?v=3', label: t[1] };
|
|
}
|
|
const joinPath = '/join/' + (a.username || a.code);
|
|
// profile fields (bio, avatar, socials, intro video) only for a paying member; a free account's wall carries the name, the line's ads and the join call (2026-10-30)
|
|
const bought = await hasBought(a); // a purchase lifts the quarantine too: the notice promised the links after the first package
|
|
let socials = null; if (bought) { try { socials = a.socials ? JSON.parse(a.socials) : null; } catch (e) {} }
|
|
return json(res, 200, { name: a.username ? '@' + a.username : 'member #' + (a.memberId || 0), bought,
|
|
avatarUrl: bought ? (a.avatarUrl || null) : null, bio: bought ? (a.bio || null) : null, socials, badge,
|
|
founder: a.founder ? { img: '/badges/badge-founder.jpg', label: 'Founder' } : null, // cosmetic Founder badge (2026-11-05)
|
|
joinUrl: joinPath, qrUrl: '/api/qr?d=' + encodeURIComponent(SITE_URL + joinPath), ladder: finalLadder, unlocked, buyerCount: bc });
|
|
}
|
|
// -- watch-to-earn video ads: serve one, then reward a server-clock-verified watch
|
|
if (p === '/api/my/videos' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const status = await ads.videoStatus(s.email);
|
|
if (status.left <= 0) return json(res, 200, { ad: null, status });
|
|
const orientation = String(u.searchParams.get('orientation') || ''); // 'portrait' = Shorts reel, 'landscape' = Watch videos tab
|
|
const ad = await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation }, viewerGeo(req))); // never your own video
|
|
if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13)
|
|
let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation, ignoreSeen: true }, viewerGeo(req)))); } catch (e) {}
|
|
return json(res, 200, { ad: null, status, allWatched });
|
|
}
|
|
const token = crypto.randomBytes(16).toString('hex');
|
|
videoTokens.set(s.email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs });
|
|
return json(res, 200, { ad, token, status });
|
|
}
|
|
if (p === '/api/my/videowatch' && 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 t = videoTokens.get(s.email);
|
|
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That video is no longer open. Load the next one.' });
|
|
const age = Date.now() - t.ts;
|
|
if (age < t.secs * 1000 - 600) return json(res, 400, { error: 'Watch the full video first.' });
|
|
if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(s.email); return json(res, 400, { error: 'That watch went stale. Load a fresh video.' }); }
|
|
videoTokens.delete(s.email); // single use
|
|
if (await ads.hasWatchedVideoToday(s.email, t.id)) // once-per-day-per-video: no double earning
|
|
return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), already: true });
|
|
const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry
|
|
if (!tier) return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), gone: true });
|
|
await ads.addEarned(s.email, tier.reward);
|
|
await ads.markVideoSeen(s.email, t.id);
|
|
const status = await ads.recordVideoWatch(s.email);
|
|
return json(res, 200, { ok: true, credited: tier.reward, status });
|
|
}
|
|
// -- verified visits: view a member's site (new tab) for the dwell, pass a
|
|
// human check, and it counts as one guaranteed unique visit for the pack
|
|
if (p === '/api/my/visits' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const status = await ads.visitStatus(s.email);
|
|
if (status.count >= status.cap) return json(res, 200, { ad: null, status });
|
|
const ad = await ads.serveVisit(s.email, viewerGeo(req));
|
|
if (!ad) return json(res, 200, { ad: null, status });
|
|
const token = crypto.randomBytes(16).toString('hex');
|
|
visitTokens.set(s.email, { token, ts: Date.now(), id: ad.id });
|
|
return json(res, 200, { ad, token, status });
|
|
}
|
|
if (p === '/api/my/visitchallenge' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const t = visitTokens.get(s.email);
|
|
if (!t || t.token !== String(u.searchParams.get('token') || '')) return json(res, 400, { error: 'That visit is no longer open.' });
|
|
const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000;
|
|
const age = Date.now() - t.ts;
|
|
if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) });
|
|
if (age > 5 * 60 * 1000) { visitTokens.delete(s.email); return json(res, 400, { error: 'That visit went stale. Load a fresh one.' }); }
|
|
const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5);
|
|
const answer = Math.floor(Math.random() * pick.length);
|
|
t.challenge = { answer };
|
|
return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) });
|
|
}
|
|
if (p === '/api/my/visitdone' && 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 t = visitTokens.get(s.email);
|
|
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That visit did not check out. Load the next one.' });
|
|
const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000;
|
|
if (Date.now() - t.ts < dwellMs - 400) return json(res, 400, { error: 'Give the site the full visit first.' });
|
|
if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true });
|
|
if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; return json(res, 400, { error: 'Wrong pick.', retry: true }); }
|
|
visitTokens.delete(s.email);
|
|
const r = await ads.completeVisit(s.email, t.id);
|
|
if (r.error) return json(res, 400, r);
|
|
return json(res, 200, Object.assign(r, { status: await ads.visitStatus(s.email) }));
|
|
}
|
|
// -- onsite solo ads: member inbox with read rewards
|
|
if (p === '/api/my/inbox' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const r = await ads.inboxList(s.email, viewerGeo(req));
|
|
const names = await accounts.namesForMembers([...new Set(r.items.map(i => i.fromMemberId).filter(Boolean))]);
|
|
for (const i of r.items) i.fromName = (i.fromMemberId && names[i.fromMemberId]) ? '@' + names[i.fromMemberId]
|
|
: i.fromMemberId ? 'member #' + i.fromMemberId : 'a member';
|
|
return json(res, 200, r);
|
|
}
|
|
m = /^\/api\/my\/inbox\/(\d+)$/.exec(p);
|
|
if (m && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const r = await ads.inboxOpen(s.email, m[1]);
|
|
if (!r.error) {
|
|
const names = r.fromMemberId ? await accounts.namesForMembers([r.fromMemberId]) : {};
|
|
r.fromName = (r.fromMemberId && names[r.fromMemberId]) ? '@' + names[r.fromMemberId]
|
|
: r.fromMemberId ? 'member #' + r.fromMemberId : 'a member';
|
|
}
|
|
return json(res, r.error ? 404 : 200, r);
|
|
}
|
|
// media upload for solo ads: raw body, size-capped, magic-byte verified
|
|
if (p === '/api/my/upload' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
return handleUpload(req, res, s.email);
|
|
}
|
|
m = /^\/api\/my\/inbox\/(\d+)\/visit$/.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 r = await ads.markSoloVisit(s.email, m[1]);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/inbox\/(\d+)\/claim$/.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 r = await ads.claimSoloRead(s.email, m[1]);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/activity' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s) return json(res, 401, { error: 'Sign in first.' });
|
|
const id = s.memberId || await auth.refreshMemberId(s);
|
|
if (!id) return json(res, 200, { memberId: 0, earnings: [], purchases: [], referrals: [] });
|
|
const evs = chain.recentEvents(1e9); // whole history (was the last 600: IAP lost older members' earnings that way on 2026-09-16)
|
|
return json(res, 200, {
|
|
memberId: id,
|
|
earnings: (await attachNames(evs.filter(e => (e.type === 'TierPaid' && e.recipientId === id) || (e.type === 'AwardPaid' && e.toId === id))))
|
|
.map(e => { const ov = e.type === 'AwardPaid' && override.txInfo(e.tx); return ov ? Object.assign({}, e, { override: true, overrideWeek: ov.week }) : e; }), // level-4 override label
|
|
// buys from the member's linked positions count too (Marty's #353 bought a package that Credits never showed, 2026-10-18);
|
|
// position = 2, 3 ... in the order the positions were added, null = the main wallet
|
|
purchases: await (async () => {
|
|
const posOf = {}; try { if (s.email) (await accounts.positions(s.email)).forEach((ps, i) => { if (ps.memberId && ps.memberId !== id) posOf[ps.memberId] = i + 2; }); } catch (e) {}
|
|
return attachNames(evs.filter(e => e.type === 'Purchase' && (e.buyerId === id || posOf[e.buyerId])).map(e => Object.assign({}, e, { position: e.buyerId === id ? null : posOf[e.buyerId] })));
|
|
})(),
|
|
referrals: await attachNames(evs.filter(e => (e.type === 'MemberActivated' && e.sponsorId === id) || (e.type === 'BuyerCounted' && e.sponsorId === id)))
|
|
});
|
|
}
|
|
|
|
// -- ad engine (spec §8b v1: banners, text, login ads)
|
|
if (p === '/api/ads/slot' && req.method === 'GET') {
|
|
const t = String(u.searchParams.get('type') || 'banner');
|
|
const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req), audiences.matcher(req)));
|
|
// login ads: the member clicks "Open Ad" (a real, counted click into a
|
|
// new tab) while the countdown runs on our interstitial page
|
|
if (ad && t === 'login') ad.dwell = ads.rates().loginDwellSeconds || 10;
|
|
return json(res, 200, { ad });
|
|
}
|
|
m = /^\/api\/ads\/click\/(\d+)$/.exec(p);
|
|
if (m && req.method === 'GET') {
|
|
const target = await ads.click(m[1]);
|
|
if (!target) { res.writeHead(404, baseHeaders()); return res.end(); }
|
|
coach.recordClick(m[1], req.headers.referer); // where the click happened
|
|
const t = await adClickTarget(m[1], target, req); // conversion pixel: click id recorded + ?lsclk= on the target (2026-10-23)
|
|
res.writeHead(302, baseHeaders(Object.assign({ Location: t.url }, t.cookie ? { 'Set-Cookie': t.cookie } : {})));
|
|
return res.end();
|
|
}
|
|
if (p === '/api/my/audiences' && 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, { audiences: audiences.list(s.email), host: SITE_HOST });
|
|
}
|
|
if (p === '/api/my/audiences' && 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.remove ? audiences.remove(s.email, b.id) : b.id ? audiences.rename(s.email, b.id, b.name) : audiences.create(s.email, b.name);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/my/campaigns' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const memberId = await auth.refreshMemberId(s);
|
|
// welcome credits used to unlock only through the classic dashboard; the Control Room Ads screen grants them the same way (2026-09-29)
|
|
let gauntletPending = false;
|
|
if (!(await ads.welcomeGranted(s.email))) { const tour = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl); if (!tour.length) await ads.grantWelcome(s.email); else gauntletPending = true; }
|
|
const out = { campaigns: await ads.listCampaigns(s.email), rates: ads.rates(), bannerSizes: ads.bannerSizes(), gauntletPending, audiences: audiences.list(s.email) };
|
|
out.loginSlots = await ads.loginSlots(); // { max, used, queued, free, credits, days }: the Ads screen shows how many are open
|
|
out.loginQueue = await ads.myLoginQueue(s.email); // my paid reservations: place in line + estimated start (Central)
|
|
out.loginNext = await ads.loginNext(); // the place and estimated start a new reservation would get
|
|
// a login slot is paid from ONE position (Michael Camire 2026-11-03: 1,000 credits split 618 + 382 failed with a toast he never saw):
|
|
// the screen shows each position's free purchased credits and stops the buy before it is tried
|
|
try { const pool = await ads.balances((await myMemberIds(s)).ids, s.email);
|
|
out.loginFunds = { best: (pool.best.avail || 0) + (pool.credited || 0), credited: pool.credited || 0, per: pool.per.map(x => ({ memberId: x.memberId, avail: x.avail })) }; } catch (e) { out.loginFunds = null; }
|
|
out.creditLog = await ads.creditLog(s.email, 20); // credit activity (login slots, reservations, refunds)
|
|
out.editFee = editFee(); // credits per edit after each campaign's free one (the editor says which this is)
|
|
out.clickSources = await coach.clickSources(out.campaigns.map(c => c.id));
|
|
out.hours = await ads.hoursFor(out.campaigns.map(c => c.id)); // on-site views per UTC hour, last 7 days
|
|
out.geo = await ads.geoFor(out.campaigns.map(c => c.id)); // on-site serves per viewer country
|
|
{ const t = geo.tierLists(siteConfig()); out.tiers = { t1: [...t.t1], t2: [...t.t2] }; out.geoReady = geo.status().loaded; }
|
|
const pool = await ads.balances((await myMemberIds(s)).ids, s.email);
|
|
out.purchasedCredits = pool.total;
|
|
out.largestPosition = pool.best.avail; // a single campaign budget has to fit one position
|
|
out.positionCount = pool.per.length;
|
|
out.creditedCredits = pool.credited; // refunded/credited purchased money, free (counts inside purchasedCredits)
|
|
out.earnedCredits = pool.earned; // earned pool minus what live campaigns already hold
|
|
out.earnedReserved = pool.earnedReserved;
|
|
out.inCampaigns = pool.inCampaigns; // budget still to deliver across live campaigns
|
|
out.availableCredits = pool.available;
|
|
return json(res, 200, out);
|
|
}
|
|
if (p === '/api/my/campaigns' && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const memberId = await auth.refreshMemberId(s); // 0 is fine: earned credits fund banner/text
|
|
const b = await readBody(req);
|
|
if (!MEMBER_AD_TYPES.includes(String(b.type || ''))) return json(res, 400, { error: 'LinkSpin runs banner, text and login ads.' });
|
|
if (b.audience && !audiences.owns(s.email, b.audience)) return json(res, 400, { error: 'That audience is not one of yours.' }); // Marty 2026-09-29: the three formats members buy
|
|
{ const ck = await adChecks(String(b.type || ''), { targetUrl: b.targetUrl, imageUrl: b.imageUrl, size: b.size }); if (ck.error) return json(res, 400, { error: ck.error }); } // frame check (banner/text views frame the target) + banner image check, shared with edits
|
|
// charge the best-funded of the member's positions (main + Qualified Start
|
|
// wallets). A campaign burns from one member id, so the budget must fit inside it.
|
|
const ids = (await myMemberIds(s)).ids;
|
|
const pool = await ads.balances(ids, s.email);
|
|
const fundId = pool.best.memberId || memberId;
|
|
const earnedNow = String(b.type) !== 'login' ? pool.earned : 0;
|
|
const budget = Math.floor(Number(b.budget) || 0);
|
|
if (String(b.type) === 'login' && pool.per.length > 1 && budget > pool.best.avail + pool.credited && budget <= pool.total)
|
|
return json(res, 400, { error: 'Nothing was charged. A login-ad slot costs ' + budget.toLocaleString('en-US') + ' purchased credits and is paid from ONE position. Your credits are spread across ' + pool.per.length + ' positions (' + pool.per.map(x => '#' + x.memberId + ': ' + x.avail.toLocaleString('en-US')).join(', ') + ' free), so none of them holds ' + budget.toLocaleString('en-US') + ' on its own. Buy a package on one position to bring it to ' + budget.toLocaleString('en-US') + ', or let a running campaign on it finish, then try again.', loginFunds: true });
|
|
if (pool.per.length > 1 && budget > pool.best.avail + pool.credited + earnedNow && budget <= pool.total + earnedNow)
|
|
return json(res, 400, { error:'Your credits are spread across ' + pool.per.length + ' positions and one campaign spends from one of them. The largest single position holds ' + pool.best.avail + ' credits: set the budget to that or less, or run two campaigns.' });
|
|
const r = await ads.createCampaign(s.email, fundId, b, ids);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// edit a campaign's link, creative or name (Orlando, 2026-10-18): owner only, the create checks, first edit free
|
|
m = /^\/api\/my\/campaigns\/(\d+)\/edit$/.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 = await editAd(m[1], b, { owner: s.email, ids: (await myMemberIds(s)).ids });
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/campaigns\/(\d+)\/topup$/.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 memberId = await auth.refreshMemberId(s);
|
|
const b = await readBody(req);
|
|
const r = await ads.topUpCampaign(s.email, memberId, m[1], b.credits);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/campaigns\/(\d+)\/cancel-reservation$/.exec(p); // a queued login slot: cancel before start = full refund
|
|
if (m && req.method === 'POST') {
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const r = await ads.cancelLoginReservation(s.email, m[1]);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/my\/campaigns\/(\d+)\/(pause|resume)$/.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 r = await ads.setStatus(s.email, m[1], m[2] === 'pause' ? 'paused' : 'active');
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
|
|
// -- admin portal: email magic-code sign-in, allowlisted to ADMIN_EMAIL
|
|
if (p === '/api/admin/auth/start' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
const e = String(b.email || '').trim().toLowerCase();
|
|
if (!ADMIN_EMAIL) return json(res, 503, { error: 'ADMIN_EMAIL is not set on the server.' });
|
|
if (!e || e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' });
|
|
const k = 'admin:' + e;
|
|
const prev = emailCodes.get(k);
|
|
if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' });
|
|
const code = String(Math.floor(100000 + Math.random() * 900000));
|
|
emailCodes.set(k, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 });
|
|
if (mailer.hasKey()) {
|
|
try { await mailer.sendCode(e, code); } catch (err) {
|
|
console.error('admin sendCode failed', err.message);
|
|
return json(res, 502, { error: 'Could not send the email. Try again in a minute.' });
|
|
}
|
|
return json(res, 200, { ok: true, sent: true });
|
|
}
|
|
if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code });
|
|
return json(res, 503, { error: 'Email sign-in is not configured yet.' });
|
|
}
|
|
if (p === '/api/admin/auth/verify' && req.method === 'POST') {
|
|
const b = await readBody(req);
|
|
const e = String(b.email || '').trim().toLowerCase();
|
|
const k = 'admin:' + e;
|
|
const rec = emailCodes.get(k);
|
|
if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' });
|
|
rec.tries += 1;
|
|
if (rec.tries > 6) { emailCodes.delete(k); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); }
|
|
if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' });
|
|
emailCodes.delete(k);
|
|
if (e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' });
|
|
const token = mintAdminSession(e);
|
|
return json(res, 200, { ok: true, email: e }, { 'Set-Cookie': adminCookie(token) });
|
|
}
|
|
if (p === '/api/admin/auth/logout' && req.method === 'POST') {
|
|
dropAdminSession(req);
|
|
return json(res, 200, { ok: true }, { 'Set-Cookie': clearAdminCookie() });
|
|
}
|
|
if (p === '/api/admin/me' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 200, { admin: false });
|
|
return json(res, 200, { admin: true, email: ADMIN_EMAIL });
|
|
}
|
|
if (p === '/api/admin/overview' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const camps = await ads.adminList();
|
|
const byStatus = {}, byType = {};
|
|
for (const c of camps) { byStatus[c.status] = (byStatus[c.status] || 0) + 1; byType[c.type] = (byType[c.type] || 0) + 1; }
|
|
let memberCount = null; try { memberCount = await chain.memberCount(); } catch (e) {}
|
|
const cc = chain.getConfig();
|
|
return json(res, 200, { accounts: await accounts.count(), memberCount, campaigns: camps.length,
|
|
house: camps.filter(c => c.house).length, byStatus, byType,
|
|
openReports: await reports.openCount(), pendingBurns: (await ads.pendingBurns()).length,
|
|
followups: await drip.stats(),
|
|
chain: { contract: cc.contract, chainId: cc.chainId, chainName: cc.chainName, explorer: cc.explorer },
|
|
site: siteConfig(), rates: ads.rates() });
|
|
}
|
|
if (p === '/api/admin/members' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const members = await accounts.listAll(500);
|
|
// resolve each sponsor token (username, share code or member #) to the sponsor's name
|
|
const byTok = {};
|
|
for (const m of members) for (const t of [m.username, m.code, m.memberId ? String(m.memberId) : null]) if (t) byTok[String(t).toLowerCase()] = m;
|
|
for (const m of members) {
|
|
const t = String(m.sponsorRef || '').toLowerCase();
|
|
const sp = t ? byTok[t] : null;
|
|
m.sponsorName = sp ? (sp.username ? '@' + sp.username : (sp.memberId ? 'member #' + sp.memberId : sp.email)) : null;
|
|
m.sponsorVia = sp ? (t === String(sp.username || '').toLowerCase() ? 'username' : t === String(sp.code || '').toLowerCase() ? 'code' : 'member #') : (t ? 'unresolved' : '');
|
|
}
|
|
for (const m of members) { try { const ps = await accounts.positions(m.email); m.positions = ps.length; m.positionIds = ps.map(p => p.memberId).filter(Boolean); } catch (e) { m.positions = 0; } }
|
|
return json(res, 200, { members });
|
|
}
|
|
if (p === '/api/admin/members' && req.method === 'PATCH') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
if (!b.email) return json(res, 400, { error: 'Which member?' });
|
|
const r = await follow.setDeliberate(b.email, b.sponsorRef, 'admin', 'admin members table'); // deliberate: follows to InstantAdPay until bound
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/campaigns' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { campaigns: await ads.adminList(), rates: ads.rates(), bannerSizes: ads.bannerSizes(), houseOwner: ads.HOUSE_OWNER });
|
|
}
|
|
if (p === '/api/admin/campaigns' && req.method === 'POST') { // free house ad
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
{ const ck = await adChecks(String(b.type || ''), { targetUrl: b.targetUrl, imageUrl: b.imageUrl, size: b.size }); if (ck.error) return json(res, 400, { error: ck.error }); }
|
|
const r = await ads.createHouseCampaign(b);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/admin\/campaigns\/(\d+)\/edit$/.exec(p); // any campaign, free, never uses up the member's free edit
|
|
if (m && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const r = await editAd(m[1], await readBody(req), { admin: true });
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/login-queue' && req.method === 'GET') { // the paid login-slot line, oldest first
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { queue: await ads.loginQueue(), slots: await ads.loginSlots() });
|
|
}
|
|
m = /^\/api\/admin\/campaigns\/(\d+)\/cancel-reservation$/.exec(p); // admin cancel + full refund of a queued login slot
|
|
if (m && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const r = await ads.cancelLoginReservation(null, m[1], { admin: true });
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
m = /^\/api\/admin\/campaigns\/(\d+)\/(pause|resume)$/.exec(p);
|
|
if (m && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const r = await ads.adminSetStatus(m[1], m[2] === 'pause' ? 'paused' : 'active');
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/audit' && req.method === 'GET') { // counters reconciled against delivery logs
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, await audit.run());
|
|
}
|
|
if (p === '/api/admin/reports' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { reports: await reports.list(200) });
|
|
}
|
|
m = /^\/api\/admin\/reports\/(\d+)\/resolve$/.exec(p);
|
|
if (m && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, await reports.resolve(m[1]));
|
|
}
|
|
if (p === '/api/admin/upload' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return handleUpload(req, res, 'admin');
|
|
}
|
|
if (p === '/api/admin/rates' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { rates: ads.rates() });
|
|
}
|
|
if (p === '/api/admin/drip' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { sequence: drip.sequence(), defaults: drip.DEFAULT_SEQUENCE, stats: await drip.stats(), mailReady: mailer.hasKey() });
|
|
}
|
|
if (p === '/api/admin/drip' && req.method === 'PATCH') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const r = b.reset ? drip.resetSequence() : drip.setSequence(b.sequence);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/drip/test' && req.method === 'POST') { // send one step to the admin inbox
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
if (!ADMIN_EMAIL) return json(res, 400, { error: 'ADMIN_EMAIL is not set.' });
|
|
if (!mailer.hasKey()) return json(res, 400, { error: 'No mail key on the server.' });
|
|
try { const r = await drip.sendStep(ADMIN_EMAIL, Number(b.step) || 0, ADMIN_EMAIL); return json(res, r.error ? 400 : 200, r); }
|
|
catch (e) { return json(res, 502, { error: 'Send failed: ' + e.message }); }
|
|
}
|
|
// wall fallback ads: shown in wall positions a member has not earned or filled, when no upline banner exists
|
|
if (p === '/api/admin/wall-ads' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
let saved = null; try { saved = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); } catch (e) {}
|
|
return json(res, 200, { ads: Array.isArray(saved) ? saved : [], defaults: getAdminWallAds(), usingDefaults: !Array.isArray(saved) || !saved.length });
|
|
}
|
|
if (p === '/api/admin/wall-ads' && req.method === 'PATCH') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const src = Array.isArray(b.ads) ? b.ads.slice(0, 20) : [];
|
|
const out = [];
|
|
for (const o of src) {
|
|
const name = String((o && o.name) || '').trim().slice(0, 60);
|
|
const targetUrl = String((o && o.targetUrl) || '').trim();
|
|
const bannerUrl = String((o && o.bannerUrl) || '').trim();
|
|
if (!targetUrl) continue;
|
|
if (!/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Every wall ad needs an https:// link (' + (name || targetUrl) + ').' });
|
|
if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL (' + (name || targetUrl) + ').' });
|
|
out.push({ name: name || 'LinkSpin', targetUrl, bannerUrl: bannerUrl || null });
|
|
}
|
|
const file = path.join(DATA_DIR, 'admin-wall-ads.json');
|
|
if (out.length) fs.writeFileSync(file, JSON.stringify(out, null, 2)); else { try { fs.unlinkSync(file); } catch (e) {} }
|
|
return json(res, 200, { ok: true, ads: out, usingDefaults: !out.length });
|
|
}
|
|
// -- growth snapshot: preview the post, or send it now
|
|
if (p === '/api/admin/snapshot' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { text: await snapshot.preview() });
|
|
}
|
|
if (p === '/api/admin/snapshot/send' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
let target = ''; try { target = String(((await readBody(req)) || {}).target || '').trim(); } catch (e) {}
|
|
const r = target ? await snapshot.postTo(target) : await snapshot.post(); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
// -- level-4 override (2026-10-23): ?week=YYYY-MM-DD (any day of the week) or ?from=&to= (ms); rows=1 adds every purchase.
|
|
// Carries the week's payout status and the payer state; pay-now and resolve work only while the live payer is ready.
|
|
if (p === '/api/admin/override' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const from = Number(u.searchParams.get('from')), to = Number(u.searchParams.get('to'));
|
|
const r = from && to ? await override.report(from, to) : await override.week(u.searchParams.get('week') || '');
|
|
if (u.searchParams.get('rows') !== '1') delete r.rows;
|
|
r.payer = await override.payerStatus().catch(e => ({ error: e.message }));
|
|
r.dueWeeks = override.dueWeeks(true).slice(-8).map(w => override.weekStatus(w));
|
|
return json(res, 200, r, { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/admin/override/pay' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const live = override.liveState(); if (!live.ready) return json(res, 400, { error: 'The payer is off: ' + live.why.join('; ') });
|
|
const b = await readBody(req); const wk = /^\d{4}-\d{2}-\d{2}$/.test(String(b.week || '')) ? String(b.week) : '';
|
|
return json(res, 200, await override.payDue({ force: true, week: wk || undefined }));
|
|
}
|
|
if (p === '/api/admin/override/resolve' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const r = await override.resolve(String(b.week || ''), Number(b.memberId), String(b.action || ''), String(b.tx || ''));
|
|
return json(res, r && r.error ? 400 : 200, r);
|
|
}
|
|
// -- launch week (2026-11-05): Founder badge preview/grant + launch contest standings and the admin-approved POL payout
|
|
if (p === '/api/admin/launch-week' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, await launchweek.adminView(), { 'Cache-Control': 'no-store' });
|
|
}
|
|
if (p === '/api/admin/launch-week/founders' && req.method === 'POST') { // run the Founder grant now (refused before the launch moment)
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const r = await launchweek.grantFounders({ manual: true }); return json(res, r.error ? 400 : 200, Object.assign(r, { preview: await launchweek.founderPreview() }));
|
|
}
|
|
if (p === '/api/admin/launch-week/pay' && req.method === 'POST') { // pays the frozen places that match the list the admin confirmed; never twice
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req); if (!b || b.confirm !== true) return json(res, 400, { error: 'Send confirm: true with the places you saw.' });
|
|
const r = await launchweek.pay(b.places); return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/launch-week/resolve' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req); const r = await launchweek.resolve(Number(b.place), String(b.action || ''), String(b.tx || ''));
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/site' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { site: siteConfig() });
|
|
}
|
|
// -- profit and loss from the chain index: volume, platform fees, member payouts,
|
|
// pass-ups, per period (by block: ~43,200 Polygon blocks a day), plus the fee
|
|
// wallets' live balances and an admin-entered fixed monthly cost
|
|
if (p === '/api/admin/pnl' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const days = Math.max(0, Number(u.searchParams.get('days') || 30));
|
|
let latest = 0; try { latest = parseInt(await chain.rpc('eth_blockNumber', []), 16); } catch (e) {}
|
|
const fromBlock = days ? latest - Math.round(days * 43200) : 0;
|
|
const evs = chain.recentEvents(1e9).filter(e => !days || e.block >= fromBlock);
|
|
const sum = (list, f) => list.reduce((n, e) => n + BigInt(f(e) || '0'), 0n);
|
|
const purchases = evs.filter(e => e.type === 'Purchase');
|
|
const tier = evs.filter(e => e.type === 'TierPaid');
|
|
const admin = evs.filter(e => e.type === 'AdminPaid');
|
|
const passed = evs.filter(e => e.type === 'PassedUp');
|
|
const byTier = {};
|
|
for (const t of [1, 2, 3]) byTier[t] = sum(tier.filter(e => e.tier === t), e => e.amountWei).toString();
|
|
const byPkg = {};
|
|
for (const e of purchases) { const k = '$' + Math.round(e.priceCents / 100); byPkg[k] = (byPkg[k] || 0) + 1; }
|
|
let polUsd = 0; try { const cat = await chain.catalog(); const pk = (cat.products || cat).find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {}
|
|
const wallets = { feeA: '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', feeB: '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', engine: burner.status().address || null };
|
|
const balances = {};
|
|
for (const [k, a] of Object.entries(wallets)) { if (!a) continue; try { balances[k] = BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { balances[k] = null; } }
|
|
return json(res, 200, { days, fromBlock, latest, polUsd,
|
|
purchases: { count: purchases.length, volumeWei: sum(purchases, e => e.paidWei).toString(), usdCents: purchases.reduce((n, e) => n + (e.priceCents || 0), 0), byPackage: byPkg },
|
|
platformWei: sum(admin, e => e.amountWei).toString(), memberPayoutsWei: sum(tier, e => e.amountWei).toString(), byTier,
|
|
passedUp: { count: passed.length, unqualified: passed.filter(e => e.reason === 'unqualified').length, sendFailed: passed.filter(e => e.reason === 'send-failed').length },
|
|
wallets, balances, fixedMonthlyUsd: Number(siteConfig().pnlFixedMonthlyUsd) || 0, burner: burner.status() });
|
|
}
|
|
// -- Refuel Kit admin: kits as data (month, theme, five base images), placeholder art from public/banners, personalization preview
|
|
if (p === '/api/admin/kits' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, { kits: kit.listKits(), sizes: kit.ORDER }); }
|
|
if (p === '/api/admin/kits' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const r = kit.saveKit(await readBody(req)); return json(res, r.error ? 400 : 200, r); }
|
|
if (p === '/api/admin/kits/placeholder' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, kit.usePlaceholder(String(b.month || ''))); }
|
|
if (p === '/api/admin/kits/upload' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
let buf; try { buf = await readRaw(req, 3 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large (3 MB max).' }); }
|
|
const r = kit.uploadBase(String(u.searchParams.get('month') || ''), String(u.searchParams.get('size') || ''), buf, req.headers['content-type']);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/kits/preview' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const r = await kit.preview(String(u.searchParams.get('month') || ''), String(u.searchParams.get('size') || ''), String(u.searchParams.get('username') || 'yourname').replace(/[^a-z0-9_]/gi, '').slice(0, 24), u.searchParams.get('variant') === 'gif' ? 'gif' : 'still');
|
|
if (r.error) return json(res, 400, r);
|
|
res.writeHead(200, { 'Content-Type': { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[r.ext], 'Cache-Control': 'no-store' }); return fs.createReadStream(r.file).pipe(res);
|
|
}
|
|
if (p === '/api/admin/refuel' && req.method === 'GET') { // Monthly Refuel, LinkSpin side: switch, link to InstantAdPay, reports waiting to go
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, refuel.adminView());
|
|
}
|
|
if (p === '/api/admin/refuel/tick' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, await refuel.tick());
|
|
}
|
|
// -- the Refuel Kit (2026-10-24): personalized banners are public by URL, rendered only for entitled members
|
|
if (p.startsWith('/kitimg/') && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
const f = kit.servePath(p.slice(8)); if (!f) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
|
|
res.writeHead(200, { 'Content-Type': f.mime, 'Cache-Control': 'public, max-age=86400', 'Access-Control-Allow-Origin': '*' });
|
|
return req.method === 'HEAD' ? res.end() : fs.createReadStream(f.file).pipe(res);
|
|
}
|
|
if (p === '/api/my/kits' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
const mk = await kit.myKits(s.email);
|
|
if (mk && mk.on) { try { mk.spinRoom = await kitspin.room(s.email, bannerspin); } catch (e) { mk.spinRoom = null; } } // the panel pre-picks the sizes that fit the tier (2026-10-24)
|
|
return json(res, 200, mk);
|
|
}
|
|
if (p === '/api/my/kits/render' && 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 = await kit.renderFor(s.email, String(b.month || ''), String(b.size || ''), b.variant === 'gif' ? 'gif' : 'still');
|
|
return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, url: r.url, abs: r.abs, size: r.size, variant: r.variant, bytes: r.bytes });
|
|
}
|
|
// "Load into my Banner Spin": each Banner Spin size in the kit goes into one of the member's Banner Spins of that size with
|
|
// room, or a new one when the tier allows; the banner is the member's personalized file, the target their own link
|
|
if (p === '/api/my/kits/bannerspin' && 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 = await kitspin.load({ kit, bannerspin, content, uploadsDir: UPLOADS_DIR, email: s.email, month: String(b.month || ''), variant: b.variant, sizes: b.sizes });
|
|
return json(res, r.error ? (r.status || 400) : 200, r);
|
|
}
|
|
// -- the Engine Room panel (2026-10-24): LinkSpin's facts + InstantAdPay's facts and the streak (signed, cached a minute)
|
|
if (p === '/api/my/engine' && req.method === 'GET') {
|
|
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
if (!refuel.cfg().on) return json(res, 200, { on: false });
|
|
const [own, peer] = await Promise.all([engine.facts({ site: 'linkspin', adminMember, ads, coach, bannerspin, rotator, pages, convtrack }, s.email), engineFromIap(s.email, u.searchParams.get('fresh') === '1')]);
|
|
if (!peer || !peer.refuel) return json(res, 200, { on: true, error: 'InstantAdPay did not answer just now. Try again in a minute.' });
|
|
return json(res, 200, engine.build({ site: 'linkspin', refuel: peer.refuel, iap: peer.facts, ls: own, goal: peer.refuel.goal }));
|
|
}
|
|
if (p === '/api/my/engine/goal' && 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);
|
|
try { const r = await SF.peerPost(IAP_BASE(), '/api/partner/refuel/goal', { email: s.email, goal: b.goal }, 8000); iapEngineCache.delete(s.email); return json(res, 200, r); }
|
|
catch (e) { return json(res, 502, { error: 'InstantAdPay did not answer just now. Try again in a minute.' }); }
|
|
}
|
|
if (p === '/api/my/refuel' && req.method === 'GET') { // the member's Refuel card, from InstantAdPay's record ({ on:false } while switched off)
|
|
const s = await auth.fromRequest(req);
|
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
|
return json(res, 200, await refuel.status(s.email));
|
|
}
|
|
if (p === '/api/admin/refill' && req.method === 'GET') { // who was told their ads ran low or out, and what they did next
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, refill.stats());
|
|
}
|
|
if (p === '/api/admin/refill/reset' && req.method === 'POST') { // re-decide conversions under a corrected rule
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
return json(res, 200, refill.resetConversions(Array.isArray(b.kinds) ? b.kinds : null));
|
|
}
|
|
if (p === '/api/admin/refill/run' && req.method === 'POST') { // send the next batch now instead of waiting for the tick
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, await refill.tick());
|
|
}
|
|
if (p === '/api/admin/burner' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, burner.status());
|
|
}
|
|
if (p === '/api/admin/burner/run' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, await burner.tick());
|
|
}
|
|
|
|
// -- admin (Bearer ADMIN_PASSWORD, or the /admin portal session)
|
|
if (p === '/api/admin/burns' && req.method === 'GET') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
return json(res, 200, { pending: await ads.pendingBurns() });
|
|
}
|
|
if (p === '/api/admin/burns/mark' && req.method === 'POST') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const r = await ads.markBurned(b.id, b.tx);
|
|
return json(res, r.error ? 400 : 200, r);
|
|
}
|
|
if (p === '/api/admin/rates' && req.method === 'PATCH') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
return json(res, 200, { ok: true, rates: ads.setRates(b) });
|
|
}
|
|
|
|
if (p === '/api/admin/site' && req.method === 'PATCH') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const cur = siteConfig();
|
|
fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, b), null, 2));
|
|
return json(res, 200, { ok: true, site: siteConfig() });
|
|
}
|
|
if (p === '/api/admin/chain' && req.method === 'PATCH') {
|
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
|
const b = await readBody(req);
|
|
const file = path.join(DATA_DIR, 'config.json');
|
|
let cur = {}; try { cur = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) {}
|
|
fs.writeFileSync(file, JSON.stringify(Object.assign(cur, b), null, 2));
|
|
chain.reloadConfig();
|
|
return json(res, 200, { ok: true, config: chain.getConfig() });
|
|
}
|
|
|
|
// -- pages (HEAD answered like GET so link previewers and crawlers see 200; Node drops the body)
|
|
if (req.method === 'GET' || req.method === 'HEAD') {
|
|
if (p === '/') return sendFile(res, path.join(PUBLIC_DIR, 'index.html'));
|
|
if (p === '/ledger') return sendFile(res, path.join(PUBLIC_DIR, 'ledger.html'));
|
|
if (p === '/contract') return sendFile(res, path.join(PUBLIC_DIR, 'contract.html'));
|
|
if (p === '/conversion-tracking') return sendFile(res, path.join(PUBLIC_DIR, 'conversion-tracking.html')); // how to set up the conversion pixel, the member guide (2026-10-24)
|
|
if (p === '/refuel') return sendFile(res, path.join(PUBLIC_DIR, 'refuel.html')); // Fuel Your Offers: the Monthly Refuel member guide (2026-10-24)
|
|
if (p === '/terms') return sendFile(res, path.join(PUBLIC_DIR, 'terms.html'));
|
|
if (p === '/privacy') return sendFile(res, path.join(PUBLIC_DIR, 'privacy.html'));
|
|
if (p === '/disclaimer') return sendFile(res, path.join(PUBLIC_DIR, 'disclaimer.html'));
|
|
if (p === '/tools') return sendFile(res, path.join(PUBLIC_DIR, 'my.html')); // classic panes the control room lacks (More)
|
|
if (p === '/my') { // retired 2026-10-08: old links/emails/bookmarks land on the right control-room screen by #pane
|
|
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }));
|
|
return res.end('<!doctype html><html><head><meta charset="utf-8"><title>LinkSpin</title><meta name="robots" content="noindex"></head><body><script src="/assets/my-redirect.js?v=20261008a"></script><noscript><a href="/links">Open the control room</a></noscript></body></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 === '/conversions') return sendFile(res, path.join(PUBLIC_DIR, 'conversions.html')); // Control Room: conversion pixel goals + per-goal reports (2026-10-23)
|
|
if (p === '/pages') return sendFile(res, path.join(PUBLIC_DIR, 'pages.html'));
|
|
if (p === '/zones') return sendFile(res, path.join(PUBLIC_DIR, 'zones.html'));
|
|
if (p === '/sources') return sendFile(res, path.join(PUBLIC_DIR, 'sources.html')); // Control Room: traffic sources, network macros + postbacks (2026-10-12)
|
|
if (p === '/traffic-guide') return sendFile(res, path.join(PUBLIC_DIR, 'traffic-guide.html')); // which traffic for which offer (Marty 2026-10-28)
|
|
if (p === '/ads') return sendFile(res, path.join(PUBLIC_DIR, 'ads.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 === '/credits') return sendFile(res, path.join(PUBLIC_DIR, 'credits.html')); // Control Room: buy packages, link wallet, payouts on (2026-10-07)
|
|
if (p === '/help') return sendFile(res, path.join(PUBLIC_DIR, 'help.html')); // Control Room: Help, the member's support tickets (2026-10-16)
|
|
if (p === '/support' || /^\/support\/t\/[A-Za-z0-9_.-]{20,80}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'support.html')); // public form + private ticket link, open past the curtain
|
|
if (p === '/join') return serveJoinPage(res, '', '', null, []); // bare join: sponsor from the cookie if any (home-page CTAs)
|
|
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'));
|
|
if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12)
|
|
if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html')); // member guide: how earning works (2026-09-12)
|
|
// -- badge share page + image: /b/<username>/<key> (OG preview = the member's composed badge) (Marty, 2026-09-13)
|
|
m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3|founder)\.jpg$/.exec(p);
|
|
if (m) return sendFile(res, path.join(UPLOADS_DIR, 'badge-' + m[1] + '-' + m[2] + '.jpg'));
|
|
m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3|founder)$/i.exec(p);
|
|
if (m) {
|
|
const un = m[1].toLowerCase(), key = m[2];
|
|
const a = await accounts.byUsername(un);
|
|
const file = path.join(UPLOADS_DIR, 'badge-' + un + '-' + key + '.jpg');
|
|
if (!a || !fs.existsSync(file) || !(await badgesHeld(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
|
|
const [label, sub] = BADGE_META[key];
|
|
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
const url = SITE_URL + '/b/' + un + '/' + key, img = SITE_URL + '/badge-img/' + un + '/' + key + '.jpg';
|
|
const title = '@' + un + ' unlocked ' + label + ' on LinkSpin';
|
|
const desc = label + ': ' + sub + '. LinkSpin pays sponsors in the same transaction, on-chain. Join @' + un + '\u2019s line free.';
|
|
const html = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + esc(title) + '</title>'
|
|
+ '<meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="' + url + '"><meta name="robots" content="noindex">'
|
|
+ '<meta property="og:type" content="website"><meta property="og:site_name" content="LinkSpin"><meta property="og:title" content="' + esc(title) + '"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:url" content="' + url + '"><meta property="og:image" content="' + img + '"><meta property="og:image:width" content="1024"><meta property="og:image:height" content="1024">'
|
|
+ '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' + esc(title) + '"><meta name="twitter:description" content="' + esc(desc) + '"><meta name="twitter:image" content="' + img + '">'
|
|
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=ls20261101t">'
|
|
+ '<style>.bp{max-width:560px;text-align:center;padding:40px 16px 60px}.bp img{width:100%;max-width:520px;border-radius:18px;border:1px solid var(--line);box-shadow:0 20px 60px rgba(0,0,0,.45)}.bp h1{font-size:clamp(24px,5vw,34px);margin:22px 0 8px}.bp p{color:var(--muted);max-width:44ch;margin:0 auto 20px}</style></head>'
|
|
+ '<body><div class="wrap bp"><img src="' + img + '" alt="' + esc(label) + ' badge for @' + esc(un) + '"><h1>@' + esc(un) + ' unlocked <em>' + label + '</em></h1><p>' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On LinkSpin every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.</p>'
|
|
+ '<a class="btn" href="/join/' + esc(un) + '">Join @' + esc(un) + '\u2019s line free</a><p class="small" style="margin-top:26px">Advertising with a performance referral program. Not an investment; no income is guaranteed.</p></div>'
|
|
+ '<script src="/assets/common.js?v=20261101t"></script><script src="/assets/blog-page.js?v=20260912a"></script></body></html>';
|
|
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }));
|
|
return res.end(html);
|
|
}
|
|
// -- blog: server-rendered so crawlers get real HTML + metadata (Marty, 2026-09-12)
|
|
if (p === '/blog' || p === '/blog/' || /^\/blog\/page\/\d+$/.test(p) || /^\/blog\/tag\/[^/]+$/.test(p)) {
|
|
const posts = await blog.listPublished();
|
|
const pg = (m = /^\/blog\/page\/(\d+)$/.exec(p)) ? Number(m[1]) : 1;
|
|
const tag = (m = /^\/blog\/tag\/([^/]+)$/.exec(p)) ? decodeURIComponent(m[1]).toLowerCase() : null;
|
|
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }));
|
|
return res.end(blog.renderIndex(posts, pg, tag));
|
|
}
|
|
m = /^\/handout\/([a-z0-9_]{3,20})$/i.exec(p);
|
|
if (m) { const h = await toolkit.handout(m[1].toLowerCase()); if (!h) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); return res.end(h); }
|
|
if (p === '/leaderboard') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=60' })); return res.end(await leaderboard.renderPage()); }
|
|
if (p === '/whats-new') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=120' })); return res.end(releases.renderPage()); }
|
|
if (p === '/blog/feed.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/rss+xml; charset=utf-8', 'Cache-Control': 'public, max-age=900' })); return res.end(blog.rss(await blog.listPublished())); }
|
|
if (p === '/sitemap.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.sitemap(await blog.listPublished())); }
|
|
if (p === '/robots.txt') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.robots()); }
|
|
m = /^\/blog\/([a-z0-9-]{1,80})$/.exec(p);
|
|
if (m) {
|
|
const post = await blog.get(m[1]);
|
|
const preview = !!(post && post.status !== 'published' && isAdmin(req)); // admins can open a draft at its real URL
|
|
if (!post || (post.status !== 'published' && !preview)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8' })); return res.end(blog.renderIndex(await blog.listPublished(), 1, null).replace('<title>', '<title>Not found | ')); }
|
|
if (!preview && req.method === 'GET') blog.bumpViews(post.slug);
|
|
const related = blog.relatedFor(post, await blog.listPublished());
|
|
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': preview ? 'no-store' : 'public, max-age=300' }));
|
|
return res.end(blog.renderPost(post, related));
|
|
}
|
|
if (p === '/wallets') return sendFile(res, path.join(PUBLIC_DIR, 'wallets.html'));
|
|
if (p === '/launch') return sendFile(res, path.join(PUBLIC_DIR, 'launch.html'));
|
|
if (/^\/view\/[a-f0-9]{32}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'view.html'));
|
|
m = /^\/uploads\/([a-z0-9]{24}\.(?:png|jpg|webp|gif|mp4|webm))$/.exec(p);
|
|
if (m) return sendFile(res, path.join(UPLOADS_DIR, m[1]));
|
|
if (/^\/tx\/0x[0-9a-fA-F]{64}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'tx.html'));
|
|
m = /^\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p);
|
|
if (m) { // server-inject per-member OG tags so shared bio links preview correctly (crawlers don't run JS)
|
|
try {
|
|
const tok = m[1].toLowerCase();
|
|
let a = await accounts.byUsername(tok); if (!a) a = await accounts.byCode(tok);
|
|
// a deleted or never-seen name is a real 404, never a bare "Banner wall" page at 200 (a soft 404 Google kept indexed, 2026-10-30)
|
|
if (!a) {
|
|
const nf = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>No wall under that name | LinkSpin</title><meta name="robots" content="noindex"><link rel="icon" type="image/png" href="/logo-icon.png">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=ls20261101t"></head><body><section><div class="wrap" style="max-width:720px;text-align:center;padding:60px 0"><h1>No wall under that name</h1><p class="muted">This member page does not exist or was removed.</p><p><a class="btn" href="/">Go to LinkSpin</a></p></div></section></body></html>';
|
|
res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Robots-Tag': 'noindex' }));
|
|
return res.end(nf);
|
|
}
|
|
let html = fs.readFileSync(path.join(PUBLIC_DIR, 'wall.html'), 'utf8');
|
|
if (a) {
|
|
const nm = a.username ? '@' + a.username : 'member #' + (a.memberId || 0);
|
|
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
const bought = await hasBought(a); // only a paying member's avatar becomes the share image
|
|
const title = nm + '\u2019s ad wall | LinkSpin';
|
|
const desc = esc(wallDescription(nm)); // fixed site sentence, never the bio (indexed snippet stays ours)
|
|
const img = bought && a.avatarUrl && /^https:/.test(a.avatarUrl) ? a.avatarUrl : SITE_URL + '/banners/linkspin-og-1200x630.png';
|
|
const url = SITE_URL + '/wall/' + (a.username || a.code);
|
|
const og = [
|
|
'<meta property="og:type" content="profile">',
|
|
'<meta property="og:site_name" content="LinkSpin">',
|
|
'<meta property="og:url" content="' + url + '">',
|
|
'<meta property="og:title" content="' + esc(title) + '">',
|
|
'<meta property="og:description" content="' + desc + '">',
|
|
'<meta property="og:image" content="' + esc(img) + '">',
|
|
'<meta name="twitter:card" content="summary_large_image">',
|
|
'<meta name="twitter:title" content="' + esc(title) + '">',
|
|
'<meta name="twitter:description" content="' + desc + '">',
|
|
'<meta name="twitter:image" content="' + esc(img) + '">',
|
|
'<meta name="description" content="' + desc + '">',
|
|
'<link rel="canonical" href="' + url + '">'
|
|
].join('\n');
|
|
html = html.replace('<title>Banner wall | LinkSpin</title>', '<title>' + esc(title) + '</title>').replace('<!--OG-->', og);
|
|
}
|
|
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' }));
|
|
return res.end(html);
|
|
} catch (e) { return sendFile(res, path.join(PUBLIC_DIR, 'wall.html')); }
|
|
}
|
|
const safe = path.normalize(p).replace(/^([.\\/])+/, '');
|
|
const file = path.join(PUBLIC_DIR, safe);
|
|
if (file.startsWith(PUBLIC_DIR) && fs.existsSync(file) && fs.statSync(file).isFile()) return sendFile(res, file);
|
|
}
|
|
|
|
res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' }));
|
|
res.end('Not found');
|
|
} catch (e) {
|
|
console.error('request error', req.url, e.message);
|
|
try { json(res, 500, { error: 'server error' }); } catch (_) {}
|
|
}
|
|
});
|
|
boot().then(() => {
|
|
server.listen(PORT, () => console.log(`LinkSpin site on :${PORT} — chain: ${chain.getConfig().chainName} — store: ${db.enabled() ? 'MySQL' : 'volume JSON'}`
|
|
+ ` — outbound mail: ${OUTBOUND_MAIL ? 'ON' : 'OFF'} — sign-ups: ${SIGNUPS_OPEN ? 'open' : 'CLOSED'}`));
|
|
}).catch(e => { console.error('boot failed:', e.message); process.exit(1); });
|