// 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 netsites = require('./netsites'); // footer network list from the hub (2026-11-14 trust pack) const netdeals = require('./netdeals'); // Network Weekend ribbon feed from the hub (2026-11-17) const sendy = require('./sendy'); const { URL } = require('url'); const chain = require('./chain'); const auth = require('./auth'); const accounts = require('./accounts'); const networksso = require('./networksso'); // network sign-in with InstantAdPay (2026-11-12, Marty approved): see networksso.js 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 netkb = require('./netkb'); // the shared network KB on the hub; suggest() for the Help screen (2026-11-16) 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 tankready = require('./tankready'); // holding-tank readiness from the network hub (2026-11-18): entry reason, stage, heat, last action on the tank cards. No mail. 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 loginClock = require('./loginadclock'); // login ads on a clock, not only at sign-in (Marty 2026-11-15): see loginadclock.js const erase = require('./erase'); // member erase (2026-11-15, LS-1021): POST /api/admin/erase + the hub's member.erased event const adwriter = require('./hubadwriter'); // the network AI ad writer, asked through the hub (2026-11-17): text ads + page headlines const hubsync = require('./hubsync'); // network hub link, inert unless HUB_ENABLED=1 (2026-11-12) 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 housespins = require('./housespins'); // admin: house Banner Spins on the admin's own account, no member sign-in (2026-11-16) const adminaudit = require('./adminaudit'); // admin action log: who, what, when (2026-11-16) 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/ (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/ 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'); require('./safefs').install(DATA_DIR); // every .json data file is written atomically (2026-11-13 rotator.json loss) const docstore = require('./docstore'); docstore.install(DATA_DIR); // data documents live in MySQL when DOCSTORE_URL is set (2026-11-13, database is the standard) 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 = {}; if (!process.env.DOCSTORE_URL) { try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } } // with MySQL: loaded right after docstore.init 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. // Video Spin (2026-11-22). Limits by tool tier, mirroring Banner Spin. The picker and the play counts come from Video App Income over // signed calls: X-Ls-Ts + X-Ls-Sig = HMAC-SHA256(NETCONV_SECRET_VAI, 'vspin.v1.' + ts + '\n' + raw). VAI_URL defaults to the live site. const VS_LIMITS = { free: { spins: 0, videos: 0 }, starter: { spins: 2, videos: 5 }, builder: { spins: 5, videos: 15 }, leader: { spins: 10, videos: 25 } }; const VAI_URL = () => String(process.env.VAI_URL || 'https://videoappincome.com').trim().replace(/\/+$/, ''); const vsSecret = () => String(process.env.NETCONV_SECRET_VAI || '').trim(); const vsOn = () => vsSecret().length >= 32; async function vaiCall(op, body) { const raw = JSON.stringify(body), ts = String(Date.now()); const r = await fetch(VAI_URL() + '/api/partner/ls/' + op, { method: 'POST', headers: { 'content-type': 'application/json', 'x-ls-ts': ts, 'x-ls-sig': crypto.createHmac('sha256', vsSecret()).update('vspin.v1.' + ts + '\n' + raw).digest('hex') }, body: raw, signal: AbortSignal.timeout(12000) }); return { s: r.status, j: await r.json().catch(() => ({})) }; } // the video's page: the address Video App Income gives for it when it is a plain watch address for that id, else the known one const vsWatchUrl = x => { const u = String((x && x.url) || ''), id = String((x && x.id) || ''); return u.startsWith('http') && !u.includes('?') && !u.includes('#') && u.endsWith('/watch/' + id) && u.length < 200 && (!IS_PROD || u.startsWith('https://socialtube.club/')) ? u : 'https://socialtube.club/watch/' + id; }; async function vsCreate(email, name) { // -> { code, body } if (!vsOn()) return { code: 503, body: { error: 'Video Spins are not switched on yet.' } }; const t = await toolTier(email), lim = VS_LIMITS[t.key] || VS_LIMITS.free, have = (await rotator.list(email)).filter(x => x.kind === 'video').length; if (!lim.spins) return { code: 400, body: { error: 'Video Spins start at the Starter tier (any package of your own).', tier: t } }; if (have >= lim.spins) return { code: 400, body: { error: 'Your ' + t.label + ' tier holds ' + lim.spins + ' Video Spins and you have ' + have + '.', tier: t } }; let mine = { member: null }; try { mine = await vsMine(email); } catch (e) {} const ref = mine.member ? mine.member.username || mine.member.id : ''; const r = await rotator.create(email, { name, fallback: 'https://socialtube.club/' + (ref ? '?ref=' + encodeURIComponent(ref) : ''), kind: 'video', vref: ref }); return { code: r.error ? 400 : 200, body: r }; } async function vsAdd(email, id, b) { // b: { ids: [own video ids], link: a Social Tube video address } -> { code, body } if (!vsOn()) return { code: 503, body: { error: 'Video Spins are not switched on yet.' } }; const rot = (await rotator.list(email)).find(x => x.id === Number(id) && x.kind === 'video'); if (!rot) return { code: 404, body: { error: 'No such Video Spin.' } }; const t = await toolTier(email), lim = VS_LIMITS[t.key] || VS_LIMITS.free, raw = rotator._json.state().rotations.find(x => x.id === rot.id); const picks = []; // { id, title, owner, poster, url } try { const ids = (Array.isArray(b.ids) ? b.ids : []).map(String).filter(x => /^[A-Za-z0-9]{1,20}$/.test(x)).slice(0, 25); if (ids.length) { const mine = await vsMine(email); for (const vid of ids) { const vd = mine.videos.find(x => x.id === vid); if (vd) picks.push(vd); } if (picks.length !== ids.length) return { code: 400, body: { error: 'One of those is not a video of yours on Social Tube. Reload and pick again.' } }; } const link = String(b.link || '').trim(); if (link) { const x = await vaiCall('video', { link }); if (x.s !== 200 || !x.j.video) return { code: 400, body: { error: (x.j && x.j.error) || 'That video link could not be checked.' } }; picks.push(x.j.video); } } catch (e) { return { code: 502, body: { error: 'Video App Income is not answering right now. Nothing was added. Try again in a minute.' } }; } if (!picks.length) return { code: 400, body: { error: 'Pick at least one video, or paste a Social Tube video link.' } }; const fresh = picks.filter((x, i) => !rot.destinations.some(d => d.vid === x.id) && picks.findIndex(y => y.id === x.id) === i); if (!fresh.length) return { code: 400, body: { error: picks.length === 1 ? 'That video is already in this Video Spin.' : 'Those videos are already in this Video Spin.' } }; if (rot.destinations.length + fresh.length > lim.videos) return { code: 400, body: { error: 'Your ' + t.label + ' tier holds ' + lim.videos + ' videos in one Video Spin. This one has ' + rot.destinations.length + '.', tier: t } }; let out = null; for (const x of fresh) { out = await rotator.addDest(email, rot.id, { url: vsWatchUrl(x) + '?vs=' + rot.code + (raw && raw.vref ? '&ref=' + encodeURIComponent(raw.vref) : ''), label: String(x.title || 'Video').slice(0, 60), weight: 10 }, { video: x }); if (out.error) return { code: 400, body: out }; } return { code: 200, body: { ok: true, added: fresh.length, rotation: out.rotation } }; } const vsMineCache = new Map(); // email -> { ts, v }: the member's own Social Tube videos, kept one minute async function vsMine(email) { const e = String(email || '').toLowerCase(), hit = vsMineCache.get(e); if (hit && Date.now() - hit.ts < 60000) return hit.v; if (!vsOn()) return { member: null, videos: [] }; let username = ''; try { const a = await accounts.byEmail(e); username = (a && a.username) || ''; } catch (er) {} const x = await vaiCall('videos', { email: e, username }); if (x.s !== 200) throw new Error('vai ' + x.s); const v = { member: x.j.member || null, videos: Array.isArray(x.j.videos) ? x.j.videos : [] }; vsMineCache.set(e, { ts: Date.now(), v }); return v; } 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:' | 'em:' | 'tk:' -> [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/): 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(/' + '' // keeps ?v= so shares stay on the angle + '' + ''; html = html.replace(/[^<]*<\/title>/, '<title>' + escA(title) + ' | LinkSpin' + og); if (ang) html = html.replace('', ''); // 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) await docstore.init({ splits: [{ doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }] }); // before any module reads its data process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); }); if (process.env.DOCSTORE_URL) { try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } } 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)); hubsync.onChain(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 }); // network sign-in (2026-11-12): a member signed in on InstantAdPay arrives here signed in, and the other way round. Member // sessions only (the admin portal is never shared). An email that is not here yet (the 2-minute sync has not run) or is not // let in (LS_TESTERS) gets the normal email-code sign-in with the email filled in; nothing is created by the network sign-in. networksso.init({ self: 'linkspin', peer: 'iap', peerBase: IAP_BASE, isProd: IS_PROD, dataDir: DATA_DIR, db, defaultPath: '/ads', wallets: { bannerline: () => String(process.env.BL_URL || 'https://downlinebanners.com').replace(/\/+$/, ''), // Downline Banners by wallet (2026-11-13) vbb: () => String(process.env.VBB_URL || 'https://viralbannerblitz.com').replace(/\/+$/, ''), // Viral Banner Blitz by wallet (2026-11-14) viraladblitz: () => String(process.env.VAB_URL || 'https://viraladblitz.com').replace(/\/+$/, ''), // ViralAdBlitz by wallet (2026-11-15; VAB_URL = staging host until the domain switch) downlinehydra: () => String(process.env.DH_URL || 'https://downlinehydra.com').replace(/\/+$/, ''), // DownlineHydra (2026-11-15; DH_URL = https://dh.saasy.top until the domain switch) fivex: () => String(process.env.FIVEX_URL || 'https://5xyourteam.com').replace(/\/+$/, '') }, // 5xYourTeam by wallet (2026-11-15: it asked with r=fivex and was answered as if InstantAdPay asked) wallet: async s => { const a = await accounts.byEmail(s.email); const addr = String(s.address || (a && a.address) || '').toLowerCase(); return addr ? { address: addr, name: '' } : null; }, member: async req => { // a wallet sign-in carries the address, not the email: find the account that owns the wallet (2026-11-13) const s = await auth.fromRequest(req); if (!s) return null; let email = s.email || null; if (!email && s.address) { try { const a = await accounts.byAddress(s.address); if (a && a.email) email = a.email; } catch (e) {} } return email ? Object.assign({}, s, { email }) : null; }, accept: async email => { const a = await accounts.byEmail(email); if (!a) return { fallback: 'no account here yet' }; if (!isTester(email, a)) return { fallback: 'not on the tester list' }; return { ok: true }; }, signIn: async email => { // the same session the email code makes (4 hours, same rights) const a = await accounts.byEmail(email); let memberId = 0; if (a && a.address) { try { memberId = await chain.memberIdByAccount(a.address); } catch (e) {} } return auth.sessionCookie(await auth.mintSession({ email: a.email, address: a.address || null, memberId })); }, landing: to => to, signinPath: to => (to === '/' ? '/ads' : to) }); // every Control Room screen shows the sign-in itself accounts.init({ dataDir: DATA_DIR }); ads.init({ dataDir: DATA_DIR, chain }); loginClock.init({ url: process.env.DATABASE_URL || process.env.DOCSTORE_URL, hours: () => siteConfig().loginAdEveryHours }); 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 = '

' + text.replace(/&/g, '&').replace(//g, '>').replace(/(https?:\/\/[^\s]+)/g, '$1').split('\n\n').join('

') + '

'; 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 (hubsync.isQuiet(email)) { console.log('activation skipped: wallet filled from a network hub event (quiet)'); return; } 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); hubsync.touch(email); }); hubsync.init({ dataDir: DATA_DIR, accounts, registry, carry, follow: followStore, chain, erase, erased: email => erase.isErased(email), endSessions: (email, wallet) => auth.endSessions(email, wallet) }); setInterval(() => hubsync.tick().catch(e => console.error('hubsync', e.message)), 30 * 1000); // touch/tick do nothing while HUB_ENABLED is off 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 }); adminaudit.init({ dataDir: DATA_DIR }); housespins.init({ bannerspin, houseAccounts: () => [ADMIN_EMAIL, String(process.env.NETWORK_LINKS_OWNER || '').trim().toLowerCase()].filter(Boolean), host: want => { const hs = domains.hosts().map(d => d.host); const w = String(want || '').trim().toLowerCase(); return hs.includes(w) ? w : (hs[0] || SITE_HOST); } }); 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; } }); // network links + one traffic source per network site on the admin account (netlinks.js, 2026-11-14), made once when missing setTimeout(() => { try { console.log('network links', JSON.stringify(require('./netlinks').ensure({ owner: process.env.NETWORK_LINKS_OWNER || ADMIN_EMAIL, rotator, sources }))); } catch (e) { console.error('network links', e.message); } }, 3000); 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 }); // member erase (erase.js, 2026-11-15): the modules that keep a document in memory are scrubbed through their live copy, the rest through docstore erase.init({ dataDir: DATA_DIR, accounts, ads, rotator, docstore, owners: { 'accounts.json': accounts._json, 'audiences.json': { state: audiences._state, save: audiences._save }, 'coach.json': coach._json, 'convtrack.json': { state: convtrack._state, save: convtrack._save }, 'earned.json': ads._earned, 'hubsync.json': { state: hubsync._state, save: hubsync._save }, 'iapsync.json': { state: iapsync._state, save: iapsync._save }, 'mail-intro.json': mailer._intro, 'postbacks.json': postbacks._json, 'registry.json': registry._json, 'rotator.json': rotator._json, 'sponsorfollow.json': { state: followStore._state, save: followStore._save } }, reload: {}, forget: [email => loginClock.forget(String(email || '').toLowerCase()), email => iapsync._forget(email), email => hubsync._forgetHeld(email)] }); // 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); tankready.init({ site: 'linkspin', accounts, tank, followGet: e => followStore.get(e) }); // read-only: sends this site's facts, keeps the hub's answer for the tank cards 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) // network hub rule 3 (2026-11-14, only with HUB_ENABLED): the hub's sponsor comes first for alignment, and nobody it reports // locked on a network contract or sponsored is offered, moved to the tank or auto-assigned (hubsync.js: cache + fail-safe) hooks: { network: async (email, address) => (hubsync.on() ? await hubsync.hubSponsor(email).catch(() => null) : null) || networkSponsor(email, address), prefetch: emails => iapFacts(emails, { timeout: 20000 }), networkHeld: accts => (hubsync.on() ? hubsync.heldAmong(accts) : new Map()), networkLocked: email => (hubsync.on() ? hubsync.lockedAnywhere(email) : null), 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, '

' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s)]+)/g, '$1') + '

'), 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:///); 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) loginAdEveryHours: 3, // login ad: shown again on the next member page once the last finished view is this many hours old (Marty 2026-11-15) 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/ 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 https://polhunter.com '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://polhunter.com 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,videoappincome.com,clickvidpro.com,socialtube.club').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= 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/ 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 = '

' + String(text).replace(/&/g, '&').replace(//g, '>') .replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

').replace(/\n/g, '
') + '

'; 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: ' + weiToPol(ev.amountWei) + ' POL \u2192 ' + who(ev.recipientId); else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has ' + ev.newCount + ' 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') + ': ' + weiToPol(ev.amountWei) + ' POL \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 verify' + (sc.telegramCtaUrl ? '\nJoin free' : ''); }; 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} LinkSpin \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 = []; const all = await tank.waiting(); // the running total goes in the post too (Marty 2026-11-14: "post those totals") for (const w of tank.openedSince(all, 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} LinkSpin \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who + ' (' + tank.adoptableOf(all).length + ' waiting in total)' + '\nAdopt from Team \u203a Waiting on a wallet: ' + SITE_HOST + '/team'; 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} LinkSpin \u00b7 ' + clean(adopterName) + ' picked up ' + clean(adopteeName) + ' 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, '>'); 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(); tankready.refresh().catch(() => {}); // readiness: send the hub this site's entry facts and refresh the card cache (no mail, no sponsor change) 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} LinkSpin \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} LinkSpin \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(/' + H + '

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.

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 report page and we will pull the link.

What we record

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 privacy policy.

', disclosure: '

Affiliate and advertising disclosure

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.

' + 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.

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 terms.

', terms: '

Terms of use

By following a link on ' + H + ' you agree to these terms.

The service

' + 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.

Acceptable use

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.

No warranty

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.

Contact

Questions about these terms: linkspin.co.

', privacy: '

Privacy policy

This policy covers ' + H + ' and the link forwarding service on it.

What we collect

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.

Click ids

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 (lsclk). 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.

Cookies

This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.

Why we collect it

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.

Retention

Link statistics are kept for up to thirteen months and then deleted.

Your rights

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 linkspin.co.

', abuse: '

Report a link

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.

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 linkspin.co. Reports are usually handled the same day.

', gone: '

That link is not active

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.

' }; return '' + H + '
' + nav + (bodies[page] || bodies.gone) + '
'; } // ---- server ---- // ---- the curtain ---------------------------------------------------------- // Work in progress is not for passers-by. CURTAIN= puts a contentless holding page // in front of every request; ?k= sets a cookie that lifts it for that browser. const CURTAIN = String(process.env.CURTAIN || '').trim(); const CURTAIN_PAGE = ` Coming soon

Coming soon

This site is still being built.

`; 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; } // partner sites allowed on /api/partner//links (2026-11-15): network catalog template + the name the member sees on the link const PARTNER_LINKS = { dh: { template: 'downlinehydra', name: 'DownlineHydra' }, vab: { template: 'viraladblitz', name: 'ViralAdBlitz' }, vas: { template: 'viraladsource', name: 'ViralAdSource' }, // vas = ViralAdSource text ads (Marty 2026-11-17), the vab wiring ypb: { template: 'yourprogrambuilder', name: 'YourProgramBuilder' } }; // ypb = YourProgramBuilder saved IDs (go-live 2026-11-17), the dh wiring (sub-id ypb) 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 // network sign-in with InstantAdPay (2026-11-12): /go/iap, /sso/start, /sso/check, /sso/in, /api/sso/status (app host only) if (req.method === 'GET' && !isPagesHost(req) && !isLinkHost(req) && await networksso.page(req, res, u)) return; // network hub: daily activity ping + the hub sign-in push (2026-11-15) // every /go/ and every ?return= link goes to networksso (2026-11-17): it knows the hub's sign-in sites, so a new site no longer needs a line here if (req.method === 'GET' && (p.startsWith('/go/') || p.startsWith('/sso/') || p === '/api/sso/status' || u.searchParams.has('return')) && !isPagesHost(req) && !isLinkHost(req) && await networksso.handle(req, res, u)) return; // -- Video Spin zone (2026-11-22):