Files
instantadpay/server.js
T

5924 lines
527 KiB
JavaScript

// InstantAdPay — 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 discordRelay = require('./discord-relay.cjs'); // mirror group posts into the CTB Discord (2026-10-09)
const https = require('https');
const dns = require('dns');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const sendy = require('./sendy');
const { URL } = require('url');
const chain = require('./chain');
const auth = require('./auth');
const accounts = require('./accounts');
const ads = require('./ads');
const mailer = require('./mailer');
const { emailIssue } = require('./emailcheck'); // typo / no-mail-domain check for NEW addresses (2026-10-22)
// only addresses we have never seen get the typo check; existing members always sign in with what they have.
// Skipped when this server cannot send mail (local QA copies sign in as @example.com via devCode).
const newEmailIssue = async e => (!mailer.hasKey() || (await accounts.byEmail(e)) ? null : emailIssue(e));
const messages = require('./messages');
const reports = require('./reports');
const drip = require('./drip');
const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set)
let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ }
const chatbot = require('./chatbot');
const kb = require('./kb'); // the assistant's knowledge base: Admin > Knowledge base, seeded from chatbot.js CANNED + kb-seed.js (2026-10-20)
const fraud = require('./fraud');
const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats
const tank = require('./tank');
const walletnudge = require('./walletnudge');
const milestone = require('./milestone'); // players with POL waiting in the games and no wallet (2026-10-07) // holding tank: unsponsored free members, adoptions, pay-it-forward
const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails
const traffic = require('./traffic'); // public page views by referring domain (admin Traffic tab)
const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|preview|monitor|wget|python-requests/i; // link previewers and crawlers: never a counted BixPay click (headless stays countable for the QA harness)
const loginShows = require('./loginshows'); // login-ad showings per day, dashboard vs games (2026-10-18)
const promos = require('./promos');
const missedNotice = require('./missed'); // the whole-chain missed-payout notice // 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 ledger = require('./ledger');
const videosweep = require('./videosweep');
const sbcheck = require('./sbcheck');
const reach = require('./reach');
const lssync = require('./lssync');
const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23)
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22)
const bixpay = require('./bixpay'); // BixPay Visa card: partner-link field, sponsor-follows resolver, tracked clicks (2026-10-29, gated by site config bixpayLive)
let follow = null, followStore = null;
const LS_BASE = () => String(process.env.LS_URL || 'https://linkspin.app').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;
}
const gamestats = require('./gamestats');
const marks = require('./marks');
const gamepass = require('./gamepass'); // the $5 weekly Game Pass + the account-wide POL cap service the games call (2026-10-16)
const feedgroup = require('./feedgroup'); // one proof-feed message per purchase: buyer, package, then the tier payouts // one-time claims shared across running instances (deploy overlap) // Google Safe Browsing screen on advertiser destinations
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 badge = require('./badge'); // achievement badge image drawn on the server with ffmpeg (2026-09-16)
const friday = require('./friday');
const prohibited = require('./prohibited'); // prohibited-content policy shared with LinkSpin (2026-10-30 link-farm incident)
const spamscan = require('./spamscan'); // daily link-farm scan + quarantine rule, byte-for-byte copy on LinkSpin
const starter = require('./starter'); // member welcome offer from the games (2026-10-05)
const wednesday = require('./wednesday'); // Wired Wednesday: +25% on $10+ packs, wired into a visits campaign (2026-09-29)
const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked Sat-Thu by solo + video (2026-09-26)
const refill = require('./refill');
const refuel = require('./refuel');
const kit = require('./kit');
const engine = require('./engine'); // the Engine Room: dials, warning lights, part lights, next move across both sites (Fuel Your Offers stage 4, 2026-10-24) // the Refuel Kit: monthly members-only banner sets, personalized per member (Fuel Your Offers stage 3, 2026-10-24) // the Monthly Refuel streak, one per member across InstantAdPay + LinkSpin (Fuel Your Offers, 2026-10-24); switch refuelStreak, default off
const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20)
const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15)
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 translate = require('./translate'); // help desk: member messages in other languages, replies back in theirs (2026-10-16)
const inbound = require('./inbound'); // help desk email intake: SendGrid Inbound Parse -> tickets (2026-10-16)
const supportbot = require('./supportbot'); // @CTBTickets_bot: ticket pings with buttons + answering from Telegram (2026-10-16)
const tickets = require('./tickets'); // help desk: member Help pane, public /support, chatbot hand-off, admin Support pane (Marty, 2026-10-16)
const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15)
const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12)
const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/refuel', '/conversion-tracking', '/presentation', '/support', '/bixpay']);
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 PORT = Number(process.env.PORT || 3000);
const ROOT = __dirname;
const PUBLIC_DIR = path.join(ROOT, 'public');
const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, 'data');
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme';
const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase();
// Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept
// in the volume so a restart doesn't log the admin out. Separate cookie and
// store from member sessions; the Bearer ADMIN_PASSWORD API path still works.
const ADMIN_SESS_FILE = path.join(DATA_DIR, 'admin-sessions.json');
const ADMIN_TTL = 12 * 60 * 60 * 1000;
let adminSessions = {};
try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; }
function saveAdminSessions() {
const now = Date.now();
for (const k of Object.keys(adminSessions)) if (!adminSessions[k] || adminSessions[k].expires < now) delete adminSessions[k];
try { fs.writeFileSync(ADMIN_SESS_FILE, JSON.stringify(adminSessions), { mode: 0o600 }); } catch (e) {}
}
function mintAdminSession(email) {
const t = crypto.randomBytes(32).toString('hex');
adminSessions[t] = { email, expires: Date.now() + ADMIN_TTL };
saveAdminSessions();
return t;
}
function adminTokenOf(req) { const m = /(?:^|;\s*)iap\.adm=([^;]+)/.exec(req.headers.cookie || ''); return m ? decodeURIComponent(m[1]) : null; }
function adminFromRequest(req) { const t = adminTokenOf(req); const s = t && adminSessions[t]; return (s && s.expires > Date.now()) ? s : null; }
function dropAdminSession(req) { const t = adminTokenOf(req); if (t && adminSessions[t]) { delete adminSessions[t]; saveAdminSessions(); } }
function adminCookie(t) { return 'iap.adm=' + encodeURIComponent(t) + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (ADMIN_TTL / 1000) + (IS_PROD ? '; Secure' : ''); }
function clearAdminCookie() { return 'iap.adm=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
const IS_PROD = process.env.NODE_ENV === 'production';
const todayCT = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); // Marty's day, never UTC
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
// 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;
// durable maps are balances and orders, not short-lived tokens: restore every entry whatever its age. Before 2026-10-10 the
// age filter silently dropped every PolyWarriors mint pass (no ts on the record) on each deploy; Orlando lost his.
const DURABLE = new Set(['pwpasses', 'pwprizes', 'pworders', 'gkorders', 'sdorders', 'gamepass', 'gporders', 'gpprizes']);
for (const [name, m] of Object.entries(persistedMaps)) {
for (const [k, v] of Object.entries(saved[name] || {})) if (v && (DURABLE.has(name) || 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)
// 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 InstantAdPay: 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;
}
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: 'InstantAdPay', targetUrl: 'https://instantadpay.com/', bannerUrl: null }];
}
const chatHits = new Map();
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();
// Sponsor bound to the sign-up, not only to a cookie (Marty, 2026-09-29: nancyr #180 and others "supposed to land under
// Mad Dog" were created with no sponsor and fell to the company). The iap.sponsor cookie is SameSite=Lax, so it is
// rejected when the join page is shown inside another site (traffic-exchange frames), and it never crosses browsers
// (in-app browser -> mail app -> default browser). So: the join page sends the token from its own URL with the code
// request, the server remembers "this email asked for a code under <token>" for 30 days on disk (deploys restart the
// process), and account creation uses page token, then cookie, then that memory. A token-less request never
// overwrites a remembered token.
const pendingSponsor = {
FILE: () => path.join(DATA_DIR, 'pending-sponsors.json'), db: null,
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = {}; } },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} },
set(email, f) { if (!email || !f || !f.ref) return; if (!this.db) this.load(); this.db[email] = { ref: f.ref, via: f.via || '', joinedRef: f.joinedRef || null, at: Date.now() }; this.prune(); this.save(); },
get(email) { if (!this.db) this.load(); const r = this.db[email]; return r && Date.now() - r.at < 30 * 86400e3 ? r : null; },
del(email) { if (!this.db) this.load(); if (this.db[email]) { delete this.db[email]; this.save(); } },
prune() { const cut = Date.now() - 30 * 86400e3; for (const k of Object.keys(this.db)) if (this.db[k].at < cut) delete this.db[k]; }
};
const pageTok = v => { const t = String(v || '').trim().toLowerCase(); return /^[a-z0-9_]{1,40}$/.test(t) ? (JOIN_ALIASES[t] || t) : ''; }; // a token the join page read from its own URL
// ── 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)
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) + '***');
// Form age is measured on the visitor's own clock (fage = their Date.now() minus the moment the form loaded), so a
// phone whose clock runs fast or slow is not refused forever. Comparing their fts with OUR clock did exactly that
// (2026-10-07: a member retried and was stopped every time). Old cached pages send only fts: fall back to it.
const fts = Number(b.fts) || 0;
const fage = (b.fage !== undefined && b.fage !== null && b.fage !== '' && Number.isFinite(Number(b.fage))) ? Number(b.fage) : (fts ? now - fts : -1);
if (fage < CODE_LIMITS.minFormMs) { guardLog(req, 'form-age', b); return { status: 400, body: { error: 'Give the page a second, then tap again.' } }; }
if (fage > 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;
}
// 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 InstantAdPay 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, 'InstantAdPay: 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']];
// Spooky Doors' door check uses Halloween icons (Marty, 2026-10-02)
const DOOR_CAPTCHA = [['🎃', 'pumpkin'], ['👻', 'ghost'], ['🦇', 'bat'], ['🍬', 'candy'], ['🕷️', 'spider'], ['💀', 'skull'], ['🍭', 'lollipop'], ['🧙', 'witch'], ['🕸️', 'spider web'], ['🌕', 'full moon'], ['🍫', 'chocolate']];
// ── 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;
const rq = mod.get(u.href, { timeout: 8000,
headers: { 'User-Agent': 'Mozilla/5.0 (compatible; InstantAdPay-FrameCheck/1.0)', Accept: 'text/html' } }, 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 ((uploadCounts.get(key) || 0) >= 10) 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);
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);
return json(res, 200, { url: '/uploads/' + name, type: isVideo ? 'video' : 'image' });
}
// lead-capture page hooks (og tags + copy live in public/assets/join.js too)
const JOIN_ALIASES = { company: 'martbost', top: 'martbost' }; // neutral partner links -> the top position
const JOIN_ANGLES = {
// legacy bridge pages (/from/<brand>): former members of Marty's closed EvolutionScript sites
'fw-adv': { t: 'Your next ad budget pays you back.', d: 'Faucet Wave closed. InstantAdPay was built for the people who bought ads there: packages from $5, seven formats, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: 'https://instantadpay.com/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: 'https://instantadpay.com/from/faucetwave' },
't1-adv': { t: 'Your next ad budget pays you back.', d: 'Tier One Ads closed. InstantAdPay was built for the people who bought ads there: packages from $5, seven formats, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: 'https://instantadpay.com/from/tieroneads?seg=advertiser' },
'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: 'https://instantadpay.com/from/tieroneads' },
// SocialPix (socialpix.club) gate, 2026-09-20: the media-sharing site was being used as a free
// ad board; its signup/post flows now land here. Default copy = advertiser (that is why they came).
'sp-adv': { t: 'Your ad, seen across a whole network.', d: 'SocialPix no longer takes ad posts. Advertising now runs through InstantAdPay: a free account, your ad in seven formats across every site in the network, and every package in your line paid out on Polygon in the same transaction. Real email required.', url: 'https://instantadpay.com/from/socialpix' },
'sp-earn': { t: 'Same feed. Real payouts on-chain.', d: 'SocialPix has moved its advertising to InstantAdPay. View ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Join free by email.', url: 'https://instantadpay.com/from/socialpix?seg=earn' },
play: { t: 'If you have time to play a game, you have time to build a business.', d: 'Free games that pay real Polygon to your wallet, on chain, where anyone can check it. Play free, then join free by email.' },
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. Seven formats, packages from $5. 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.' },
friday: { t: 'Five Dollar Friday: 20% bonus credits.', d: 'Every Friday, US Central time, any ad package from $5 up earns 20% bonus credits the moment it settles, and every pack pays its sponsor line in the same transaction. Join free by email.' },
wednesday: { t: 'Wired Wednesday: 25% bonus credits, wired in the second it settles.', d: 'Every Wednesday, US Central time, any ad package from $20 up earns 25% bonus credits, wired into your balance the moment the purchase settles and good for any ad format. Join free by email.' },
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.' },
// Build Wide hook (2026-10-15): the 'buildwide' promo video; files keep the uploaded promo/buildwide.* names
wide: { t: 'Width unlocks depth.', d: 'Watch the fifty percent land, then the deeper levels open. Every package in your line is split by a verified contract on Polygon in the same transaction. Join free by email.', img: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/buildwide.jpg', imgW: 1280, imgH: 720 }
};
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 = 'https://instantadpay.com';
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 InstantAdPay: real ad packages with same-transaction payouts on Polygon, every payment public. Join free by email.';
// each hook angle previews with its own video's opening frame (Marty 2026-10-13: shared angle links all showed the generic hero)
const ogImg = (ang && ang.img) || (base + (['play', 'instant', 'adspend', 'free', 'ledger', 'two'].includes(angle) ? '/banners/iap-angle-' + angle + '-1200x630.jpg?v=1' : '/banners/iap-hero-1200x630.png'));
const ogW = (ang && ang.imgW) || 1200, ogH = (ang && ang.imgH) || 630;
const escA = t => String(t).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
const og = '<meta property="og:type" content="website"><meta property="og:site_name" content="InstantAdPay">'
+ '<meta property="og:title" content="' + escA(title) + '"><meta property="og:description" content="' + escA(desc) + '">'
+ '<meta property="og:url" content="' + escA(url) + '">' // keeps ?v= so shares stay on the angle
+ '<meta property="og:image" content="' + ogImg + '"><meta property="og:image:width" content="' + ogW + '"><meta property="og:image:height" content="' + ogH + '">'
+ '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' + escA(title) + '"><meta name="twitter:description" content="' + escA(desc) + '"><meta name="twitter:image" content="' + ogImg + '">';
html = html.replace(/<title>[^<]*<\/title>/, '<title>' + escA(title) + ' | InstantAdPay</title>' + og);
if (ang) html = html.replace('<body>', '<body class="squeeze">'); // angle pages: squeeze layout from the first paint
// Network Ad Space zone on the two legacy squeeze pages only (Marty, 2026-09-19): below the
// fine print, above the footer links. The regular join pages stay ad-free.
if (/^(fw|t1)-(adv|earn)$/.test(String(angle || ''))) html = html.replace('<div class="jn-foot">',
'<div class="jn-nas" style="max-width:728px;margin:34px auto 0;overflow:hidden;text-align:center"><!-- nas-legacy --><iframe title="Advertisement" width="728" height="90" scrolling="no" loading="lazy" style="border:0;max-width:100%;display:block;margin:0 auto;background:transparent" srcdoc="&lt;!doctype html&gt;&lt;base target=&quot;_blank&quot;&gt;&lt;style&gt;html,body{margin:0;padding:0;overflow:hidden;background:transparent}&lt;/style&gt;&lt;script src=&quot;https://www.networkadspace.com/showadss.php?w=728&amp;h=90&amp;n=1&amp;bw=728&amp;bh=90&amp;c=999&quot;&gt;&lt;/script&gt;"></iframe><!-- framed 2026-10-24: a dead ad server must never block the page --></div>' + '<div class="jn-foot">');
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);
}
// A banner creative must be an IMAGE (2026-09-16: campaign #134 had the member's join-page link in the
// image field and served a broken banner 141 times on the network). Accept /uploads/ files and
// image extensions outright; otherwise HEAD the URL and require an image/* content-type.
async function imageCheck(url) {
const u = String(url || '').trim();
if (/^\/uploads\//.test(u) || /^https?:\/\/instantadpay\.com\/(uploads|banners)\//i.test(u)) return { ok: true };
if (/\.(png|jpe?g|gif|webp|svg)([?#].*)?$/i.test(u)) return { ok: true };
try {
const h = await headUrl(u);
if (h && /^image\//i.test(String(h.contentType || ''))) return { ok: true };
return { ok: false, reason: 'That link is a web page, not an image. Paste the direct image link (it usually ends in .png or .jpg), or use Promo tools > Banners > Copy image URL.' };
} catch (e) { return { ok: false, reason: 'Could not load that image link. Paste the direct image link (ends in .png or .jpg), or use Promo tools > Banners > Copy image URL.' }; }
}
// A video campaign's source has to actually exist. The create form only matched the URL
// shape, so a placeholder (yourdomain.com/....mp4) went live on 2026-09-11 and sat there for
// eleven days handing every Tier 1 viewer a black player they could never finish.
// PolHunter pays real POL out of its own faucet and none of it passes through this contract, so
// the P&L cannot derive it from chain events and has to read it across (Marty, 2026-09-23). Cached
// and fail-soft: the P&L page must never hang or break because the other site is down.
let huntCache = { at: 0, data: null };
// real block timestamps for the tax summary, read once and kept (a block's time never changes)
let blockTimesCache = null;
function blockTimes() { if (!blockTimesCache) { try { blockTimesCache = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'blocktimes.json'), 'utf8')); } catch (e) { blockTimesCache = {}; } } return blockTimesCache; }
function saveBlockTimes(bt) { try { const f = path.join(DATA_DIR, 'blocktimes.json'); fs.writeFileSync(f + '.tmp', JSON.stringify(bt)); fs.renameSync(f + '.tmp', f); } catch (e) {} }
async function huntLedger() {
if (Date.now() - huntCache.at < 120000) return huntCache.data;
const base = String(process.env.HUNT_URL || 'https://polhunter.com').replace(/\/+$/, '');
try {
const r = await fetch(base + '/api/ledger', { signal: AbortSignal.timeout(6000) });
if (!r.ok) throw new Error('HTTP ' + r.status);
const j = await r.json();
huntCache = { at: Date.now(), data: { totals: j.totals || null, referrals: j.referrals || null, pools: j.pools || null, at: Date.now() } };
} catch (e) {
huntCache = { at: Date.now(), data: huntCache.data || { error: e.message } };
}
return huntCache.data;
}
async function videoCheck(url) {
const u = String(url || '').trim();
if (/^\/uploads\//.test(u)) return { ok: true }; // uploaded here, already on our disk
let h;
try { h = await headUrl(u); }
catch (e) { // no DNS, refused, timed out
return { ok: false, reason: 'We could not reach that video link, so members would just see a black player. Check the address, or upload the file here instead.' };
}
if (h && (h.status === 404 || h.status === 410))
return { ok: false, reason: 'That video link answers with HTTP ' + h.status + ' — the file is not there. Point the campaign at a file that loads, or upload it here.' };
const ct = String((h && h.contentType) || '').split(';')[0].trim().toLowerCase();
if (ct && !/^video\//.test(ct) && ct !== 'application/octet-stream' && ct !== 'binary/octet-stream')
return { ok: false, reason: 'That link returns ' + ct + ', not a video file. Paste the direct .mp4 or .webm link, or upload the file here.' };
return { ok: true };
}
function headUrl(url) {
return new Promise((resolve, reject) => {
let u; try { u = new URL(url); } catch (e) { return reject(new Error('bad url')); }
const mod = u.protocol === 'http:' ? require('http') : require('https');
const req = mod.request({ method: 'HEAD', hostname: u.hostname, port: u.port || undefined, path: u.pathname + u.search, timeout: 6000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; InstantAdPay-ImageCheck/1.0)' } }, r => {
if (r.statusCode >= 300 && r.statusCode < 400 && r.headers.location && !u.searchParams.has('_r')) { try { const nx = new URL(r.headers.location, url); nx.searchParams.set('_r', '1'); return resolve(headUrl(nx.toString())); } catch (e) {} }
resolve({ status: r.statusCode, contentType: r.headers['content-type'] || '' }); r.resume();
});
req.on('error', reject); req.on('timeout', () => req.destroy(new Error('timeout'))); req.end();
});
}
// login-ad gate: can this sponsor's page load inside our frame? Cached 6 h per campaign + url; an answer that
// takes longer than 4 s counts as "no" for this sign-in (new-tab fallback) while the check finishes for the cache.
const loginFrameCache = new Map();
async function loginFrameable(id, url, inGame) { // inGame: the frame sits on a game's page, so an allowance for instantadpay.com alone is not enough
const key = (inGame ? 'g|' : '') + id + '|' + url, hit = loginFrameCache.get(key);
if (hit && Date.now() - hit.ts < 6 * 3600 * 1000) return hit.ok;
if (!url) return false;
const check = frameCheck(url, inGame).then(r => { loginFrameCache.set(key, { ok: !!r.ok, ts: Date.now() }); return !!r.ok; }).catch(() => false);
return Promise.race([check, new Promise(r => setTimeout(() => r(false), 4000))]);
}
async function frameCheck(url, inGame) {
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:' || (!inGame && v.includes('instantadpay.com'));
}))
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 };
}
async function boot() {
await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode)
marks.init({ db });
marks.ensureTable().catch(e => console.error('marks table', e.message));
lsconv.init({ db, dataDir: DATA_DIR });
auth.onSeen((email, req) => lsconv.noteSession(email, clientIp(req), req.headers['user-agent'])); // own-click tests on LinkSpin (2026-10-26)
setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref();
chain.init({ onEvent: ev => {
// the in-memory feed is per instance and always runs
attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev));
// everything outward (email, Telegram, the Friday bonus, sponsor sync) happens ONCE across
// every running copy of the app: during a deploy two copies watch the chain for ~30 s,
// and on 2026-09-25 both emailed Marty and both granted his Friday bonus
marks.claim('ev:' + ev.tx + ':' + ev.li).then(mine => {
if (!mine) return;
emailOnEvent(ev).catch(() => {});
telegramOnEvent(ev).catch(() => {});
starter.onEvent(ev).catch(e => console.error('starter bonus', e.message));
pwMintOnEvent(ev).catch(e => console.error('polywarriors mint', e.message));
// the Friday bonus and the pass order first, then the Friday pass perk, which needs both results (Marty 2026-10-23)
Promise.all([friday.onEvent(ev).catch(e => { console.error('friday bonus', e.message); return null; }), gamepass.onEvent(ev).catch(e => { console.error('gamepass order', e.message); return null; })])
.then(([bonus, gp]) => fridayPassPerk(ev, bonus, gp)).catch(e => console.error('friday pass perk', e.message));
wednesday.onEvent(ev).catch(e => console.error('wednesday bonus', e.message));
refuel.onIapPurchase(ev).catch(e => console.error('refuel streak', e.message)); // its own bonus, stacked on Friday/Wednesday; no-op while refuelStreak is off
sponsorSyncOnEvent(ev).catch(e => console.error('sponsor sync', e.message));
}).catch(e => console.error('marks claim', e.message));
} });
auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: 'instantadpay.com' });
accounts.init({ dataDir: DATA_DIR });
ads.init({ dataDir: DATA_DIR, chain, tiers: () => geo.tierLists(siteConfig()) });
mailer.init({ dataDir: DATA_DIR });
messages.init({ dataDir: DATA_DIR });
reports.init({ dataDir: DATA_DIR });
drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: 'https://instantadpay.com' });
chatbot.init({ dataDir: DATA_DIR, chain, bixLive: () => bixpay.live(), gameLive: slug => String(siteConfig().gamesLive == null ? 'polhunter' : siteConfig().gamesLive).split(',').map(x => x.trim().toLowerCase()).includes(slug), refuelOn: () => refuel.cfg().on, passTiers: () => { const c = gamepass.cfg(); return { on: c.enabled && c.tierSales, rows: gamepass.TIER_DEFS.filter(d => d.key !== 'weekly').map(d => ({ name: d.name, perks: d.perks, price: c.tiers[d.key].price, usd: c.tiers[d.key].price / 100, days: c.tiers[d.key].days, sale: c.tiers[d.key].sale })) }; } }); // pass tiers fact follows sovTiers (2026-10-22)
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
// 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 });
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
translate.init({ dataDir: DATA_DIR });
tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram, translate });
inbound.init({ tickets, accounts });
supportbot.init({ tickets, chatId: () => String(siteConfig().supportTelegramChat || '1289244227').trim(), site: 'https://instantadpay.com' });
badge.init({ publicDir: PUBLIC_DIR });
gamestats.init({ dataDir: DATA_DIR });
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, publicDir: PUBLIC_DIR, games: gamestats, launchesToday: () => GAMES().filter(g => (g.soon && g.soon.opens === todayCT()) || (g.season && g.season.start === todayCT() && String(siteConfig().gamesLive == null ? 'polhunter' : siteConfig().gamesLive).split(',').map(x => x.trim().toLowerCase()).includes(g.slug))).map(g => g.name),
send: async (c, t, th) => { await telegramSend(c, t, th); return true; },
sendPhoto: (c, jpeg, cap, th) => telegramSendPhoto(c, jpeg, cap, th) });
fridaybank.init({ db });
starter.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts });
friday.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts, mailer, drip, marks,
telegram: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> \u00b7 ' + text, sc.telegramEchoTopicId); },
notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; const html = '<p>' + String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/(https:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); } });
// Campaign refill notices: an advertiser is told when an ad is nearly out and when it has stopped,
// with the bonus ladder in the same message, and every send is watched for what they did next.
refill.init({
dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks, 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@instantadpay.com', [to], subject, html, 'notice'); },
});
// prepaid login-ad line (2026-10-23): when a reservation starts, its owner gets an on-site notice (kind 'notice', never the
// sign-in pop) and an email unless they unsubscribed. ads.js calls this once per start, from the one copy that won it.
ads.onLoginPromoted(async c => {
const owner = String(c.owner || '').toLowerCase(); if (!owner) return;
const name = c.name || ('campaign #' + c.id);
const until = new Date(Number(c.expires)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central';
const days = Number(c.body) || ads.rates().loginSlotDays || 30;
const subject = 'Your login ad "' + name + '" is live';
const text = 'Your place in line came up. Your reserved login-ad slot has started, so "' + name + '" now shows full screen to members as they sign in, for ' + days + ' days, until ' + until + '.\n\n'
+ 'You paid for it when you reserved, so nothing more is charged. See it in Members > Campaigns: https://instantadpay.com/my#campaigns\n\nInstantAdPay';
const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const html = '<p>Your place in line came up. Your reserved login-ad slot has started, so <b>' + esc(name) + '</b> now shows full screen to members as they sign in, for ' + days + ' days, until ' + esc(until) + '.</p>'
+ '<p>You paid for it when you reserved, so nothing more is charged. See it in <a href="/my#campaigns">Members &gt; Campaigns</a>.</p>';
try { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [owner], subject, html, 'notice'); } catch (e) { console.error('login line inbox', e.message); }
const stopped = drip && drip.isUnsubscribed ? await drip.isUnsubscribed(owner).catch(() => false) : false;
if (!stopped && mailer.hasKey()) { try { await mailer.send(owner, subject, text); } catch (e) { console.error('login line mail', e.message); } }
console.log('login line: #' + c.id + ' started for ' + owner.replace(/^(.).*(@.*)$/, '$1***$2'));
});
setInterval(() => ads.promoteLoginQueue().catch(e => console.error('login line', e.message)), 60 * 1000); // safety net: a slot that expired between changes
// the Monthly Refuel streak (refuel.js): source of truth for both sites; LinkSpin reports purchases and collects its grants
// through /api/partner/refuel/*. Feed lines go to the payments topic like other InstantAdPay feed lines.
refuel.init({ dataDir: DATA_DIR, db, marks, siteConfig, accounts, ads, mailer, drip,
featuredPerDay: () => ads.rates().featuredPerDay || 40,
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); },
badge: (email, key) => postBadgeOnce(email, key, 'Monthly Refuel'),
feed: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> \u00b7 ' + text, sc.telegramEchoTopicId); } });
kit.init({ dataDir: DATA_DIR, program: 'iap', publicDir: PUBLIC_DIR, siteUrl: 'https://instantadpay.com',
entitled: async email => { const v = await refuel.view(email); return v && v.on ? { 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: 'https://instantadpay.com/join/' + tok } : null; } });
setTimeout(() => refuel.tick().catch(e => console.error('refuel', e.message)), 120000);
setInterval(() => refuel.tick().catch(e => console.error('refuel', e.message)), 10 * 60 * 1000);
setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000);
setInterval(() => refill.tick().catch(e => console.error('refill', e.message)), 20 * 60 * 1000);
setInterval(() => friday.tick().catch(e => console.error('friday', e.message)), 5 * 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: 'InstantAdPay', siteUrl: 'https://instantadpay.com', otherSite: 'LinkSpin', 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); const hermes = String(process.env.HERMES_BOT_TOKEN || '').trim(); if (hermes) return tgSendAs(hermes, chat, text); if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'InstantAdPay link-farm scan', text); },
alsoOn: async (email, a) => (a && a.joinedVia === 'linkspin') ? true : lssync.knows(email) });
setTimeout(() => spamscan.tick().catch(e => console.error('spamscan', e.message)), 150000);
setInterval(() => spamscan.tick().catch(e => console.error('spamscan', e.message)), 5 * 60 * 1000);
wednesday.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts, mailer, drip, marks, rates: () => ads.rates(),
telegram: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> · ' + text, sc.telegramEchoTopicId); },
notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; const html = '<p>' + String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/(https:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); } });
setInterval(() => wednesday.tick().catch(e => console.error('wednesday', e.message)), 5 * 60 * 1000);
override.init({ dataDir: DATA_DIR, chain, siteConfig, notify: supportTelegram, db, brand: 'InstantAdPay', siteUrl: 'https://instantadpay.com' });
setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000);
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
// sponsor follow (sponsorfollow.js): a deliberate change (tank adoption, rescue, release, window expiry, admin edit) is
// recorded and follows to LinkSpin, and LinkSpin's deliberate changes are applied here, until the member is bound on
// InstantAdPay's contract (memberId, or the wallet already on chain). Ordinary bindings keep the first-platform rule.
followStore = SF.create({ dataDir: DATA_DIR, platform: 'instantadpay' });
follow = SF.glue({ store: followStore, accounts, tank: () => tank, peer: 'linkspin',
isBound: async a => {
if (Number(a.memberId) > 0) return { bound: true, why: 'InstantAdPay member #' + a.memberId };
if (!a.address) return { bound: false };
try { const id = Number(await chain.memberIdByAccount(a.address)) || 0; return id ? { bound: true, why: 'wallet is InstantAdPay member #' + id } : { bound: false }; }
catch (e) { return { retry: true, why: 'InstantAdPay 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 });
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore,
// activation hold + 24-hour safety net (2026-10-27): a tank member is never bound under the fallback position
hooks: { network: (email, address) => lsinbound.networkSponsor(email, address), isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em),
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text),
// switch-on-payouts reminders after an assignment (2026-10-27): one send per key across both app copies (deploy overlap),
// the sponsor's nudge as an in-app notice (never a pop-up broadcast), stop once the wallet is on chain
claim: key => marks.claim(key), activated: a => !!(a && a.address && activationByAddress().get(String(a.address).toLowerCase())),
notify: async (email, subject, text) => { const html = '<p>' + String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/(https:\/\/[^\s)]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [email], subject, html, 'notice'); } } });
// LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest
lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email));
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore });
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account
walletnudge.init({ dataDir: DATA_DIR, accounts, chain, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com',
bixLine: a => bixpay.nudgeLine(a ? (a.username || a.code) : ''), // one BixPay sentence in the nudge, only while bixpayLive (2026-10-29)
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); } });
setTimeout(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 3 * 60 * 1000); // past the deploy overlap window
setInterval(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 60 * 60 * 1000);
// 1,000-member POL drop (Marty 2026-10-10): watches the account count every 2 minutes while milestoneMode is dry or armed
milestone.init({ dataDir: DATA_DIR, accounts, chain, mailer, ledger, optedIn: updates.optedIn, site: 'https://instantadpay.com', siteConfig, noPayoutSet,
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); },
telegram: async html => { const sc = siteConfig(); if (sc.telegramChatId) await telegramSend(sc.telegramChatId, html, sc.telegramTopicId); if (sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, html, sc.telegramEchoTopicId); } });
setTimeout(() => milestone.tick().catch(e => console.error('milestone', e.message)), 4 * 60 * 1000);
setInterval(() => milestone.tick().catch(e => console.error('milestone', e.message)), 2 * 60 * 1000);
await fraud.init({ dataDir: DATA_DIR });
{ // a suspended account is signed out everywhere: every member route sees no session
const realFrom = auth.fromRequest.bind(auth);
auth.fromRequest = async (req) => { const sess = await realFrom(req); if (sess && sess.email && fraud.isSuspended(sess.email)) return null; return sess; };
}
legacy.init({ dataDir: DATA_DIR });
traffic.init({ dataDir: DATA_DIR });
bixpay.init({ dataDir: DATA_DIR, accounts, siteConfig, refAccount });
loginShows.init({ dataDir: DATA_DIR });
promos.init({ dataDir: DATA_DIR });
blog.init({ dataDir: DATA_DIR, extraPages: () => bixpay.live() ? ['/bixpay'] : [] });
adminMember.init({ accounts, ads, chain, tank, legacy, promos, messages, dataDir: DATA_DIR });
gamepass.init({ dataDir: DATA_DIR, siteConfig, accounts, marks, isProd: IS_PROD, persistedMap, polUsd: polUsdLive,
blockTime: async n => { const blk = await chain.rpc('eth_getBlockByNumber', ['0x' + Number(n).toString(16), false]); return blk && blk.timestamp ? parseInt(blk.timestamp, 16) : 0; }, // a pass order is fulfilled only by a purchase mined after it
telegram: async html => { const sc = siteConfig(); const chat = String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(); if (!sc.telegramBotToken || !chat) return false; await telegramSend(chat, html, sc.telegramGamesTopicId || null); return true; },
notify: (to, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice') }); // before loadOpenTokens: its maps must exist to be restored
loadOpenTokens();
setTimeout(() => gamepass.tournamentTick().catch(e => console.error('gamepass tournament', e.message)), 120 * 1000);
setInterval(() => gamepass.tournamentTick().catch(e => console.error('gamepass tournament', e.message)), 60 * 60 * 1000);
setInterval(() => { try { gamepass.prune(); } catch (e) { console.error('gamepass prune', e.message); } }, 6 * 3600 * 1000).unref();
syndicate.init({ dataDir: DATA_DIR, publicDir: PUBLIC_DIR, uploadsDir: UPLOADS_DIR });
releases.init({ dataDir: DATA_DIR });
ledger.init({ dataDir: DATA_DIR });
// re-check live video sources on a schedule: videoCheck only ever runs at save time, so a
// campaign created before it existed, or a link that rots later, is otherwise invisible
const videosweepAlert = async text => {
const sc = siteConfig();
// Marty's own Hermes chat, where his other operational pings land (@CoolifyHermes_Bot).
// Admin channels ONLY, never a member-visible one: this names a member's campaign and
// their email address, so the shared payments topic would put it in front of the team.
const hermes = String(process.env.HERMES_BOT_TOKEN || '').trim();
if (hermes && sc.telegramAdminChatId) return tgSendAs(hermes, sc.telegramAdminChatId, text);
if (sc.telegramBotToken && sc.telegramAdminChatId) return telegramSend(sc.telegramAdminChatId, text);
if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'InstantAdPay: broken video sources', text.replace(/<[^>]+>/g, ''));
console.log('videosweep: no admin channel configured, alert not sent');
};
videosweep.init({ dataDir: DATA_DIR, fs, path, db, videoCheck, alert: videosweepAlert });
videosweep.start();
// Screen every advertiser destination against Google Safe Browsing: refuse a flagged one at
// save time, and re-screen the live ones daily. Added 2026-09-24 after Google marked the
// site "deceptive pages" with campaign #225 opening llclickpro.com (flagged) from our pages.
// Shares videosweep's alert path on purpose: it names members and their emails, admin only.
sbcheck.init({ dataDir: DATA_DIR, fs, path, db, selfHost: 'instantadpay.com', alert: videosweepAlert });
sbcheck.start();
// Destination reachability (2026-10-07): a link that resolved when saved can die later (campaign #163's
// lmgnow.co vanished and 65 members hit a dead end while Safe Browsing read 'cannot resolve' as unknown).
// Refuses a host with no DNS record at save time; pauses live ads whose host is dead two days running.
reach.init({ dataDir: DATA_DIR, fs, path, db, selfHost: 'instantadpay.com', alert: videosweepAlert, site: 'https://instantadpay.com',
message: (to, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'),
mailer, optedIn: email => updates.optedIn(email) });
reach.start();
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, 'InstantAdPay: counter audit', text).catch(() => {}); } });
setTimeout(() => audit.dailyTick(), 5 * 60 * 1000); setInterval(() => audit.dailyTick(), 24 * 60 * 60 * 1000);
videomaker.init({ dataDir: DATA_DIR, spaces, accounts });
leaderboard.init({ chain, accounts, ads, fraud, 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)), 2 * 60 * 1000); // after the LinkSpin inbound state is loaded
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 });
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);
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);
pdsync.init({ dataDir: DATA_DIR, ads });
if (pdsync.enabled()) { const every = Math.max(2, Number(process.env.PD_SYNC_MIN || 5)) * 60 * 1000; setTimeout(() => pdsync.sync().catch(e => console.error('pdsync', e.message)), 90 * 1000); setInterval(() => pdsync.sync().catch(e => console.error('pdsync', e.message)), every); console.log('PassiveDrip PTC bridge: on, every', every / 60000, 'min'); } else console.log('PassiveDrip PTC bridge: off (no PD_BRIDGE_URL/SECRET)');
setInterval(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 5 * 60 * 1000);
}
}
// Game Pass partner helpers (2026-10-16): which secret signs for which game, signature compare, member resolution, dev clock
const GP_SECRETS = () => ({ polhunter: String(process.env.HUNT_SSO_SECRET || '').trim(), gemkingdom: GK_SECRET(), spellwheel: SW_SECRET(), spookydoors: SD_SECRET(), polywarriors: PW_SECRET(),
clutterhunt: SEEK_SECRET(), polybreak: PB_SECRET(), polminer: PM_SECRET(), warpwares: WW_SECRET(), driprunner: DR_SECRET(), roadagent: RA_SECRET(), shardsofvalor: SOV_SECRET() });
function gpPartnerCheck(game) { if (!gamepass.GAMES.includes(game)) return { error: 'unknown game', code: 400 }; const secret = GP_SECRETS()[game] || ''; if (secret.length < 32) return { error: game + ' is not connected', code: 503 }; return { secret }; }
const gpSigOk = (want, got) => typeof got === 'string' && want.length === got.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got));
async function gpResolve(memberId, email) { // the account behind a game's player: main member id, a linked position's id, or (no wallet yet) the email
const id = Number(memberId) || 0; let a = null;
if (id) { a = await accounts.byMemberId(id); if (!a) { const pos = await accounts.positionByMember(id); if (pos && pos.email) a = await accounts.byEmail(pos.email); } }
if (!a && email && /^[^\s@]+@[^\s@]+$/.test(String(email))) a = await accounts.byEmail(String(email).trim().toLowerCase());
return a && a.email ? { email: String(a.email).toLowerCase(), memberId: a.memberId || id || 0, acct: a } : null;
}
const gpDevNow = devDay => (!IS_PROD && /^\d{4}-\d{2}-\d{2}$/.test(String(devDay || ''))) ? Date.parse(devDay + 'T17:00:00Z') : Date.now(); // local tests fake the Central day
// live USD per POL from the catalog quotes (the rate the games use for the tournament pool); cached 10 minutes
const polUsdCache = { at: 0, v: 0 };
async function polUsdLive() {
if (!IS_PROD && Number(process.env.DEV_POL_USD) > 0) return Number(process.env.DEV_POL_USD); // local tests: no RPC
if (polUsdCache.at && Date.now() - polUsdCache.at < 300000 && polUsdCache.v > 0) return polUsdCache.v; // 5 min: what members see as today's dollar value
const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (!pk) return polUsdCache.v || 0;
const v = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); if (v > 0) { polUsdCache.v = v; polUsdCache.at = Date.now(); } return v;
}
// the Game Pass flag rides in every sign-in hand-off token (3a: games get it at sign-in and on every polgrant answer)
// gamePass: { active, until, tier } (tier = the highest active pass: weekly | explorer | champion | sovereign | legend | null; a game treats a missing tier as weekly)
const gpClaim = c => { if (!(c && c.email && (!c.kind || c.kind === 'sso'))) return {}; const f = gamepass.flag(c.email); return { gamePass: { active: f.active, until: f.until, tier: f.tier } }; };
function siteConfig() {
let saved = {};
try { saved = JSON.parse(fs.readFileSync(SITE_FILE, 'utf8')); } catch (e) {}
return Object.assign({
siteName: 'InstantAdPay',
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: 'https://instantadpay.com/',
fraudMaxSignupsPerIpDay: 2, fraudBlockSharedDevice: 'on', // anti-fraud: accounts per IP per day; block a second account from the same browser
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
fridayPromo: '1', // Five Dollar Friday on/off (Marty, 2026-09-20)
fridayBonusPct: '20', // bonus credits on any $5+ package bought on a Friday, Central
fridayStart: '2026-09-25', // the first Five Dollar Friday
wednesdayPromo: '1', wednesdayBonusPct: '25', wednesdayMinCents: '2000', wednesdayStart: '2026-09-30', // Wired Wednesday (Marty, 2026-09-29)
refuelStreak: '0', // the Monthly Refuel streak master switch (Fuel Your Offers, 2026-10-24): '0' = nothing counted or granted, no reminders, cards hidden
refuelReminders: '1', refuelReminderHour: '9', // refuel reminders (email + on-site notice) 5 days before, on the day, last call; Central hour
refuelDayPromo: '0', refuelDayPct: '10', // optional network Refuel Day bonus on the 1st of each month (Central), off by default
refuelMinIapCents: '2000', refuelMinLsCents: '2500', // what counts as a refuel: $20+ on InstantAdPay, $25+ on LinkSpin
wednesdayNotice: '0', wednesdayKick: '0', // the Tuesday email/notice and the Wednesday Telegram kickoff stay off until Marty approves the copy
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
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
memberWeeklyEmail: '0', // 1 = the weekly 'Your week on InstantAdPay' email goes to every active member, not only sponsors with a line
noPayoutIds: '25', // 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)
legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand>
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
// Game Pass (2026-10-16, docs/GAME-PASS.md): off until Marty flips it; caps apply from capsStartDate (Central), before it polgrant allows everything and only records
gamePassEnabled: '0', gamePassPriceCredits: 500, gamePassDays: 7, capFreeDaily: 0.30, capFreeTotal: 2.0, capPassDaily: 1.50, capPassTotal: 5.0, capsStartDate: '', passTournamentPct: 5,
// Explorer and Champion monthly passes beside the weekly one (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md): islands and looks
// in Shards of Valor, never power, never more POL (same caps as the weekly pass). sovTiers = the sale switch for both (off: only ADMIN_EMAIL
// sees and can buy them, for testing; holders keep their pass). gamePass<Tier>Enabled '0' stops one tier alone. passTournamentTierSales '1'
// would add their sales to the Pass Tournament pool (off = the pool exactly as before).
// 2026-10-22 (Dallas's structure, Marty approved): Explorer $19.99 / Champion $39.99 for 30 days, plus Sovereign $99.99 for 30 days and
// Legend $249.99 for 365 days (the yearly pass), all behind sovTiers. Names, perks and the rank live in gamepass.js TIER_DEFS.
// 2026-10-25 (Marty): prices = the one-click packages: Explorer $20, Champion $50, Sovereign $100, Legend $250 (cents below).
sovTiers: '0', gamePassExplorerEnabled: '1', gamePassExplorerPriceCredits: 2000, gamePassExplorerDays: 30, gamePassChampionEnabled: '1', gamePassChampionPriceCredits: 5000, gamePassChampionDays: 30,
gamePassSovereignEnabled: '1', gamePassSovereignPriceCredits: 10000, gamePassSovereignDays: 30, gamePassLegendEnabled: '1', gamePassLegendPriceCredits: 25000, gamePassLegendDays: 365, passTournamentTierSales: '0',
supportTelegramChat: '1289244227', // help desk pings: Marty's PRIVATE chat only (a positive user id; group/channel ids are refused). Sent with telegramBotToken, Hermes bot as fallback
supportTemplates: '', // help desk saved replies, JSON [{name, body}] (Admin > Support > Saved replies); empty = the built-in set
telegramGamesChatId: '', telegramGamesTopicId: '661565', // Game Achievements topic for the weekly Pass Tournament post (chat blank = the shared echo chat)
// share-link domain (2026-10-20, Marty): member invite links go out as https://<shareDomain>/<username>, which 302s to
// /join/<username> here, so shared links do not carry instantadpay.com (Spamhaus DBL). '' = old instantadpay.com/join links.
// Switch to the spare (mylinehq.com) if one gets flagged. Old links keep working either way.
shareDomain: 'ctbgo.com',
// BixPay Visa card (2026-10-29, docs/BIXPAY-INTEGRATION.md): '0' = nothing shows anywhere (no Profile field, Wallet card,
// Overview card, promo tab, /bixpay guide, chatbot says coming soon). bixCompanyLink = the network fallback partner link
// (Marty's own PARTNER link, IB12143793); bixpayLiveSince is stamped when the switch is flipped on (the Overview card runs a week).
bixpayLive: '0', bixCompanyLink: bixpay.DEFAULT_COMPANY_LINK, bixpayLiveSince: '',
pnlFixedMonthlyUsd: 0
}, 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', '.vtt': 'text/vtt; charset=utf-8', '.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://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ='; 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 https://linkspin.app; 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();
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.
// the games load the sign-in kit from here with no version tag, so it revalidates every load (2026-10-18)
'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : path.basename(file) === 'game-signin.js' ? 'no-cache' : '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);
});
}
function readBody(req) {
return new Promise((resolve, reject) => {
let d = ''; let n = 0;
req.on('data', c => { n += c.length; if (n > 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;
}
// First sign-in to a waiting account made from a LinkSpin row (lsinbound.js): it becomes the person's own ordinary account.
// Its LinkSpin sponsor stands; one that arrived with no sponsor at all takes the link they signed in through, exactly as a
// brand-new account would (first InstantAdPay touch). Marked seen at once, so the sweeps count it from here on.
async function claimShell(email, shell, ref) {
try {
if (!shell.sponsorRef && ref) { const tok = String(ref).toLowerCase(); let sp = await accounts.byCode(tok); if (!sp) sp = await accounts.byUsername(tok); if (sp && sp.email !== email) await accounts.setSponsorRef(email, ref); }
await accounts.touchSeen(email);
console.log('linkspin waiting account claimed', email.replace(/^(.).*(@.*)$/, '$1***$2'), shell.sponsorRef ? 'sponsor ' + shell.sponsorRef : (ref ? 'sponsor from link ' + ref : 'no sponsor'));
} catch (e) { console.error('claimShell', e.message); }
}
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
// Payment trace (Marty, 2026-09-16): every purchase a member is involved in, tier by tier — who was
// paid, who was skipped and why (with how many qualifying buyers the skipped person had at that block)
// — so "why didn't X get paid on Y's buy" becomes a self-serve lookup instead of a support thread.
async function nameForMember(id) {
try { const a = await accounts.byMemberId(id); if (a && a.username) return a.username; } catch (e) {}
if (db.enabled()) { // a linked extra wallet: name it after its owner
try { const r = await db.q('SELECT email FROM positions WHERE member_id=? LIMIT 1', [Number(id)]); if (r.length) { const a = await accounts.byEmail(r[0].email); if (a && a.username) return a.username + ' (linked wallet)'; } } catch (e) {}
}
return null;
}
function sponsorMapFromIndex(evs) { const m = new Map(); for (const e of evs) if (e.type === 'MemberActivated' && e.id) m.set(e.id, Number(e.sponsorId) || 0); return m; }
function uplineIds(map, id, hops) { const out = []; let cur = map.get(Number(id)) || 0; for (let i = 0; i < hops && cur; i++) { out.push(cur); cur = map.get(cur) || 0; } return out; }
async function tracePurchases(targetId, limit) {
const id = Number(targetId) || 0; if (!id) return { error: 'Which member?' };
const evs = chain.recentEvents(1e9); // whole history, newest first
const byTx = new Map();
for (const e of evs) { if (!e.tx) continue; let g = byTx.get(e.tx); if (!g) { g = []; byTx.set(e.tx, g); } g.push(e); }
const counted = evs.filter(e => e.type === 'BuyerCounted');
const buyersBefore = (sid, block) => counted.filter(e => e.sponsorId === sid && e.block < block).length;
const out = [];
for (const e of evs) {
if (e.type !== 'Purchase') continue;
const g = byTx.get(e.tx) || [];
const paid = g.filter(x => x.type === 'TierPaid' && x.buyerId === e.buyerId);
const skipped = g.filter(x => x.type === 'PassedUp' && x.buyerId === e.buyerId);
const act = g.find(x => x.type === 'MemberActivated' && x.id === e.buyerId);
const admin = g.find(x => x.type === 'AdminPaid' && x.buyerId === e.buyerId);
const involved = e.buyerId === id || paid.some(x => x.recipientId === id) || skipped.some(x => x.skippedId === id) || (act && act.sponsorId === id);
if (!involved) continue;
const tiers = [1, 2, 3].map(t => {
const p = paid.find(x => x.tier === t); const sk = skipped.filter(x => x.tier === t);
return { tier: t, pct: [50, 20, 10][t - 1], paidTo: p ? p.recipientId : 0, amountWei: p ? p.amountWei : '0', hops: p ? p.hops : 0,
skipped: sk.map(x => ({ id: x.skippedId, reason: x.reason, buyersThen: x.reason === 'unqualified' ? buyersBefore(x.skippedId, e.block) : null })) };
});
out.push({ ts: e.ts, block: e.block, tx: e.tx, buyerId: e.buyerId, sponsorId: act ? act.sponsorId : null, priceCents: e.priceCents, paidWei: e.paidWei, tiers, adminWei: admin ? admin.amountWei : '0' });
if (out.length >= (limit || 30)) break;
}
const ids = new Set([id]);
for (const p of out) { ids.add(p.buyerId); if (p.sponsorId) ids.add(p.sponsorId); for (const t of p.tiers) { if (t.paidTo) ids.add(t.paidTo); for (const x of t.skipped) ids.add(x.id); } }
const names = {}; for (const i of ids) { const n = await nameForMember(i); if (n) names[i] = n; }
const smap = sponsorMapFromIndex(evs);
return { memberId: id, name: names[id] || null, activated: smap.has(id), sponsorId: smap.get(id) || 0, buyersNow: counted.filter(e => e.sponsorId === id).length, purchases: out, names };
}
async function attachNames(evts) {
try {
const ids = [];
for (const ev of evts)
for (const k of ['id', 'buyerId', 'recipientId', 'skippedId', 'sponsorId', 'newBuyerId', 'toId', 'memberId'])
if (ev[k]) ids.push(ev[k]);
const names = await accounts.namesForMembers(ids);
if (!Object.keys(names).length) return evts;
return evts.map(ev => Object.assign({}, ev, { names }));
} catch (e) { return evts; }
}
// A sponsor token is a numeric chain id or a site share code. Codes resolve
// to the referrer's CURRENT chain id, so activation any time before the
// referral's first purchase still locks the line to them.
// No-payout positions (siteConfig.noPayoutIds): a member id whose on-chain wallet must never be paid again.
// A purchase pays the buyer's three uplines, so a buy from `id` is blocked when id itself or any of its three
// uplines is listed; a join under `id` is blocked when id or its two uplines is listed (the new member's buys
// would reach the listed wallet at tier 2 or 3). Returns the listed id that would be hit, else 0.
function noPayoutSet() { return new Set(String(siteConfig().noPayoutIds || '').split(/[,\s]+/).map(Number).filter(n => n > 0)); }
async function payoutChainBlocked(id, hops) {
const bad = noPayoutSet(); if (!bad.size || !id) return 0;
let cur = Number(id);
for (let i = 0; i <= hops && cur; i++) { if (bad.has(cur)) return cur; let m = null; try { m = await chain.member(cur); } catch (e) { break; } cur = m ? Number(m.sponsorId) || 0 : 0; }
return 0;
}
// Why a sponsor token did not resolve matters (vladz79 → #24 locked under the company on 2026-09-13 because a
// lookup came back empty and the code fell back silently): 'ok' | 'none' (no token) | 'unknown' (no such account)
// | 'notActivated' (sponsor has no wallet / payouts off) | 'rpc' (chain lookup failed right now).
async function resolveSponsorDetailed(tok) {
const t = String(tok || '').trim().toLowerCase();
if (!t) return { id: 0, reason: 'none' };
if (/^\d+$/.test(t)) return { id: Number(t), reason: 'ok' };
let acct = await accounts.byCode(t);
if (!acct) acct = await accounts.byUsername(t); // vanity links: /join/<username>
if (!acct) return { id: 0, reason: 'unknown', name: t };
if (!acct.address) return { id: 0, reason: 'notActivated', name: acct.username ? '@' + acct.username : t };
try { const id = await chain.memberIdByAccount(acct.address); return { id, reason: id ? 'ok' : 'notActivated', name: acct.username ? '@' + acct.username : t }; }
catch (e) { return { id: 0, reason: 'rpc', name: acct.username ? '@' + acct.username : t }; }
}
async function resolveSponsorToken(tok) { return (await resolveSponsorDetailed(tok)).id; }
// 2026-09-16 (Marty): a buyer is never held up because their sponsor has not activated. Walk the
// site's sponsor line upward to the first upline who can be paid on-chain (activated, payouts on,
// not on the no-payout list); none -> the catch position (#1, Marty's top). The referral then follows
// the money: sponsorSyncOnEvent re-points the buyer's account to whoever was paid once the position exists.
async function walkUpActivatedSponsor(tok) {
const skipped = []; const seen = new Set();
const t = String(tok || '').trim().toLowerCase();
let acct = await accounts.byCode(t); if (!acct) acct = await accounts.byUsername(t);
for (let hop = 0; acct && hop < 25 && !seen.has(acct.email); hop++) {
seen.add(acct.email);
const name = acct.username ? '@' + acct.username : acct.email.replace(/@.*/, '') + '@';
let id = 0;
if (acct.address) { try { id = await chain.memberIdByAccount(acct.address); } catch (e) { return { id: 0, name: null, skipped, reason: 'rpc' }; } }
if (id && !(await payoutChainBlocked(id, 2))) return { id, name, skipped, reason: 'ok' };
skipped.push({ email: acct.email, name });
acct = await accounts.sponsorOf(acct.email);
}
return { id: 0, name: null, skipped, reason: 'none' };
}
// The feed line for a walk-up: who had not switched on payouts, whose referral (and purchase, when the
// activation and the buy share a tx) routed past them, and who it belongs to now.
async function postWalkUp(buyerId, oldRef, toId, pur) {
const sc = siteConfig(); if (!sc.telegramBotToken || (!sc.telegramChatId && !sc.telegramEchoChatId)) return;
const lostAcct = await refAccount(oldRef); if (!lostAcct) return;
const lostName = lostAcct.username ? '@' + lostAcct.username : lostAcct.email.replace(/@.*/, '') + '@';
const nm = await accounts.namesForMembers([buyerId, toId]).catch(() => ({}));
const who = id => '#' + id + (nm[id] ? ' @' + nm[id] : '');
const site = 'https://instantadpay.com/my';
const what = pur ? who(buyerId) + "'s $" + Math.round(pur.priceCents / 100) + ' purchase routed past them' : who(buyerId) + ' switched on payouts and their position routed past them';
const missed = '\u{1F62C} <b>Missed sale</b>: ' + lostName + ' had not switched on payouts, so ' + what + '. That member, and every payout from them, now belongs to ' + who(toId) + '.'
+ '\nTwo minutes on the Wallet tab prevents this: <a href="' + site + '#wallet">' + site.replace(/^https:\/\//, '') + '</a>';
if (sc.telegramChatId && String(sc.telegramEvents || 'payouts') !== 'none') await telegramSend(sc.telegramChatId, missed, sc.telegramTopicId).catch(() => {});
if (sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> \u00b7 ' + missed, sc.telegramEchoTopicId).catch(() => {});
}
// The referral follows the money (Marty, 2026-09-16): when a position is created on-chain under a
// different sponsor than the account's stored referrer (walk-up past an unactivated sponsor, or the
// catch-position fallback), move the account to the sponsor that actually got paid, #1 included.
async function sponsorSyncOnEvent(ev) {
if (!ev || ev.type !== 'MemberActivated' || !ev.account) return;
const acct = await accounts.byAddress(ev.account); if (!acct) return;
if (acct.address && acct.address.toLowerCase() !== String(ev.account).toLowerCase()) return; // a linked extra position, not the main wallet
const onchain = Number(ev.sponsorId) || 0; if (!onchain) return;
const spAcct = await accounts.byMemberId(onchain);
if (spAcct && spAcct.email === acct.email) return; // never self-sponsor an account
const cur = acct.sponsorRef ? (await resolveSponsorDetailed(acct.sponsorRef)).id : 0;
if (cur === onchain) return;
const ref = spAcct && spAcct.code ? spAcct.code : String(onchain);
const old = acct.sponsorRef || '';
await accounts.setSponsorRef(acct.email, ref);
movedByTx.set(ev.tx, { buyerId: Number(ev.id) || 0, toId: onchain, oldRef: old, at: Date.now(), posted: true }); // posted below, at activation; the Purchase branch stays quiet
// Post it now (Marty, 2026-09-21): the post used to wait for a Purchase in the same tx, so an activation that
// came first (switch on payouts, buy later) was never posted. The activation is the fact; it goes out here.
try { const pur = chain.recentEvents(1e9).find(x => x.tx === ev.tx && x.type === 'Purchase') || null; await postWalkUp(Number(ev.id) || 0, old, onchain, pur); } catch (e) { console.error('walk-up post', e.message); }
if (movedByTx.size > 200) { const k = movedByTx.keys().next().value; movedByTx.delete(k); }
console.log('referral moved to where the pay landed:', acct.email, JSON.stringify(old), '->', ref, '(#' + onchain + ')');
// Notices, now that it is a fact on the chain (Marty, 2026-09-16): everyone between the stored
// referrer and the paid sponsor who was simply not activated is told they lost this referral for
// good; the sponsor who was paid is told they gained it and should coach the one who missed it.
try {
const nameOf = a => a.username ? '@' + a.username : a.email.replace(/@.*/, '') + '@';
const toName = spAcct ? nameOf(spAcct) : 'the company (#' + onchain + ')';
const lost = []; const seen = new Set();
let x = await refAccount(old);
while (x && !seen.has(x.email) && (!spAcct || x.email !== spAcct.email) && lost.length < 25) {
seen.add(x.email);
let activated = false; if (x.address) { try { activated = !!(await chain.memberIdByAccount(x.address)); } catch (e) { activated = true; } }
if (!activated) lost.push(x); // an activated-but-excluded (no-payout) sponsor is an admin matter, not a "switch on payouts" lesson
x = await accounts.sponsorOf(x.email);
}
for (const l of lost) sponsorHoldNudge(l.email, acct.email, toName).catch(() => {});
if (spAcct && lost.length) sponsorGainNudge(spAcct, nameOf(acct), lost.map(nameOf)).catch(() => {});
} catch (e) { console.error('sponsor move notices', e.message); }
}
const movedByTx = new Map(); // tx -> { buyerId, toId, oldRef } for purchases routed past an unactivated sponsor
async function refAccount(ref) {
const t = String(ref || '').trim().toLowerCase(); if (!t) return null;
let a = await accounts.byCode(t); if (!a) a = await accounts.byUsername(t);
if (!a && /^\d+$/.test(t)) a = await accounts.byMemberId(Number(t));
return a || null;
}
const sponsorGainLast = new Map(); // sponsor email|buyer -> ts
async function sponsorGainNudge(sp, buyerName, lostNames) {
if (!sp || !sp.email) return;
const key = sp.email + '|' + buyerName; if (sponsorGainLast.has(key)) return; sponsorGainLast.set(key, Date.now());
const who = lostNames.length === 1 ? lostNames[0] : lostNames.slice(0, -1).join(', ') + ' and ' + lostNames[lostNames.length - 1];
const subject = buyerName + ' is now in your line for good (' + who + ' had not switched on payouts)';
const lines = [
buyerName + ' just bought an ad package on InstantAdPay. They came in through ' + who + ', but ' + (lostNames.length === 1 ? who + ' had' : 'they had') + ' not linked a wallet and switched on payouts, so the contract could not pay ' + (lostNames.length === 1 ? 'them' : 'any of them') + '. It walked up your line and paid you at level 1 instead.',
'That is permanent. The contract locks a buyer to the sponsor who was paid at their first purchase, so ' + buyerName + ' is in your line on the chain from now on: this purchase and every one after it pays you as their level 1. They now show under you in My line.',
'The lesson to pass down: ' + who + ' just lost a referral they worked for because payouts were off. Take two minutes with them, help them link a wallet and switch on payouts (Wallet tab, one free signature and one small transaction), and show them how to check it. Every leader in this line who teaches that step keeps their people from losing the next one.',
'My line: https://instantadpay.com/my#line'
];
const text = lines.join('\n\n');
if (mailer.hasKey()) mailer.send(sp.email, subject, text + '\n\nInstantAdPay').catch(() => {});
try {
const html = lines.map(l => '<p>' + l.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/(https:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>') + '</p>').join('');
await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [sp.email], subject, html, 'notice');
} catch (e) {}
}
// Partner-code credits arrive as a drip (Marty, 2026-09-19): a fifth on the day the code is
// redeemed, then a fifth on each day the member finishes their daily ad set, five days in all,
// nothing after 30 days. Same headline number for the partner to promote; paid only to people
// who show up. Member-funded codes charge the funder one installment at a time.
async function payPromo(email, day) {
return promos.payDue(email, day, async (r, amount, n) => {
if (r.funder && r.funder !== email) {
const ok = await ads.spendEarned(r.funder, amount, { log: { kind: 'promo', note: 'Partner code ' + r.code + ' funded for ' + email + ' (day ' + n + ' of ' + promos.STEPS + ')' } });
if (!ok) { console.log('promo funder short', r.code, r.funder); return false; }
}
await ads.addEarned(email, amount, { log: { kind: 'promo', note: 'Partner code ' + r.code + ': ' + amount + ' of ' + r.credits + ' (day ' + n + ' of ' + promos.STEPS + ')' } });
return true;
});
}
// anti-fraud admin alert (Telegram admin chat, else email): who, which flags, and whether the sign-up was blocked
// Send as a specific bot, for operational alerts that should arrive from Marty's own Hermes bot
// rather than from the member-facing InstantAdPay one.
function tgSendAs(token, chatId, text, threadId) {
return new Promise(resolve => {
const body = JSON.stringify(Object.assign({ chat_id: String(chatId), text, parse_mode: 'HTML', disable_web_page_preview: true },
threadId ? { message_thread_id: Number(threadId) } : {}));
const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + token + '/sendMessage', method: 'POST', timeout: 12000,
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } },
r => { r.resume(); resolve(r.statusCode === 200); });
rq.on('error', () => resolve(false));
rq.on('timeout', () => { rq.destroy(); resolve(false); });
rq.end(body);
});
}
// Help desk pings (2026-10-16): Marty's PRIVATE Telegram chat only, never a group, topic or feed. tgSendAs skips the
// Discord relay entirely. Site bot (telegramBotToken) first, Marty's Hermes bot if that one cannot reach him.
async function supportTelegram(text, ref) {
// the dedicated support bot (two-way: buttons + replies) goes first; the old one-way path stays as the fallback
if (supportbot.enabled() && await supportbot.ping(text, ref)) return true;
const sc = siteConfig();
const chat = String(sc.supportTelegramChat || '1289244227').trim();
if (!/^\d{4,15}$/.test(chat)) { console.error('support ping refused: supportTelegramChat must be a private chat id (positive number), not', chat); return false; }
let ok = false;
const site = String(sc.telegramBotToken || '').trim(), hermes = String(process.env.HERMES_BOT_TOKEN || '').trim();
if (site) ok = await tgSendAs(site, chat, text);
if (!ok && hermes) ok = await tgSendAs(hermes, chat, text);
if (!ok) console.error('support ping not delivered (chat ' + chat + ', site bot ' + (site ? 'set' : 'missing') + ', hermes ' + (hermes ? 'set' : 'missing') + ')');
return ok;
}
// Public support form + signed-out chatbot hand-off: 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. Returns null to allow, or { status, body }.
const SUPPORT_LIMITS = { ipHour: 5, ipDay: 15, emailHour: 3, emailDay: 8, globalPerMin: 20, minFormMs: 2000 };
const supportHits = new Map(); // 'ip:<ip>' | 'em:<email>' | 'tk:<ticket id>' -> [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 InstantAdPay members. Use the email on your InstantAdPay account, or sign in first. Not a member yet? Join free at https://instantadpay.com/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;
const fage = (b.fage !== undefined && b.fage !== null && b.fage !== '' && Number.isFinite(Number(b.fage))) ? Number(b.fage) : (fts ? now - fts : -1);
if (fage < SUPPORT_LIMITS.minFormMs) { guardLog(req, 'support form-age', b); return { status: 400, body: { error: 'Give the page a few seconds, then send again.' } }; }
if (fage > 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;
}
// LinkSpin's Engine Room facts for one member (signed /api/partner/engine), cached a minute; null when LinkSpin does not answer
const lsEngineCache = new Map();
async function engineFromLinkSpin(email, fresh) {
const hit = lsEngineCache.get(email); if (!fresh && hit && Date.now() - hit.at < 60000) return hit.v;
let v = null; try { const r = await SF.peerPost(LS_BASE(), '/api/partner/engine', { email }, 6000); v = r && r.facts ? r.facts : null; } catch (e) { v = null; }
lsEngineCache.set(email, { at: Date.now(), v }); if (lsEngineCache.size > 2000) lsEngineCache.delete(lsEngineCache.keys().next().value);
return v;
}
// LinkSpin partner calls (registry rows, help desk): one secret both ways, LS_SYNC_SECRET, as X-LS-Ts (ms) + X-LS-Sig =
// hex HMAC-SHA256(ts + newline + raw body), 10-minute window. Resolves { body } or { status, error }.
async function readLsSigned(req, maxBytes) {
const secret = String(process.env.LS_SYNC_SECRET || '').trim(); if (secret.length < 32) return { status: 503, error: 'sync not configured' };
const 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); });
const ts = String(req.headers['x-ls-ts'] || ''), sig = String(req.headers['x-ls-sig'] || '');
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return { status: 401, error: 'stale' };
const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' };
try { return { body: JSON.parse(raw || '{}') }; } catch (e) { return { status: 400, error: 'bad json' }; }
}
function fraudAlert(email, fc, spAcct, blocked) {
try {
const sc = siteConfig();
const text = (blocked ? '\u26D4 InstantAdPay sign-up BLOCKED: ' : '\u{1F6A9} InstantAdPay sign-up flagged: ') + String(email).replace(/^(.{2}).*(@.*)$/, '$1***$2')
+ ' [' + (fc.flags || []).join(', ') + ']' + (fc.ip ? ' ip ' + fc.ip : '') + (spAcct ? ' sponsor ' + (spAcct.username ? '@' + spAcct.username : spAcct.email) : '') + '. Admin > Members > Duplicate signals.';
if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {});
else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: sign-up ' + (blocked ? 'blocked' : 'flagged'), text).catch(() => {});
} catch (e) {}
}
const sponsorRoutedLast = new Map(); // buyer email -> ts (one alert per buyer per hour)
function sponsorRoutedAlert(who, spd, routed, skipped) {
const k = String(who || '?'); if (Date.now() - (sponsorRoutedLast.get(k) || 0) < 3600000) return; sponsorRoutedLast.set(k, Date.now());
const text = '\u2934\uFE0F InstantAdPay heads-up: ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + ' is at checkout. Their sponsor ' + (spd.name || '?')
+ ' has not switched on payouts, so if this purchase goes through it pays ' + routed.to + ' instead.' + (skipped.length > 1 ? ' Also skipped: ' + skipped.map(x => x.name).join(', ') + '.' : '')
+ ' Nothing has been paid yet; the on-chain result posts to Telegram when the sale settles.';
const sc = siteConfig();
if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {});
else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay heads-up: a checkout will route past an unactivated sponsor', text).catch(() => {});
// the skipped sponsor and the one who gains are told by sponsorSyncOnEvent, once the position exists on the chain
}
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 InstantAdPay: purchase held for ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + '. Their sponsor ' + (r.name || r.tok || '?') + ' could not be resolved (' + r.reason + '), so the buy was blocked instead of crediting the company. ' + (r.reason === 'notActivated' ? 'The sponsor needs to switch on payouts.' : r.reason === 'rpc' ? 'Chain lookup failed; they can retry.' : 'Check the sponsor field in Admin > Members.');
const sc = siteConfig();
if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {});
else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: purchase held, sponsor unresolved', text).catch(() => {});
// and the sponsor themselves (Marty, 2026-09-15): a buy is waiting on them, once an hour at most
if (r.reason === 'notActivated') sponsorHoldNudge(String(r.tok || ''), k).catch(() => {});
}
const sponsorNudgeLast = new Map(); // sponsor email -> ts
async function sponsorHoldNudge(tok, buyerEmail, routedTo) {
const t = String(tok || '').trim().toLowerCase(); if (!t) return;
let sp = t.includes('@') ? await accounts.byEmail(t) : null;
if (!sp) sp = await accounts.byCode(t); if (!sp) sp = await accounts.byUsername(t);
if (!sp || !sp.email) return;
if (Date.now() - (sponsorNudgeLast.get(sp.email) || 0) < 3600000) return; sponsorNudgeLast.set(sp.email, Date.now());
const buyer = await accounts.byEmail(buyerEmail); const bn = buyer && buyer.username ? '@' + buyer.username : 'One of your referrals';
const step = !sp.address ? 'link a wallet and switch on payouts' : 'switch on payouts';
const subject = routedTo
? 'You lost ' + bn + ' to ' + routedTo + ' (payouts were not switched on)'
: bn + ' is trying to buy. ' + (sp.address ? 'Switch on payouts' : 'Link your wallet') + ' so it pays you';
const lines = routedTo ? [
'You just lost a sale. ' + bn + ' is buying an ad package on InstantAdPay right now, and because payouts are not switched on for your account, the contract cannot pay you. The purchase is paying ' + routedTo + ' instead.',
'This is permanent. The contract locks a buyer to the sponsor who was paid at their first purchase, so ' + bn + ' now belongs to ' + routedTo + ', has moved out of your line, and will never pay you from that wallet. Nothing can bring that referral back.',
'The next one does not have to go the same way. Open the Wallet tab and ' + step + '. One free signature to link, one small transaction to switch on. Two minutes, and every purchase in your line from then on pays you the moment it happens.',
'Wallet tab: https://instantadpay.com/my#wallet'
] : [
bn + ' just tried to buy an ad package on InstantAdPay, and the purchase is on hold because payouts are not switched on for your account yet. The contract pays your share in the same transaction, but only to a wallet that is switched on, so the site paused the buy instead of sending your 50 percent to someone else.',
'To fix it: open the Wallet tab and ' + step + '. One free signature to link, one small transaction to switch on. Takes two minutes, and every purchase in your line from then on pays you the moment it happens.',
'Until then their purchase waits, and they have been told why.',
'Wallet tab: https://instantadpay.com/my#wallet'
];
const text = lines.join('\n\n');
if (mailer.hasKey()) mailer.send(sp.email, subject, text + '\n\nInstantAdPay').catch(() => {});
try {
const html = lines.map(l => '<p>' + l.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/(https:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>') + '</p>').join('');
await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [sp.email], subject, html, 'alert');
} catch (e) {}
}
// 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 $20+ 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 InstantAdPay through your link — they are on your team from today.\n\n'
+ 'They count toward your qualification once they make a $20+ 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: https://instantadpay.com/my\n\nInstantAdPay';
mailer.send(owner.email, 'You have a new referral on InstantAdPay', 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 InstantAdPay',
'Your free InstantAdPay 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: https://instantadpay.com/my\n\nInstantAdPay').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: https://instantadpay.com/ledger\n\nInstantAdPay', null, { transactional: true }).catch(() => {}); // receipts + payouts: sent even after an unsubscribe
};
// 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, kind) => {
if (!memberId) return;
try {
const a = await accounts.byMemberId(memberId);
if (!a || !a.email) return;
const html = '<p>' + String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/(https:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>';
await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice');
} catch (e) {}
};
const tell = async (memberId, subject, text, kind) => { await notify(memberId, subject, text); await inboxNote(memberId, subject, text, kind); };
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(1e9).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 InstantAdPay 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 >= 2000
? ' This is a $20+ purchase, so it counts toward your qualification.'
: ' (Purchases under $20 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: https://instantadpay.com/my\n\nInstantAdPay').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);
// BixPay (2026-10-29): one sentence after the amount, the recipient's resolved partner link behind a counted /go link; only while live
let bixLine = ''; try { if (bixpay.live()) { const ra = await accounts.byMemberId(ev.recipientId); bixLine = bixpay.emailLine(ra ? (ra.username || ra.code) : ''); } } catch (e) { bixLine = ''; }
await tell(ev.recipientId, 'You just got paid ' + pol + ' POL on InstantAdPay',
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' +
(bixLine ? bixLine + '\n\n' : '') + 'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour dashboard: https://instantadpay.com/my');
}
else if (ev.type === 'AwardPaid') {
const ov = override.txInfo(ev.tx); // a level-4 override payment from the weekly payer
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 earnings: https://instantadpay.com/my#earnings', 'notice');
else await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on InstantAdPay', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour dashboard: https://instantadpay.com/my');
}
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 InstantAdPay', '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, 'InstantAdPay: 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 InstantAdPay',
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 $20 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 dashboard: https://instantadpay.com/my', 'alert');
}
}
// 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] : '');
// a brand-new chain id is not mapped to its account yet when the activation lands, so the line read bare "#200" (Marty 2026-10-11): name them by wallet
if (ev.type === 'MemberActivated' && ev.id && !names[ev.id] && ev.account) { const a = await accounts.byAddress(ev.account).catch(() => null); if (a && a.username) names[ev.id] = a.username; }
const cc = chain.getConfig();
const tx = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx;
const build = async (mode) => {
let line = null;
// Tier payouts and the purchase itself are no longer posted one by one: they are composed
// into ONE message on AdminPaid, the last event of every purchase tx, so the feed reads
// "who bought what, then who was paid" (Marty, 2026-09-25). In payouts mode a purchase that
// paid no member (root or unsponsored buyer) stays silent, as before.
if (ev.type === 'AdminPaid') {
const txEvents = chain.recentEvents(1e9).filter(x => x.tx === ev.tx);
const ids = new Set(); txEvents.forEach(x => { for (const k of ['buyerId', 'recipientId', 'skippedId']) if (x[k]) ids.add(x[k]); });
const nm = await accounts.namesForMembers([...ids]).catch(() => ({}));
line = feedgroup.compose(txEvents, id => '#' + id + (nm[id] ? ' @' + nm[id] : ''), weiToPol, { requirePayout: mode === 'payouts' });
}
else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has <b>' + ev.newCount + '</b> qualifying buyer' + (ev.newCount === 1 ? '' : 's') + (ev.newCount === 2 ? ' \u00b7 level 2 open' : ev.newCount === 5 ? ' \u00b7 level 3 open' : '');
else if (ev.type === 'AwardPaid') line = '\u{1F4B8} ' + (override.txInfo(ev.tx) ? 'Level 4 override' : 'Award payout') + ': <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.toId);
else if (ev.type === 'MemberActivated' && mode === 'all') line = '\u{1F91D} ' + who(ev.id) + ' switched on payouts';
if (!line) return null;
return line + ' \u00b7 <a href="' + tx + '">verify</a>' + (sc.telegramCtaUrl ? '\n<a href="' + sc.telegramCtaUrl + '">Join free</a>' : '');
};
// Missed-payout lines (Marty, 2026-09-16): when a share is passed over, say who missed it and who got it.
// (a) on-chain pass-up: the TierPaid with hops>0 follows the PassedUp events of the same tx, already indexed.
// (b) off-chain walk-up past an unactivated sponsor: recorded by sponsorSyncOnEvent, posted on the Purchase.
let missed = null;
try {
const site = 'https://instantadpay.com/my';
// (a) on-chain pass-ups: AdminPaid is the last event of every purchase tx, so by then every
// PassedUp and TierPaid of the tx is indexed; one message shows the whole chain (missed.js).
if (ev.type === 'AdminPaid') {
const all = chain.recentEvents(1e9);
const txEvents = all.filter(x => x.tx === ev.tx);
if (txEvents.some(x => x.type === 'PassedUp')) {
const ids = new Set(); txEvents.forEach(x => { for (const k of ['buyerId', 'skippedId', 'recipientId']) if (x[k]) ids.add(x[k]); });
const nm2 = await accounts.namesForMembers([...ids]).catch(() => ({}));
const who2 = id => '#' + id + (nm2[id] ? ' @' + nm2[id] : '');
const had = (id, tier) => all.filter(y => y.type === 'BuyerCounted' && y.sponsorId === id && y.block < ev.block).length;
missed = missedNotice.composeMissed(txEvents, who2, had, site);
}
}
if (ev.type === 'Purchase' && movedByTx.has(ev.tx) && !movedByTx.get(ev.tx).posted) { // legacy path; walk-ups now post at activation
const mv = movedByTx.get(ev.tx); movedByTx.delete(ev.tx);
const lostAcct = await refAccount(mv.oldRef);
if (lostAcct) {
const lostName = lostAcct.username ? '@' + lostAcct.username : lostAcct.email.replace(/@.*/, '') + '@';
const nm3 = await accounts.namesForMembers([mv.toId]).catch(() => ({}));
missed = '\u{1F62C} <b>Missed sale</b>: ' + lostName + ' had not switched on payouts, so ' + who(ev.buyerId) + "'s $" + Math.round(ev.priceCents / 100) + ' purchase routed past them. That buyer, and every payout from them, now belongs to #' + mv.toId + (nm3[mv.toId] ? ' @' + nm3[mv.toId] : '') + ' for good.'
+ '\nTwo minutes on the Wallet tab prevents this: <a href="' + site + '#wallet">' + site.replace(/^https:\/\//, '') + '</a>';
}
}
} catch (e) { console.error('missed-payout post', e.message); }
// the main group used to get bare payout lines with no product name: nobody knew what they were from
const brand = t => '\u{1F7E0} <b>InstantAdPay</b>\n' + t;
if (sc.telegramChatId) { const t = await build(String(sc.telegramEvents || 'payouts')); if (t) await telegramSend(sc.telegramChatId, brand(t), sc.telegramTopicId); if (missed && String(sc.telegramEvents || 'payouts') !== 'none') await telegramSend(sc.telegramChatId, missed, sc.telegramTopicId).catch(() => {}); }
if (sc.telegramEchoChatId) { const t = await build(String(sc.telegramEchoEvents || 'payouts')); if (t) await telegramSend(sc.telegramEchoChatId, brand(t), sc.telegramEchoTopicId); }
if (missed && sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> \u00b7 ' + missed, sc.telegramEchoTopicId).catch(() => {});
}
// 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);
const fresh = (await tank.waiting()).filter(w => (w.joined || 0) > since);
st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st));
if (!fresh.length) return;
const named = fresh.filter(w => w.username).map(w => '@' + w.username);
const who = named.length ? ': ' + named.slice(0, 8).join(', ') + (named.length > 8 ? ' and ' + (named.length - 8) + ' more' : '') : '';
const text = '\u{1FAA3} <b>InstantAdPay</b> \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who
+ '\nAdopt from My line \u203a Holding tank: <a href="https://instantadpay.com/my#line">instantadpay.com/my</a>';
await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId);
}
// a holding-tank pickup: the live feed + one line in the shared payments topic (manual adoptions since 2026-09-12;
// the 24-hour safety net says "(auto-assigned)", 2026-10-27)
function tankPickupPost(adopterName, adopteeName, auto) {
pushFeed({ type: 'Adopted', sponsor: adopterName, member: adopteeName, ts: Date.now() });
try {
const sc = siteConfig();
const clean = t => String(t || '').replace(/[<>&]/g, '');
if (sc.telegramBotToken && sc.telegramEchoChatId)
telegramSend(sc.telegramEchoChatId, '\u{1F91D} <b>InstantAdPay</b> \u00b7 <b>' + clean(adopterName) + '</b> picked up <b>' + clean(adopteeName) + '</b> from the holding tank and is now their sponsor' + (auto ? ' (auto-assigned)' : ''), sc.telegramEchoTopicId).catch(() => {});
} catch (e) {}
}
// admin-only channels (never a member-visible topic: it names an email), the same order as the video-sweep alerts
async function tankAdminAlert(text) {
const sc = siteConfig(); const hermes = String(process.env.HERMES_BOT_TOKEN || '').trim();
const html = String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
if (hermes && sc.telegramAdminChatId) return tgSendAs(hermes, sc.telegramAdminChatId, html);
if (sc.telegramBotToken && sc.telegramAdminChatId) return telegramSend(sc.telegramAdminChatId, html);
if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'InstantAdPay: holding tank needs an adopter', text);
console.log('tank: no admin channel configured, alert not sent:', text);
}
// holding tank every 15 min (2026-10-27): 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
async function tankReadyTick() {
const r = await tank.readyTick();
if (r.aligned || r.assigned.length || r.held || r.fresh.length || (r.reminders || []).length) console.log('tank ready tick', JSON.stringify({ fresh: r.fresh.length, aligned: r.aligned, assigned: r.assigned.length, held: r.held, payReminders: (r.reminders || []).map(x => x.stage) }));
const sc = siteConfig();
if (!r.fresh.length || !sc.telegramBotToken || !sc.telegramEchoChatId) return r;
const clean = t => String(t || '').replace(/[<>&]/g, '');
const link = 'https://instantadpay.com/my#line';
if (r.fresh.length <= 3) {
// a fresh link says so; a wallet that predates this tank visit (a dormant member returned by a sponsor) says "already
// linked" with the last sign-in, so adopters can judge (Marty 2026-10-29: the old wording read as a live member)
const seen = ms => { try { return new Date(ms).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'America/Chicago' }); } catch (e) { return ''; } };
for (const w of r.fresh) await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} ' + (w.username ? '@' + clean(w.username) : 'A new member')
+ (w.linkedNow ? ' linked a wallet and is ready to switch on payouts. Adopt them from the holding tank in the next 24 hours: '
: ' is in the holding tank with a wallet already linked' + (w.lastSeen ? ' (last seen ' + seen(w.lastSeen) + ')' : '') + '. Adopt them in the next 24 hours: ') + 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} ' + r.fresh.length + ' members in the holding tank have a wallet linked 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 24 hours: ' + 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;
discordRelay.mirror({ chatId, threadId, text });
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 => {
// say what happened: a feed that fails silently is indistinguishable from a quiet day (2026-09-25)
let raw = ''; r.setEncoding('utf8'); r.on('data', d => { raw += d; });
r.on('end', () => { let j = null; try { j = JSON.parse(raw); } catch (e) {}
if (j && j.ok) console.log('tg-ok chat=' + chatId + (threadId ? ' thread=' + threadId : '') + ' message_id=' + (j.result && j.result.message_id));
else console.error('tg-fail chat=' + chatId + (threadId ? ' thread=' + threadId : '') + ' http=' + r.statusCode + ' ' + ((j && j.description) || raw.slice(0, 160)));
resolve(); });
});
rq.on('error', e => { console.error('tg-fail chat=' + chatId + ' network: ' + e.message); resolve(); });
rq.on('timeout', () => { console.error('tg-fail chat=' + chatId + ' 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;
discordRelay.mirror({ chatId, threadId, text: caption, photo: jpeg });
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 = { 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'], fridays: ['Five Fridays', 'five Five Dollar Fridays in a row'], gamepass: ['Game Pass', 'Game Pass holder'],
refuelStart: ['Engine Started', 'first monthly refuel'], refuel3: ['Refueled 3 months', 'three monthly refuels in a row'], refuel6: ['Refueled 6 months', 'six monthly refuels in a row'], refuel12: ['Refueled 12 months', 'twelve monthly refuels in a row'] };
const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json');
function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } }
// Post a member's badge to the payments topic + General ONCE ever (the same card and caption as an unlock). Used by the
// automatic Friday Game Pass perk; returns how many chats it reached (0 when already posted or not configured).
async function postBadgeOnce(email, key, note) {
const e = String(email || '').toLowerCase(); const log = badgeLog(); const mine = log[e] || {}; if (mine[key] || !BADGE_META[key]) return 0;
const a = await accounts.byEmail(e); if (!a) return 0;
const who = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'a member');
const link = a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com';
const [label, sub] = BADGE_META[key];
const caption = '\u{1F3C6} <b>InstantAdPay</b> · <b>' + who.replace(/[<>&]/g, '') + '</b> unlocked <b>' + label + '</b>: ' + sub + (note ? ' · ' + note : '') + '\n' + link;
const jpeg = await badge.render(key, a.username || ('member #' + a.memberId)); if (!jpeg) return 0;
mine[key] = { ts: Date.now(), sent: 0, auto: note || true }; log[e] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (er) {} // claim first: no double post
const sc = siteConfig(); let sent = 0;
if (sc.telegramBotToken && sc.telegramEchoChatId) {
if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++;
if (String(sc.telegramBadgeGeneral || '1') !== '0' && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++;
}
mine[key].sent = sent; log[e] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (er) {}
pushFeed({ type: 'Badge', member: who, label, ts: Date.now() });
console.log('badge posted (auto)', e, key, 'sent', sent);
return sent;
}
// Five Dollar Friday Game Pass perk (Marty 2026-10-23: "this should happen automatically every Friday"): a $5+ package on a
// Friday (the Friday bonus landed, so it qualified) also gives the buyer a free 7-day Game Pass, once per member per Friday.
// A purchase that itself started a paid pass gets no second week on top. The Game Pass badge posts only the first time a
// member ever holds a pass. Counts as no sale (comp). Switch: site setting fridayPassPerk '0' turns it off.
async function fridayPassPerk(ev, bonus, gp) {
if (!(Number(bonus) > 0) || gp) return null;
if (String(siteConfig().fridayPassPerk || '1') === '0' || !gamepass.cfg().enabled) return null;
const a = await accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null;
const ms = Number(ev.ts) > 1e12 ? Number(ev.ts) : (Number(ev.ts) > 0 ? Number(ev.ts) * 1000 : Date.now());
const day = new Date(ms).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
if (!(await marks.claim('fdfpass:' + day + ':' + a.email))) return null; // once per member per Friday, across app copies
const r = gamepass.comp(a.email, 'Five Dollar Friday perk ' + day, 'weekly');
console.log('friday pass perk', a.email, day, 'until', new Date(r.until).toISOString());
try {
const until = new Date(r.until).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], 'Five Dollar Friday: a free Game Pass week', '<p>Your Friday package came with a free 7-day Game Pass, on top of the Friday bonus credits. It runs until ' + until + ' Central, across all ten games.</p>', 'notice');
} catch (e) { console.error('friday pass notice', e.message); }
try { await postBadgeOnce(a.email, 'gamepass', 'Five Dollar Friday'); } catch (e) { console.error('friday pass badge', e.message); }
return r;
}
// ---- 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); } }
}
// ---- server ----
// -- Drip Runner (2026-09-30): the hand-off, refuel visits and the signed callback to the game.
// Tokens share PolHunter's shape (base64url payload . base64url HMAC) under a separate secret.
const DR_SECRET = () => String(process.env.DR_SSO_SECRET || '').trim();
const DR_URL = () => String(process.env.DR_URL || 'https://driprunner.saasy.top').replace(/\/+$/, '');
const drB64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
const drSign = payload => drB64u(crypto.createHmac('sha256', DR_SECRET()).update(payload).digest());
function drMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + drSign(payload); }
function drOpen(token) {
if (DR_SECRET().length < 32) return { error: 'Drip Runner is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = drSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That refuel link has expired. Go back to the game and tap Refuel again.' };
return { ok: true, claims: c };
}
const refuelTokens = new Map(); // nonce -> { email, memberId, id, title, target, ts, ret, challenge, done }
async function drCallback(body) {
const raw = JSON.stringify(body); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', DR_SECRET()).update(ts + '\n' + raw).digest('hex');
try { const r = await fetch(DR_URL() + '/api/refuel/callback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-DR-Ts': ts, 'X-DR-Sig': sig }, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; }
catch (e) { console.warn('driprunner callback', e.message); return false; }
}
// -- Gem Kingdom (2026-10-01): sign-in hand-off + the Crown shop checkout. Same token shape as Drip Runner, its own
// secret GK_SSO_SECRET (also set on the game). The game mints a 'gk-buy' order; this site shows the member what it
// costs, spends the ad credits through ads.gamePurchase (credit log + on-chain burn like any flat buy), then signs a
// 'gk-receipt' back: as a redirect to the game AND as a server-to-server callback, so Crowns land even if they never return.
const GK_SECRET = () => String(process.env.GK_SSO_SECRET || '').trim();
const GK_URL = () => String(process.env.GK_URL || 'https://gemkingdom.app').replace(/\/+$/, '');
const gkSign = p => drB64u(crypto.createHmac('sha256', GK_SECRET()).update(p).digest());
function gkMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + gkSign(payload); }
function gkOpen(token) {
if (GK_SECRET().length < 32) return { error: 'Gem Kingdom is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = gkSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That order has expired. Go back to Gem Kingdom and open the shop again.' };
return { ok: true, claims: c };
}
const gkOrders = persistedMap('gkorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts }
const gkEsc = s => String(s == null ? '' : s).replace(/[&<>"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[ch]));
function gkPage(res, code, title, inner, head) {
res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }));
res.end('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + gkEsc(title) + ' | InstantAdPay</title>' + (head || '')
+ '<style>body{margin:0;background:radial-gradient(ellipse 80% 50% at 50% 0%,#3B1E6E,#1B1026 70%);color:#3B1A0A;font:16px/1.5 system-ui,-apple-system,Segoe UI,sans-serif;min-height:100vh;display:grid;place-items:center;padding:24px 16px;box-sizing:border-box}'
+ '.card{width:100%;max-width:440px;background:linear-gradient(180deg,#F1E2BF,#E3CC98);border-radius:12px;box-shadow:0 0 0 3px #6B4220,0 0 0 8px #3A2214,0 24px 60px rgba(0,0,0,.6);padding:26px 22px;text-align:center}'
+ 'h1{font:700 26px/1.2 Georgia,serif;margin:0 0 6px}.sub{color:#5A3416;font-weight:700;margin:0 0 16px}.big{font:700 40px/1 Georgia,serif;color:#9A5A00;margin:8px 0}'
+ '.row{display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid rgba(90,52,22,.25);font-weight:700}.row span:first-child{color:#6A4422}'
+ '.btn{display:block;width:100%;box-sizing:border-box;margin-top:16px;padding:14px;border:0;border-radius:12px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font:700 18px Georgia,serif;text-decoration:none;cursor:pointer;box-shadow:0 4px 0 #6A0E1C}'
+ '.btn.blue{background:linear-gradient(180deg,#3B6FE8,#1D3FA8);box-shadow:0 4px 0 #10205A}.alt{display:inline-block;margin-top:14px;color:#5A3416;font-weight:700}.warn{color:#8A2A12;font-weight:800}.fine{font-size:13px;color:#6A4422;margin-top:14px}</style></head>'
+ '<body><main class="card">' + inner + '</main></body></html>');
}
function gkFormBody(req) { return new Promise((ok, no) => { let d = ''; req.on('data', ch => { d += ch; if (d.length > 20000) req.destroy(); }); req.on('end', () => ok(new URLSearchParams(d))); req.on('error', no); }); }
const gkCookie = (k, v, maxAge) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + maxAge + (IS_PROD ? '; Secure' : '');
// -- ClutterHunt (2026-10-03): seasonal hidden-object rooms at clutterhunt.com; its own secret SEEK_SSO_SECRET (also on the game)
const SEEK_SECRET = () => String(process.env.SEEK_SSO_SECRET || '').trim();
const SEEK_URL = () => String(process.env.SEEK_URL || 'https://clutterhunt.com').replace(/\/+$/, '');
const SEEK_ALT = () => String(process.env.SEEK_ALT_URLS || 'https://www.clutterhunt.com,https://clutterhunt.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
const seekSign = p => drB64u(crypto.createHmac('sha256', SEEK_SECRET()).update(p).digest());
function seekMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + seekSign(payload); }
// -- Shards of Valor (2026-10-18): multiplayer RPG at shardsofvalor.com; its own secret SOV_SSO_SECRET (also on the game).
// Same token shape as ClutterHunt; the Game Pass flag rides along (gpClaim). Not in the public games list until launch.
const SOV_SECRET = () => String(process.env.SOV_SSO_SECRET || '').trim();
const SOV_URL = () => String(process.env.SOV_URL || 'https://shardsofvalor.com').replace(/\/+$/, '');
const SOV_ALT = () => String(process.env.SOV_ALT_URLS || 'https://www.shardsofvalor.com,https://sov.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
const sovSign = p => drB64u(crypto.createHmac('sha256', SOV_SECRET()).update(p).digest());
function sovMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + sovSign(payload); }
function seekOpen(token) {
if (SEEK_SECRET().length < 32) return { error: 'ClutterHunt is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = seekSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That hint link has expired. Go back to ClutterHunt and tap Hint again.' };
return { ok: true, claims: c };
}
const seekIsGameUrl = u => [SEEK_URL()].concat(SEEK_ALT()).some(o => String(u || '').startsWith(o + '/'));
async function seekCallback(cbUrl, receipt) {
if (!seekIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('clutterhunt callback', e.message); return false; }
}
// -- SpellWheel (2026-10-04): the letter-wheel word game at spellwheel.com; its own secret SW_SSO_SECRET (also on the game)
const SW_SECRET = () => String(process.env.SW_SSO_SECRET || '').trim();
const SW_URL = () => String(process.env.SW_URL || 'https://spellwheel.com').replace(/\/+$/, '');
const SW_ALT = () => String(process.env.SW_ALT_URLS || 'https://www.spellwheel.com,https://spellwheel.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
const swSign = p => drB64u(crypto.createHmac('sha256', SW_SECRET()).update(p).digest());
function swMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + swSign(payload); }
function swOpen(token) {
if (SW_SECRET().length < 32) return { error: 'SpellWheel is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = swSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That hint link has expired. Go back to SpellWheel and tap Hint again.' };
return { ok: true, claims: c };
}
const swIsGameUrl = u => [SW_URL()].concat(SW_ALT()).some(o => String(u || '').startsWith(o + '/'));
// -- PolyBreak (2026-10-13): the brick breaker; its own secret PB_SSO_SECRET (also on the game), same shape as SpellWheel
const PB_SECRET = () => String(process.env.PB_SSO_SECRET || '').trim();
const PB_URL = () => String(process.env.PB_URL || 'https://polybreak.app').replace(/\/+$/, '');
const PB_ALT = () => String(process.env.PB_ALT_URLS || 'https://www.polybreak.app,https://polybreak.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
const pbSign = p => drB64u(crypto.createHmac('sha256', PB_SECRET()).update(p).digest());
function pbMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pbSign(payload); }
function pbOpen(token) {
if (PB_SECRET().length < 32) return { error: 'PolyBreak is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = pbSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That link has expired. Go back to PolyBreak and tap One more paddle again.' };
return { ok: true, claims: c };
}
const pbIsGameUrl = u => [PB_URL()].concat(PB_ALT()).some(o => String(u || '').startsWith(o + '/'));
async function pbCallback(cbUrl, receipt) {
if (!pbIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('polybreak callback', e.message); return false; }
}
// -- POL Miner (2026-10-28): the dig-down mining game; its own secret POLMINER_SSO_SECRET (also on the game), same shape as PolyBreak.
// Members see nothing until 'polminer' is in site config gamesLive (Games card, strip); the hand-off, in-game sign-in and supply
// crates work as soon as the secret is set, so testers can play behind the game's own staging gate.
const PM_SECRET = () => String(process.env.POLMINER_SSO_SECRET || '').trim();
const PM_URL = () => String(process.env.POLMINER_URL || 'https://polminer.com').replace(/\/+$/, '');
const PM_ALT = () => String(process.env.POLMINER_ALT_URLS || 'https://www.polminer.com,https://polminer.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
const pmSign = p => drB64u(crypto.createHmac('sha256', PM_SECRET()).update(p).digest());
function pmMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pmSign(payload); }
function pmOpen(token) {
if (PM_SECRET().length < 32) return { error: 'POL Miner is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = pmSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That link has expired. Go back to POL Miner and tap the supply crate again.' };
return { ok: true, claims: c };
}
const pmIsGameUrl = u => [PM_URL()].concat(PM_ALT()).some(o => String(u || '').startsWith(o + '/'));
async function pmCallback(cbUrl, receipt) {
if (!pmIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('polminer callback', e.message); return false; }
}
// -- Warp & Wares (2026-10-29): the Trade Wars-style 30-day season game; its own secret WW_SSO_SECRET (also on the game), the same
// protocol as POL Miner. Members see nothing until 'warpwares' is in site config gamesLive (Games card, strip, games page, promo
// tools, chatbot), and its season window is WW_SEASON (env WW_SEASON_START / WW_SEASON_END, Central days, end exclusive).
// A SPONSOR DOCK is its refuel: a verified visit at a sponsor market, visit kind 'dock' with its own daily cap (ads.js), paying
// the player bonus turns in the game, never POL.
const WW_SECRET = () => String(process.env.WW_SSO_SECRET || '').trim();
const WW_URL = () => String(process.env.WW_URL || 'https://warpwares.saasy.top').replace(/\/+$/, '');
const WW_ALT = () => String(process.env.WW_ALT_URLS || '').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
const WW_SEASON = { start: /^\d{4}-\d{2}-\d{2}$/.test(String(process.env.WW_SEASON_START || '')) ? process.env.WW_SEASON_START : '2026-11-30', end: /^\d{4}-\d{2}-\d{2}$/.test(String(process.env.WW_SEASON_END || '')) ? process.env.WW_SEASON_END : '2026-12-30' };
const wwSign = p => drB64u(crypto.createHmac('sha256', WW_SECRET()).update(p).digest());
function wwMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + wwSign(payload); }
function wwOpen(token) {
if (WW_SECRET().length < 32) return { error: 'Warp & Wares is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = wwSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That link has expired. Go back to Warp & Wares and dock again.' };
return { ok: true, claims: c };
}
const wwIsGameUrl = u => [WW_URL()].concat(WW_ALT()).some(o => String(u || '').startsWith(o + '/'));
async function wwCallback(cbUrl, receipt) {
if (!wwIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('warpwares callback', e.message); return false; }
}
// -- PolyWarriors (2026-10-05): the cyberpunk fighting game at polywarriors.com; its own secret PW_SSO_SECRET (also on the game)
const PW_SECRET = () => String(process.env.PW_SSO_SECRET || '').trim();
const PW_URL = () => String(process.env.PW_URL || 'https://polywarriors.com').replace(/\/+$/, '');
const PW_ALT = () => String(process.env.PW_ALT_URLS || 'https://www.polywarriors.com,https://polywarriors.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
const pwSign = p => drB64u(crypto.createHmac('sha256', PW_SECRET()).update(p).digest());
function pwMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pwSign(payload); }
async function swCallback(cbUrl, receipt) {
if (!swIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('spellwheel callback', e.message); return false; }
}
const PW_MINT_COOKIE_S = 4 * 3600; // the dashboard "back to the mint" bar lives this long (was 7 days: people who looked at the price and left saw it for a week, Marty 2026-10-11)
// -- PolyWarriors paid mints (2026-10-05): the first mint is free in the game; later mints cost PW_MINT_CREDITS (100) from
// PURCHASED credits only (package credits on a position; earned credits never count, Marty's rule). The game signs an order
// with PW_SSO_SECRET (kind 'pw-mint'), the member confirms here, ads.gamePurchase(purchasedOnly) charges, and a signed
// receipt goes back to the game twice (server callback + redirect), whichever lands first. The game mints on the receipt.
function pwOpen(token) {
if (PW_SECRET().length < 32) return { error: 'PolyWarriors is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = pwSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: 'That mint order has expired. Tap Mint in PolyWarriors again.' };
return { ok: true, claims: c };
}
const pwPasses = persistedMap('pwpasses'); // email -> { n, earned, used, log: [{ at, d, why }] }
const pwPassN = e => ((pwPasses.get(e) || {}).n || 0);
function pwPassAdd(e, d, why) { const c = pwPasses.get(e) || { n: 0, earned: 0, used: 0, log: [] }; const v = { n: Math.max(0, c.n + d), earned: c.earned + Math.max(0, d), used: c.used + Math.max(0, -d), ts: Date.now(), log: [{ at: Date.now(), d, why }].concat(c.log || []).slice(0, 50) }; pwPasses.set(e, v); return v.n; }
const pwPrizes = persistedMap('pwprizes'); // 'YYYY-MM-DD:place' -> { email, credits, at }
const pwOrders = persistedMap('pworders'); // order -> { status: 'waiting'|'paid', email, serial, ret, cb, ts, tx, cents, delivered }
const pwIsGameUrl = x => [PW_URL()].concat(PW_ALT()).some(o => String(x || '').startsWith(o + '/'));
async function pwCallback(cbUrl, receipt) {
if (!pwIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('polywarriors callback', e.message); return false; }
}
const pwReceipt = (order, o) => pwMint({ kind: 'pw-mint-receipt', order, email: o.email, serial: o.serial, paid: 5, usd: (o.cents || 500) / 100, ref: o.tx || null }, 3 * 86400000);
async function pwDeliver(order) { // the game mints on the receipt; retried each minute until the game says ok (up to a day)
const o = pwOrders.get(order); if (!o || o.status !== 'paid' || o.delivered) return;
const ok = await pwCallback(o.cb, pwReceipt(order, o));
const cur = pwOrders.get(order); if (!cur) return;
pwOrders.set(order, Object.assign({}, cur, ok ? { delivered: Date.now() } : { tries: (cur.tries || 0) + 1 }));
}
setInterval(() => { for (const [k, o] of pwOrders) { if (o.status === 'paid' && !o.delivered && (o.tries || 0) < 1440) pwDeliver(k).catch(() => {}); if (o.status === 'waiting' && Date.now() - o.ts > 7 * 86400000) pwOrders.delete(k); } }, 60000).unref();
async function pwMintOnEvent(ev) { // a package bought while a mint waits earns one mint pass per $5; waiting mints use them first
if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null;
const a = (!IS_PROD && ev.devEmail) ? { email: ev.devEmail } : await accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null; // devEmail: local tests only
const e = String(a.email).toLowerCase(), when = ev.ts || Date.now(), seen = pwPasses.get(e) || {};
if ((seen.log || []).some(x => x.why === 'buy:' + ev.tx)) return null; // each purchase counts once
const waiting = [...pwOrders.entries()].filter(([k, o]) => o.status === 'waiting' && o.email === e && o.ts <= when + 60000).sort((x, y) => y[1].ts - x[1].ts); // newest first: the warrior the member just tapped Mint on gets the first pass (an old forgotten order took Marty's on 10-06)
if (!waiting.length) return null; // passes come from packages bought for minting
const earned = Math.floor(ev.priceCents / 500); pwPassAdd(e, earned, 'buy:' + ev.tx);
const used = [];
for (const [k, o] of waiting) { if (pwPassN(e) < 1) break; pwPassAdd(e, -1, 'mint:' + k); pwOrders.set(k, Object.assign({}, o, { status: 'paid', tx: ev.tx, cents: ev.priceCents, paidAt: Date.now() })); used.push(k); }
console.log('polywarriors mint passes', e, '+' + earned, 'from tx', String(ev.tx).slice(0, 12), 'used', used.length, 'left', pwPassN(e));
for (const k of used) await pwDeliver(k);
return { earned, used, left: pwPassN(e) };
}
async function gkCallback(cbUrl, receipt) {
if (!String(cbUrl || '').startsWith(GK_URL() + '/')) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('gemkingdom callback', e.message); return false; }
}
// -- Spooky Doors (2026-10-02, the Halloween season game): sign-in hand-off, door visits and the costume shop. Same token
// shape as Drip Runner and Gem Kingdom under its own secret SD_SSO_SECRET (also set on the game, at least 32 characters).
// A door is a verified visit of its own kind ('door', own daily cap doorCapPerDay, never touching refuel or Earn counts).
// The game hears about it twice: a signed server-to-server callback AND a signed receipt on the redirect back, whichever
// lands first. Costumes are bought with ad credits through ads.gamePurchase, exactly like Gem Kingdom Crowns.
const SD_SECRET = () => String(process.env.SD_SSO_SECRET || '').trim();
const SD_URL = () => String(process.env.SD_URL || 'https://spookydoors.com').replace(/\/+$/, '');
const SD_SEASON = { start: '2026-10-04', end: '2026-11-01' }; // Central days, end exclusive (through Halloween night); start moved up from 10-17 (Marty, 2026-10-02)
const sdGoldenBonus = () => { const n = Number(ads.rates().goldenBonusCandy); return Number.isFinite(n) && n >= 0 ? Math.round(n) : 2; }; // extra candy on a Golden Door
const sdSign = p => drB64u(crypto.createHmac('sha256', SD_SECRET()).update(p).digest());
function sdMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + sdSign(payload); }
function sdOpen(token, expiredMsg) {
if (SD_SECRET().length < 32) return { error: 'Spooky Doors is not connected yet.' };
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
const want = sdSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
if (!c.exp || Date.now() > c.exp) return { error: expiredMsg || 'That link has expired. Go back to Spooky Doors and try again.' };
return { ok: true, claims: c };
}
// -- Road Agent (2026-10-07): the same door round trip under its own secret; a fuel stop is a door with game: 'roadagent'
const RA_SECRET = () => String(process.env.RA_SSO_SECRET || '').trim();
const RA_URL = () => String(process.env.RA_URL || 'https://roadagent.app').replace(/\/+$/, '');
const DOOR_GAMES = () => ({ spookydoors: { name: 'Spooky Doors', secret: SD_SECRET(), url: SD_URL(), hdr: 'SD', back: 'Go back to Spooky Doors and knock again.' },
roadagent: { name: 'Road Agent', secret: RA_SECRET(), url: RA_URL(), hdr: 'RA', back: 'Go back to Road Agent and fuel up again.' } });
const gSign = (g, p) => drB64u(crypto.createHmac('sha256', g.secret).update(p).digest());
function gMint(g, claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + gSign(g, payload); }
// open a door token from whichever game signed it: { ok, claims, game } or { error }
function doorOpen(token, expiredMsg) {
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
const G = DOOR_GAMES(); const key = G[c.game] ? c.game : 'spookydoors'; const g = G[key];
if (!g.secret || g.secret.length < 32) return { error: g.name + ' is not connected yet.' };
const want = gSign(g, payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
if (!c.exp || Date.now() > c.exp) return { error: expiredMsg || ('That link has expired. ' + g.back) };
return { ok: true, claims: c, game: key };
}
const gameUrlOk = (key, x) => String(x || '').startsWith(DOOR_GAMES()[key].url + '/');
async function gameCallback(key, body) { // door done -> the game's server, signed over ts + newline + raw body
const g = DOOR_GAMES()[key]; const raw = JSON.stringify(body); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', g.secret).update(ts + '\n' + raw).digest('hex');
const h = { 'Content-Type': 'application/json' }; h['X-' + g.hdr + '-Ts'] = ts; h['X-' + g.hdr + '-Sig'] = sig;
try { const r = await fetch(g.url + '/api/door/callback', { method: 'POST', headers: h, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; }
catch (e) { console.warn(key + ' callback', e.message); return false; }
}
const doorTokens = persistedMap('door'); // nonce -> { kind, email, memberId, id, title, target|videoUrl, host, ts, ret, challenge, done, doneRet }
const sdOrders = persistedMap('sdorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts }
const sdIsGameUrl = x => String(x || '').startsWith(SD_URL() + '/');
const sdJoin = (ret, q) => ret + (String(ret).includes('?') ? '&' : '?') + q; // ret is SD_URL/play?door=<nonce>, so this appends &...
async function sdCallback(body) { // door done: POST {nonce, memberId, campaignId, credits, host} (+ house, program on a house ad), X-SD-Sig = hex HMAC(secret, ts + "\n" + rawBody)
const raw = JSON.stringify(body); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', SD_SECRET()).update(ts + '\n' + raw).digest('hex');
try { const r = await fetch(SD_URL() + '/api/door/callback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SD-Ts': ts, 'X-SD-Sig': sig }, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; }
catch (e) { console.warn('spookydoors callback', e.message); return false; }
}
async function sdShopCallback(cbUrl, receipt) {
if (!sdIsGameUrl(cbUrl)) return false;
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('spookydoors shop callback', e.message); return false; }
}
// the visited campaign owner's public username ("+12 candy from @host"); null for house ads or members without one
async function sdHost(campaignId) {
try { const c = await ads.campaignById(campaignId); if (!c || !c.owner) return null; const a = await accounts.byEmail(String(c.owner).toLowerCase()); return (a && a.username) || null; } catch (e) { return null; }
}
// house ads (2026-10-02): when a door finds no visit pack and no video, one of Marty's own programs (rates.doorHouseAds)
// instead of "Nobody's home". Never the same one twice in a row for a member; otherwise the one least recently shown to
// them today. The player's own IAP username rides along where the program takes a share link (ref with {u}).
const doorHouse = persistedMap('doorhouse'); // email -> { ts, day, last, shown: { program: ts } }
function doorHouseList() {
const l = ads.rates().doorHouseAds;
return (Array.isArray(l) ? l : []).filter(x => x && String(x.name || '').trim() && /^https:\/\/[^\s"'<>]+$/i.test(String(x.url || ''))).slice(0, 20);
}
async function doorHousePick(email, claimedUsername, skipName) {
const list = doorHouseList().filter(x => !skipName || String(x.name).toLowerCase() !== String(skipName).toLowerCase()); if (!list.length) return null;
const day = todayCT(); const prev = doorHouse.get(email) || {}; const shown = prev.day === day ? Object.assign({}, prev.shown) : {};
const pool = list.length > 1 ? list.filter(x => x.name !== prev.last) : list;
const h = pool.slice().sort((a, b) => (shown[a.name] || 0) - (shown[b.name] || 0))[0]; // never shown today sorts first, list order breaks ties
shown[h.name] = Date.now(); doorHouse.set(email, { ts: Date.now(), day, last: h.name, shown });
let username = null; try { const a = await accounts.byEmail(email); username = (a && a.username) || null; } catch (e) {}
if (!username && claimedUsername) username = String(claimedUsername);
const withRef = username && /^[A-Za-z0-9_.-]{1,40}$/.test(username) && /^https:\/\/[^\s"'<>]*\{u\}/i.test(String(h.ref || ''));
return { name: String(h.name).trim().slice(0, 60), title: String(h.title || h.name).trim().slice(0, 120), target: withRef ? String(h.ref).replace('{u}', encodeURIComponent(username)) : String(h.url) };
}
function sdPage(res, code, title, inner) {
res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }));
res.end('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>' + gkEsc(title) + ' | InstantAdPay</title>'
+ '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Creepster&family=Fredoka:wght@400;600;700&display=swap">'
+ '<style>body{margin:0;background:#140B24 linear-gradient(rgba(20,11,36,.72),rgba(20,11,36,.92)),url(/assets/door-open.jpg?v=20261002) center/cover fixed;color:#F4F1FF;font:16px/1.5 Fredoka,"Trebuchet MS",system-ui,sans-serif;min-height:100vh;display:grid;place-items:center;padding:24px 16px;box-sizing:border-box}'
+ '.card{width:100%;max-width:440px;background:rgba(36,19,57,.95);border:1px solid #4A3270;border-radius:18px;box-shadow:0 16px 40px rgba(0,0,0,.55);padding:26px 22px;text-align:center;box-sizing:border-box}'
+ 'h1{font:400 40px/1.05 Creepster,Chiller,fantasy;color:#FF8A1F;text-shadow:0 3px 0 #5a1f00;margin:0 0 8px;letter-spacing:.02em}.sub{color:#5FE0D2;font-weight:600;font-size:13px;letter-spacing:.12em;text-transform:uppercase;margin:0 0 12px}.big{font:400 40px/1 Creepster,Chiller,fantasy;color:#FF5FA2;margin:8px 0 14px}'
+ '.row{display:flex;justify-content:space-between;gap:12px;padding:8px 0;border-bottom:1px solid rgba(185,169,214,.25);font-weight:600}.row span:first-child{color:#B9A9D6}'
+ '.btn{display:block;width:100%;box-sizing:border-box;margin-top:16px;padding:13px;border:0;border-radius:14px;background:#FF8A1F;color:#2a1200;font:700 17px Fredoka,system-ui,sans-serif;text-decoration:none;cursor:pointer;box-shadow:0 5px 0 #C25A06}'
+ '.btn.blue{background:transparent;color:#F4F1FF;box-shadow:inset 0 0 0 2px #4A3270}.alt{display:inline-block;margin-top:14px;color:#B9A9D6;font-weight:600}.warn{color:#FF5FA2;font-weight:700}.fine{font-size:13px;color:#B9A9D6;margin-top:14px}</style></head>'
+ '<body><main class="card">' + inner + '</main></body></html>');
}
// the generic season window (2026-10-02), shared by the Games card and the Promo tools card: 'live' while today (Central) is in
// [start, end), 'preview' before start for the admin only, 'hidden' otherwise (and for everyone from end on)
function seasonState(season, day, admin) {
if (!season) return 'live';
if (day >= season.end) return 'hidden';
if (day < season.start) return admin ? 'preview' : 'hidden';
return 'live';
}
// game testers: GAMES_TESTERS env = comma list of usernames or emails who may play coming-soon / not-yet-live games from the Games tab
const GAME_TESTERS = () => new Set(String(process.env.GAMES_TESTERS || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean));
const isGameTester = (acct, email) => { const T = GAME_TESTERS(); if (!T.size) return false; return T.has(String((acct && acct.username) || '').toLowerCase()) || T.has(String(email || '').toLowerCase()); };
// -- the games registry (2026-10-01). Add a game here; launch it by adding its slug to site config gamesLive.
function GAMES() {
return withPerks([
{ slug: 'spookydoors', name: 'Spooky Doors', tag: 'Halloween \u00b7 Oct 4 to 31', blurb: 'Trick or treat! Walk the street, knock on doors and fill your candy bucket. Every door is a short visit to a member\u2019s page or ad, and candy climbs a ladder with POL at set levels. Gone after Halloween night.',
art: SD_URL() + '/og-spookydoors.jpg', play: '/api/my/spookydoors', pays: 'POL at set candy levels', season: { start: SD_SEASON.start, end: SD_SEASON.end }, progress: sdProgress },
{ slug: 'roadagent', name: 'Road Agent', tag: 'Night highway shooter', blurb: 'Drive the night highway, shoot the hostiles that hunt you, spare the civilians. Fuel from a sponsor visit brings the weapons truck. Every sector you clear for the first time pays POL.',
art: RA_URL() + '/og-roadagent.jpg', play: '/api/my/roadagent', pays: 'POL for first sector clears and the daily patrol', progress: raProgress,
soon: { opens: '2026-10-15', label: 'Opens Thursday, Oct 15' } }, // Marty 2026-10-07: release Thu Oct 15; testers reach it by direct link meanwhile
{ slug: 'driprunner', name: 'Drip Runner', tag: 'Arcade runner', blurb: 'Hop the network, dodge the bots, clear chapters. Each first clear drips POL into your game balance, and a refuel on a member\u2019s page keeps your run alive.',
art: DR_URL() + '/og-driprunner.jpg?v=20261002', artPos: 'left', play: '/api/my/driprunner', pays: 'POL to your wallet at 0.10', progress: drProgress },
{ slug: 'gemkingdom', name: 'Gem Kingdom', tag: 'Fantasy match-3', blurb: 'Match gems to battle monsters with three heroes, earn stars and rebuild your village. Crowns for instant upgrades come from your ad credits.',
art: GK_URL() + '/fantasy/og-gemkingdom.jpg?v=20261002', play: '/api/my/gemkingdom', cta: 'Play', pays: 'POL for first clears; Crowns from ad credits' },
{ slug: 'polhunter', name: 'PolHunter', tag: 'Scavenger hunt', blurb: 'Hunt hidden codes on sites across the network. Every find drips POL straight to your wallet.',
art: 'https://polhunter.com/img/hero-800.webp', play: '/api/my/polhunter', pays: 'POL per find' },
{ slug: 'clutterhunt', name: 'ClutterHunt', tag: 'Hidden objects', blurb: 'Search cozy, cluttered rooms for hidden objects. New rooms every season, starting with the Haunted Manor.',
art: SEEK_URL() + '/og-clutterhunt.jpg?v=c2', play: '/api/my/clutterhunt', pays: 'POL for first clears and 3-star clears' },
// coming soon (2026-10-04, Marty: "build some anticipation... show that it's coming soon and put the date"): every member sees
// the card with its date and no Play button until `soon.opens` (Central); from then it is an ordinary card, live via gamesLive
{ slug: 'spellwheel', name: 'SpellWheel', tag: 'Word game', blurb: 'Swipe the letter wheel to fill the crossword, travel through six cozy places, and solve a new daily puzzle with everyone. Clear levels and chapters to earn POL.',
art: SW_URL() + '/og-spellwheel.jpg?v=1', play: '/api/my/spellwheel', pays: 'POL for levels, chapters and daily puzzles', soon: { opens: '2026-10-10', label: 'Opens Saturday, Oct 10' } },
// PolyWarriors (Marty 2026-10-05: "put Poly Warriors there as well, saying that it's coming next Monday")
{ slug: 'polywarriors', name: 'PolyWarriors', tag: 'Cyberpunk fighting', blurb: 'Turn-based fights with collectible low-poly warriors. Recruit fighters born with rare traits, climb the arena, challenge other members, and mint your warriors as NFTs.',
art: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/polywarriors-trailer.jpg', video: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/polywarriors-trailer.mp4', play: '/api/my/polywarriors', pays: 'POL for first wins over arena rivals', soon: { opens: '2026-10-12', label: 'Opens Monday, Oct 12' } }, // live 10-12: trailer poster + 16:9 trailer on the public games page
// PolyBreak (2026-10-13): the brick breaker; first round clears and the purple Polygon gem pay POL
{ slug: 'polybreak', name: 'PolyBreak', tag: 'Brick breaker', blurb: 'Break walls of glass jewel bricks with the classic arcade capsules, and catch the purple Polygon gem when it falls. First clears of each round pay POL.',
art: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polybreak/og-polybreak-clean.jpg', play: '/api/my/polybreak', pays: 'POL for first round clears and gem catches' },
// POL Miner (2026-10-28): dig down, beat the drill bosses, find the rare Polygon crystals (hidden until gamesLive has 'polminer')
{ slug: 'polminer', name: 'POL Miner', tag: 'Mining adventure', blurb: 'Dig down through the layers, haul ore to sell, upgrade your pick, lamp and cart, and beat a drill boss every 30 m. Rare pink Polygon crystals pay POL.',
art: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polminer/og-polminer-clean.jpg', play: '/api/my/polminer', pays: 'POL for Polygon crystals, first boss wins and depth records' },
// Warp & Wares (2026-10-29): the 30-day trading season (hidden until gamesLive has 'warpwares'; gone after the season)
{ slug: 'warpwares', name: 'Warp & Wares', tag: 'Season game, 30 days', blurb: 'A shared galaxy of 1,200 sectors for one season. 200 turns a day for everyone: trade three goods between markets, haggle, hold sectors with fighters, build a base, run a team of five. Weekly territory and trader prizes and the season leaderboard pay POL.',
art: WW_URL() + '/og-warpwares.jpg', play: '/api/my/warpwares', pays: 'POL for weekly territory and top traders, milestones and the season leaderboard', season: { start: WW_SEASON.start, end: WW_SEASON.end } },
]);
}
// each game's member perk (the $5 welcome offer, 2026-10-05) shown on its card
const withPerks = list => { const st = starter.cfg(); return list.map(g => starter.GAMES[g.slug] && st.on ? Object.assign({}, g, { perk: starter.GAMES[g.slug].perk }) : g); };
// -- cross-promo strip (2026-10-03): one short line per game and where a signed-out player lands (the game's own page)
const STRIP = () => ({
spookydoors: { line: 'Halloween only. Run the graveyard, knock on doors, climb the candy ladder to POL.', open: SD_URL() + '/play', host: SD_URL().replace(/^https?:\/\//, '') },
roadagent: { line: 'Night highway. Shoot the hostiles, clear sectors, get paid in POL.', open: RA_URL() + '/', host: RA_URL().replace(/^https?:\/\//, '') },
driprunner: { line: 'Hop, dodge the bots, clear chapters. Every first clear drips POL.', open: DR_URL() + '/play', host: DR_URL().replace(/^https?:\/\//, '') },
gemkingdom: { line: 'Match gems, beat the bosses, rebuild your kingdom. First clears pay POL.', open: GK_URL() + '/play', host: GK_URL().replace(/^https?:\/\//, '') },
polhunter: { line: 'Find hidden codes on sites across the network. Every find drips POL.', open: 'https://polhunter.com/', host: 'polhunter.com' },
clutterhunt: { line: 'Search cozy, cluttered rooms for hidden objects. New rooms every season.', open: SEEK_URL() + '/', host: SEEK_URL().replace(/^https?:\/\//, '') },
polybreak: { line: 'Break the glass jewel wall, catch the capsules and the purple Polygon gem. First clears pay POL.', open: PB_URL() + '/', host: PB_URL().replace(/^https?:\/\//, '') },
polminer: { line: 'Dig deep, beat the drill bosses, find the rare pink Polygon crystals. Crystals pay POL.', open: PM_URL() + '/', host: PM_URL().replace(/^https?:\/\//, '') },
warpwares: { line: 'One galaxy, 30 days, 200 turns a day. Trade, hold sectors, build a base. Weekly prizes pay POL.', open: WW_URL() + '/', host: WW_URL().replace(/^https?:\/\//, '') },
spellwheel: { line: 'Swipe the letter wheel, fill the grid, solve the daily puzzle. Levels and dailies pay POL.', open: SW_URL() + '/', host: SW_URL().replace(/^https?:\/\//, '') },
polywarriors: { line: 'Recruit one-of-a-kind warriors, fight the arena, challenge members. First wins pay POL.', open: PW_URL() + '/', host: PW_URL().replace(/^https?:\/\//, '') },
});
// live for the strip: in gamesLive, and a seasonal game until its season ends (Marty 2026-10-03: Spooky Doors may show before
// its formal announcement; "if someone manages to see it and play it, that's fine")
function stripGames() {
const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean));
const day = todayCT(), S = STRIP(); const lbl = d => { const t = new Date(d + 'T12:00:00Z'); t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); };
return GAMES().filter(g => live.has(g.slug) && S[g.slug] && !(g.season && day >= g.season.end))
.map(g => ({ slug: g.slug, name: g.name, tag: g.season ? 'Limited time \u00b7 ends ' + lbl(g.season.end) : g.tag, line: S[g.slug].line, art: g.art, artPos: g.artPos || 'center', seasonal: !!g.season }));
}
// -- PassiveDrip hand-off (2026-10-01): same token shape as Drip Runner, its own secret (PD_SSO_SECRET, also stored in
// PassiveDrip's site_config iap_sso_secret). PassiveDrip signs the member in or creates the account, carries the sponsor
// over by email, and OFFERS the wallet with one confirm tap; it never writes or overwrites a payout address silently.
const PD_SECRET = () => String(process.env.PD_SSO_SECRET || '').trim();
const PD_URL = () => String(process.env.PD_URL || 'https://passivedrip.com').replace(/\/+$/, '');
function pdMint(claims) { const payload = JSON.stringify(Object.assign({ aud: 'passivedrip', iat: Date.now(), exp: Date.now() + 5 * 60000, nonce: crypto.randomBytes(16).toString('hex') }, claims)); return drB64u(payload) + '.' + drB64u(crypto.createHmac('sha256', PD_SECRET()).update(payload).digest()); }
async function pdProgress(memberId, email) {
const j = await pdsync.member(memberId, email); if (!j) return null;
if (!j.exists) return { line: 'No PassiveDrip account yet. Open it and one is made for you.' };
const coins = Math.floor(Number(j.coins) || 0);
return { line: '@' + j.username + ' · ' + coins.toLocaleString('en-US') + ' of ' + Number(j.threshold || 2000).toLocaleString('en-US') + ' coins' + (j.hasWallet ? '' : ' · no payout wallet yet') + (j.paidPol ? ' · ' + Number(j.paidPol).toFixed(2) + ' POL paid out' : '') };
}
// the player's own line on the Drip Runner card, read from the game with a signed request
async function drProgress(memberId) {
if (DR_SECRET().length < 32) return null;
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', DR_SECRET()).update('player:' + memberId + ':' + ts).digest('hex');
const r = await fetch(DR_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) });
if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' };
return { line: 'Chapter ' + j.chapter + ' \u00b7 ' + Number(j.unpaid).toFixed(3) + ' POL in your game balance' + (j.paidTotal ? ' \u00b7 ' + Number(j.paidTotal).toFixed(3) + ' POL paid out' : '') };
}
// the player's own line on the Road Agent card (signed, like the others)
async function raProgress(memberId) {
if (RA_SECRET().length < 32) return null;
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', RA_SECRET()).update('player:' + memberId + ':' + ts).digest('hex');
const r = await fetch(RA_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) });
if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' };
return { line: (Number(j.bestDist || 0) / 1000).toFixed(2) + ' km best \u00b7 ' + Number(j.sectors || 0) + ' sector' + (Number(j.sectors) === 1 ? '' : 's') + (Number(j.polEarned) ? ' \u00b7 ' + Number(j.polEarned).toFixed(2) + ' POL earned' : '') };
}
// the player's own line on the Spooky Doors card, read from the game with a signed request (same scheme as Drip Runner)
async function sdProgress(memberId) {
if (SD_SECRET().length < 32) return null;
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SD_SECRET()).update('player:' + memberId + ':' + ts).digest('hex');
const r = await fetch(SD_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) });
if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' };
const cap = ads.rates().doorCapPerDay || 15;
return { line: Number(j.candy || 0).toLocaleString('en-US') + ' candy \u00b7 ' + Number(j.doorsToday || 0) + ' of ' + cap + ' doors today' + (Number(j.polEarned) ? ' \u00b7 ' + Number(j.polEarned).toFixed(2) + ' POL earned' : '') };
}
// -- in-game sign-in (Marty, 2026-10-03: "an integrated sign-on that never leaves the game"). The game's own /signin
// page calls these endpoints straight from the player's browser (CORS, no cookies), so the sign-up guard and the
// one-account-per-person checks see the player's real connection. Same email code, same guard and the same account
// as the dashboard; the answer is the game's hand-off token instead of a session cookie, plus a GAME PASS (signed
// here, kept by the game in localStorage, 30 days) that lets the game's "open InstantAdPay" nudges arrive signed in
// (POST /api/game/enter). The IAP device cookie cannot ride a cross-site request, so the game sends its own
// browser id (req.gameDev) for the device checks.
// frames: false = that game's page CSP (default-src 'self', no frame-src) refuses iframes, so its login ad opens in a new tab
const GAME_AUTH = {
driprunner: { name: 'Drip Runner', frames: false, origins: () => [DR_URL()], host: () => DR_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => drMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), wallet: a.address || null, username: a.username || null,
sponsorRef: a.sponsorRef || null, joinedRef: a.joinedRef || null, joinedAt: a.created || null }) },
seek: { name: 'ClutterHunt', origins: () => [SEEK_URL()].concat(SEEK_ALT()), host: () => SEEK_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => seekMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) },
polybreak: { name: 'PolyBreak', frames: false, origins: () => [PB_URL()].concat(PB_ALT()), host: () => PB_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => pbMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null, sponsorRef: a.sponsorRef || null }) },
polminer: { name: 'POL Miner', frames: false, origins: () => [PM_URL()].concat(PM_ALT()), host: () => PM_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => pmMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null, sponsorRef: a.sponsorRef || null }) },
warpwares: { name: 'Warp & Wares', frames: false, origins: () => [WW_URL()].concat(WW_ALT()), host: () => WW_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => wwMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null, sponsorRef: a.sponsorRef || null }) },
spellwheel: { name: 'SpellWheel', origins: () => [SW_URL()].concat(SW_ALT()), host: () => SW_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => swMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) },
polywarriors: { name: 'PolyWarriors', origins: () => [PW_URL()].concat(PW_ALT()), host: () => PW_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => pwMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) },
shardsofvalor: { name: 'Shards of Valor', frames: false, origins: () => [SOV_URL()].concat(SOV_ALT()), host: () => SOV_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => sovMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) },
gemkingdom: { name: 'Gem Kingdom', origins: () => [GK_URL(), 'https://gemkingdom.saasy.top'], host: () => GK_URL().replace(/^https?:\/\//, ''),
mint: (a, memberId) => gkMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) },
};
// a game's one-tap link carries the inviter's ?ref to /my, where the viral-link rule sets the sponsor (2026-10-05: only Gem Kingdom and
// Spooky Doors passed it before; signed-out visitors from the other games lost their sponsor)
const refQ = u => { const r = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); return r ? '?ref=' + encodeURIComponent(r) : ''; };
const devOrigin = o => !IS_PROD && /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(o);
// the sign-in login ad, shared by the dashboard (GET /api/ads/slot?type=login) and the games' sign-in kit
// (GET /api/game/ads/login). ads.serve counts the impression and marks lastShownDay, exactly as before; the
// member clicks "Open Ad" (a real, counted click through /api/ads/click) while the countdown runs. Every call
// is tallied per Central day and surface (loginshows.js) so the admin can compare dashboard and game sign-ins.
async function loginAdFor(req, surface) {
const ad = await ads.serve('login', viewerGeo(req));
let house = false;
if (ad) {
ad.dwell = ads.rates().loginDwellSeconds || 10;
// 2026-10-09: the gate frames the sponsor's page under our bar (timer + way out visible on the ad itself).
// Login campaigns were never frame-checked, so check here, once per campaign, and fall back to a new tab.
const site = await ads.targetOf(ad.id);
ad.siteUrl = site;
ad.frameable = await loginFrameable(ad.id, site, surface !== 'dashboard');
try { const c = await ads.campaignById(ad.id); house = !!(c && (c.house || c.owner === ads.HOUSE_OWNER)); } catch (e) {}
}
loginShows.record(surface, ad ? { house } : null).catch(() => {});
return ad;
}
function gameOf(req, slug) {
const g = Object.prototype.hasOwnProperty.call(GAME_AUTH, String(slug || '')) ? GAME_AUTH[slug] : null; if (!g) return null;
const o = String(req.headers.origin || '');
return g.origins().includes(o) || devOrigin(o) ? g : null;
}
function gameCors(req) {
const o = String(req.headers.origin || '');
const ok = Object.values(GAME_AUTH).some(g => g.origins().includes(o)) || devOrigin(o);
return ok ? { 'Access-Control-Allow-Origin': o, Vary: 'Origin', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'content-type', 'Access-Control-Max-Age': '600' } : { Vary: 'Origin' };
}
let gamePassKey = '';
function gamePassSecret() {
if (gamePassKey) return gamePassKey;
const f = path.join(DATA_DIR, 'game-pass.secret');
try { gamePassKey = fs.readFileSync(f, 'utf8').trim(); } catch (e) {}
if (gamePassKey.length < 32) { gamePassKey = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, gamePassKey, { mode: 0o600 }); } catch (e) { console.error('game pass secret', e.message); } }
return gamePassKey;
}
const gamePassSign = p => drB64u(crypto.createHmac('sha256', gamePassSecret()).update(p).digest());
function gamePassMint(email, game) { const p = JSON.stringify({ e: String(email).toLowerCase(), g: game, iat: Date.now(), exp: Date.now() + 30 * 86400000 }); return drB64u(p) + '.' + gamePassSign(p); }
function gamePassOpen(tok) {
const [p, sig] = String(tok || '').split('.'); if (!p || !sig) return null;
let payload; try { payload = Buffer.from(p.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return null; }
const want = gamePassSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return null;
let c; try { c = JSON.parse(payload); } catch (e) { return null; }
return c && c.e && c.exp > Date.now() ? c : null;
}
const gameDevOf = b => { const d = String((b && b.dev) || ''); return /^[a-f0-9]{32}$/.test(d) ? d : ''; };
async function gameAnswer(g, slug, acct) { // the game token (only once a username exists) + a fresh pass
let memberId = acct.memberId || 0;
if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} }
const needUsername = !acct.username;
return { ok: true, needUsername, username: acct.username || null, token: needUsername ? null : g.mint(acct, memberId), pass: gamePassMint(acct.email, slug) };
}
const SHARE_HOSTS = String(process.env.SHARE_HOSTS || 'ctbgo.com,mylinehq.com').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
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;
// share-link domains (ctbgo.com, mylinehq.com): /<ref> goes to that member's join page, anything else to the same path
// here. 302 (not 301) so links never get pinned in caches; the query (?v= angle, ?promo=) rides along.
{ const sh = String(req.headers.host || '').toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '');
if (SHARE_HOSTS.includes(sh)) {
const ref = /^\/([A-Za-z0-9_]{1,40})\/?$/.exec(p);
const to = 'https://instantadpay.com' + (p === '/' ? '/' : ref ? '/join/' + ref[1] : p) + (u.search || '');
res.writeHead(302, { Location: to, 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }); return res.end();
} }
// -- traffic log: public page views by referring domain (admin > Traffic)
if (req.method === 'GET' && ((TRAFFIC_PAGES.has(p) && !(p === '/refuel' && u.searchParams.has('t'))) || /^\/(join|from|wall|blog)\/[^/]+$/.test(p))) traffic.hit(p.startsWith('/blog/') ? '/blog/*' : p, req.headers.referer, req.headers['user-agent']);
// -- viral links (Marty, 2026-09-21): ANY public page + ?ref=<username|code|id> is that member's
// referral link. Same 30-day last-touch sponsor cookie as /join, the view counts under the
// "page" hook in link stats. Served IN PLACE, not redirected (2026-09-21): Facebook's crawler follows
// redirects and canonicalizes a share to og:url, so the redirect (and a clean og:url) dropped the member's
// name from every share. og:url now carries the ref; rel=canonical stays clean for search engines.
// /join, /from and the APIs keep their own meaning of ?ref.
if ((req.method === 'GET' || req.method === 'HEAD') && u.searchParams.has('ref') && !p.startsWith('/api/') && !p.startsWith('/admin') && !/^\/(join|from)\//.test(p) && !/\.[a-z0-9]{2,5}$/i.test(p)) {
const raw = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40);
const tok = JOIN_ALIASES[raw] || raw;
u.searchParams.delete('ref');
const clean = p + (u.searchParams.toString() ? '?' + u.searchParams.toString() : '');
let known = false;
if (/^[a-z0-9_]{1,20}$/.test(tok)) { try { known = !!((await accounts.byCode(tok)) || (await accounts.byUsername(tok)) || (/^\d+$/.test(tok) && (await accounts.byMemberId(Number(tok))))); } catch (e) {} }
const set = [];
if (known) {
req.viralTok = tok; // later routes (bare /join) can use the sponsor even before the cookie round-trips
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`;
set.push('iap.sponsor=' + tok + cookieTail); // last touch wins, exactly like /join
set.push('iap.angle=page' + cookieTail); // the join shows under the "any page" hook
if (!parseCookies(req)['iap.ref']) set.push('iap.ref=' + encodeURIComponent(coach.refHost(req.headers.referer)) + cookieTail); // first-touch source
if (req.method === 'GET') coach.recordView(tok, 'page', req.headers.referer);
}
if (known) {
const wh = res.writeHead.bind(res); let html = false;
res.writeHead = function (code, headers) {
headers = Object.assign({}, headers || {});
if (set.length) headers['Set-Cookie'] = [].concat(headers['Set-Cookie'] || [], set);
html = /text\/html/i.test(String(headers['Content-Type'] || '')); if (html) delete headers['Content-Length'];
return wh(code, headers);
};
const end = res.end.bind(res);
res.end = function (chunk, enc, cb) {
if (html && chunk) {
let s = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
s = s.replace(/(<meta property="og:url" content=")([^"]*)(")/, (m, a, url, c) => a + url + (url.includes('?') ? '&' : '?') + 'ref=' + encodeURIComponent(tok) + c);
return end(s, 'utf8', cb);
}
return end(chunk, enc, cb);
};
}
req.url = clean; // the routes below see the clean path; u already has the ref removed
}
// -- join links: /join/<memberId or share code> — LAST-touch cookie (Marty,
// 2026-09-10): the link a visitor opened most recently is the sponsor shown
// and used, and it locks the moment the account is created (accounts.ensure
// never changes an existing account's sponsor; the contract binds the buyer at
// their first purchase). Codes resolve LATE (at buy time) to whatever chain id
// the referrer has by then, so free members refer from day one.
// Bare /join (Diann 2026-10-11: the games page's "Join free" and the Friday/Wednesday pages linked to /join and got
// "Not found"): send the visitor to the sponsored join page. ?ref= has already been folded into the iap.sponsor cookie by
// the viral-link handler above, so the cookie decides; nobody known -> the company position, like the partner kit.
if ((p === '/join' || p === '/join/') && (req.method === 'GET' || req.method === 'HEAD')) {
const clean = s => String(s || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
const refQ = clean(u.searchParams.get('ref') || req.viralTok); const spon = (refQ && (JOIN_ALIASES[refQ] || refQ)) || clean(parseCookies(req)['iap.sponsor']); // ?ref= wins, then the cookie
u.searchParams.delete('ref'); const qs = u.searchParams.toString();
res.writeHead(302, baseHeaders({ Location: '/join/' + (spon || 'company') + (qs ? '?' + qs : ''), 'Cache-Control': 'no-store' })); return res.end();
}
let m = /^\/join\/([A-Za-z0-9_]{1,20})$/.exec(p);
if (m && (req.method === 'GET' || req.method === 'HEAD')) {
// lead-capture page: email first, wallet later. ?v=<angle> picks the hook
// copy and is remembered so the account records which angle converted.
// partner placement: instantadpay.com/join/company (or /top) places the visitor directly under
// member #1, the company position, with no sponsor in between (Marty, 2026-09-12 partner kit)
const tok = JOIN_ALIASES[m[1].toLowerCase()] || m[1].toLowerCase();
const cookies = parseCookies(req);
const angle = String(u.searchParams.get('v') || '').toLowerCase();
const ang = JOIN_ANGLES[angle] || null;
if (req.method === 'GET') coach.recordView(tok, ang ? angle : '', req.headers.referer); // link stats per angle + source
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit
const set = [];
set.push('iap.sponsor=' + tok + cookieTail); // last touch wins
if (u.searchParams.get('from') === 'polhunter') set.push('iap.return=polhunter' + cookieTail); // came through a PolHunter share link: send them back after the wallet step
if (u.searchParams.get('from') === 'driprunner') set.push('iap.return=driprunner; Path=/; SameSite=Lax; Max-Age=7200' + (IS_PROD ? '; Secure' : '')); // a Drip Runner share link: back into the game once they have a username
const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup
if (promo) { const pref = String(req.headers.referer || '').replace(/^https?:\/\//, '').split('/')[0].toLowerCase().slice(0, 80); if (pref) set.push('iap.promoref=' + encodeURIComponent(pref) + cookieTail); } // which partner page it came from
if (ang) set.push('iap.angle=' + angle + cookieTail);
// First-touch source. A PolHunter share link carries ?from=polhunter in the URL itself, which
// survives the referrer being stripped (in-app browsers, a link pasted into chat). PolHunter
// pays a referral bounty only for people it actually sent, so that proof has to be reliable
// rather than dependent on a header (Marty, 2026-09-24: "not just members that come on board
// IAP and work their way over to POL Hunter").
if (!cookies['iap.ref']) {
const host = u.searchParams.get('from') === 'polhunter' ? 'polhunter.com' : u.searchParams.get('from') === 'driprunner' ? 'driprunner.saasy.top' : coach.refHost(req.headers.referer);
set.push('iap.ref=' + encodeURIComponent(host) + cookieTail);
}
return serveJoinPage(res, tok, ang ? angle : '', ang, set);
}
// -- legacy bridge: /from/faucetwave | /from/tieroneads [?seg=advertiser]. Same squeeze page
// with brand copy, NO sponsor (the sponsor cookie is cleared so they land in the holding
// tank for adoption), the angle remembered so the welcome-back grant fires at signup, and
// a forced first-touch source so link stats / admin can see the legacy arrivals.
m = /^\/from\/(faucetwave|tieroneads|socialpix)$/.exec(p);
if (m && (req.method === 'GET' || req.method === 'HEAD')) {
const brand = m[1];
// SocialPix arrivals came to POST ads, so their default copy is the advertiser one (?seg=earn flips it);
// the closed EvolutionScript brands default to the earner copy (?seg=advertiser flips it).
const seg = String(u.searchParams.get('seg') || '').toLowerCase();
const prefix = { faucetwave: 'fw', tieroneads: 't1', socialpix: 'sp' }[brand];
const key = prefix + (brand === 'socialpix' ? (seg.startsWith('earn') ? '-earn' : '-adv') : (seg.startsWith('adv') ? '-adv' : '-earn'));
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`;
const src = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9.\-]/g, '').slice(0, 40); // e.g. the old domain's splash page
const set = ['iap.sponsor=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : ''), 'iap.angle=' + key + cookieTail, 'iap.ref=' + encodeURIComponent('legacy:' + brand + (src ? ':' + src : '')) + cookieTail];
return serveJoinPage(res, '', key, JOIN_ANGLES[key], set);
}
if (p === '/unsubscribe' && (req.method === 'GET' || req.method === 'POST')) { // POST = RFC 8058 one-click from the mail client
const r = await drip.unsubscribe(u.searchParams.get('e'), u.searchParams.get('t'));
const msg = r.error ? r.error : 'Done. You will not get any more emails from InstantAdPay, apart from sign-in codes you ask for and receipts for payments to or from your account. Your account is unchanged.';
res.writeHead(r.error ? 400 : 200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }));
return res.end('<!doctype html><html><head><meta charset="utf-8"><title>InstantAdPay</title><link rel="stylesheet" href="/assets/site.css?v=20260909a"></head><body><div class="wrap" style="max-width:560px;padding:80px 22px"><a href="/"><img src="/logo.png" alt="InstantAdPay" style="height:34px"></a><h1 style="font-size:30px;margin:26px 0 12px">' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '</h1><p>' + msg + '</p><p><a class="btn small sec" href="/my">Member area</a></p></div></body></html>');
}
// -- public API
if (p === '/api/friday' && req.method === 'GET') return json(res, 200, friday.view(), { 'Cache-Control': 'public, max-age=60' });
// member welcome offer from the games: public numbers for the game cards, the member's own view, and the 'came from' mark
if (p === '/api/starter/public' && req.method === 'GET') return json(res, 200, starter.publicView(), { 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' });
if (p === '/api/starter' && (req.method === 'GET' || req.method === 'POST')) {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (req.method === 'POST') { const b = await readBody(req); starter.setFrom(s.email, String(b.game || '')); }
const acct = await accounts.byEmail(s.email);
return json(res, 200, await starter.view(s.email, Number((acct && acct.memberId) || s.memberId || 0)));
}
if (p === '/api/wednesday' && req.method === 'GET') return json(res, 200, wednesday.view(), { 'Cache-Control': 'public, max-age=60' });
if (p === '/api/admin/pdsync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, pdsync.status()); }
if (p === '/api/admin/pdsync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await pdsync.sync()); }
if (p === '/api/admin/wednesday-previews' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, wednesday.previews()); }
if (p === '/api/admin/wednesday/kick' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const r = await wednesday.kickNow(); return json(res, r.error ? 400 : 200, r); }
// -- the pages a member can turn into a viral link (promo tools > Viral links)
if (p === '/api/pages' && req.method === 'GET') {
const pages = [{ path: '/', title: 'Home page' }, { path: '/blog', title: 'Blog' }, { path: '/earning', title: 'How earning works' }, { path: '/games', title: 'Games that pay POL' }, { path: '/ledger', title: 'Live ledger' }, { path: '/leaderboard', title: 'Leaderboard' }, { path: '/contract', title: 'The contract' }, { path: '/plays', title: 'Team-building plays' }, { path: '/wallets', title: 'Wallet guide' }, { path: '/friday', title: 'Five Dollar Friday' }, { path: '/refuel', title: 'Fuel Your Offers: the Monthly Refuel guide' }, { path: '/conversion-tracking', title: 'Conversion tracking: how to set it up' }, { path: '/whats-new', title: "What's new" }, { path: '/shorts', title: 'Shorts' }, { path: '/presentation', title: 'The presentation (narrated video)' }];
if (bixpay.live()) pages.push({ path: '/bixpay', title: 'BixPay: a Visa card for your POL' }); // the guide resolves the sharer's partner link from ?ref (2026-10-29)
try { for (const b of (await blog.listPublished()).slice(0, 40)) pages.push({ path: '/blog/' + b.slug, title: 'Article: ' + b.title, cover: b.cover || null }); } catch (e) {}
return json(res, 200, { pages });
}
if (p === '/api/config' && req.method === 'GET') {
const c = chain.getConfig();
// public copy of the site settings: never anything that looks like a credential
const pubSite = {};
for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k) && !/^support/.test(k)) pubSite[k] = v; // support* = help desk internals (Marty's chat id, saved replies)
return json(res, 200, Object.assign({ contract: c.contract, chainId: c.chainId,
chainName: c.chainName, explorer: c.explorer, rpc: c.rpcs[0],
emailAuth: mailer.hasKey() || !IS_PROD }, pubSite));
}
if (p === '/api/moonpay-url' && req.method === 'GET') {
// Card on-ramp deep link. With MoonPay keys set — PUBLIC key via
// MOONPAY_PUBLIC_KEY env or site config, SECRET key via MOONPAY_SECRET_KEY
// env ONLY (never site config, since /api/config exposes siteConfig) —
// returns a SIGNED checkout URL prefilled with the buyer's own wallet and
// a POL amount; otherwise a generic MoonPay buy page. Zero custody either
// way: MoonPay is merchant of record and the crypto goes straight to the
// buyer's wallet — this site never touches or holds anyone's money.
const addr = (u.searchParams.get('address') || '').trim();
let pol = Math.round(Number(u.searchParams.get('pol')) || 0);
if (!pol || pol < 30) pol = 30;
if (pol > 100000) pol = 100000;
const pk = (process.env.MOONPAY_PUBLIC_KEY || siteConfig().moonpayPublicKey || '').trim();
const sk = (process.env.MOONPAY_SECRET_KEY || '').trim();
if (pk && sk && /^0x[0-9a-fA-F]{40}$/.test(addr)) {
const qs = '?apiKey=' + encodeURIComponent(pk) + '&currencyCode=pol_polygon&walletAddress=' + encodeURIComponent(addr) + '&quoteCurrencyAmount=' + pol;
const sig = crypto.createHmac('sha256', sk).update(qs).digest('base64');
return json(res, 200, { url: 'https://buy.moonpay.com/' + qs + '&signature=' + encodeURIComponent(sig), signed: true, pol });
}
return json(res, 200, { url: 'https://www.moonpay.com/buy/matic', signed: false, pol }); // MoonPay's Polygon page still lives at the old slug; /buy/pol renders their 404 (same fix as RM Circle)
}
if (p === '/api/catalog' && req.method === 'GET') {
// five live quotes per call: serve a 20-second cache so pages that load the
// ladder (join, home, buy) are not waiting on the RPC every time
// stale-while-revalidate (2026-10-19): serve the cached ladder at once and refresh it in the background after
// 20 s, one refresh at a time; only wait for a fresh read when there is none or it is over 2 minutes old
const age = catalogCache.at ? Date.now() - catalogCache.at : Infinity;
if (age > 20000 && !catalogCache.busy) {
catalogCache.busy = chain.catalog().then(pr => { catalogCache.products = pr; catalogCache.at = Date.now(); })
.catch(e => console.error('catalog refresh', e.message)).finally(() => { catalogCache.busy = null; });
}
if (!catalogCache.products || age > 120000) {
try { await catalogCache.busy; } catch (e) {}
if (!catalogCache.products) throw new Error('catalog unavailable');
}
return json(res, 200, { products: catalogCache.products });
}
if (p === '/api/feed' && req.method === 'GET') {
return json(res, 200, { events: await attachNames(chain.recentEvents(Number(u.searchParams.get('n')) || 100)) });
}
if (p === '/api/feed/live' && req.method === 'GET') {
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' }));
res.write(': connected\n\n');
feedClients.add(res);
req.on('close', () => feedClients.delete(res));
return;
}
m = /^\/api\/tx\/(0x[0-9a-fA-F]{64})$/.exec(p);
if (m && req.method === 'GET') {
// tx relay so the browser never talks to the RPC directly (CSP stays 'self').
// Serves both the wallet's waitTx poll (found/status) and the built-in
// /tx/<hash> viewer (full details + decoded events).
try {
const r = await chain.rpc('eth_getTransactionReceipt', [m[1]]);
if (!r) return json(res, 200, { found: false });
const out = { found: true, status: r.status, blockNumber: r.blockNumber, gasUsed: r.gasUsed };
try {
const t = await chain.rpc('eth_getTransactionByHash', [m[1]]);
if (t) { out.from = t.from; out.to = t.to; out.valueWei = BigInt(t.value || '0x0').toString(); }
} catch (e) {}
try {
const blk = await chain.rpc('eth_getBlockByNumber', [r.blockNumber, false]);
if (blk) out.ts = blk.timestamp;
} catch (e) {}
try {
out.events = await attachNames((r.logs || []).map(chain.decodeLog).filter(Boolean)
.map(ev => Object.assign(ev, { tx: m[1] })));
} catch (e) { out.events = []; }
return json(res, 200, out);
} catch (e) { return json(res, 200, { found: false, rpcError: true }); }
}
if (p === '/api/sponsor' && req.method === 'GET') {
// The account's stored sponsor is authoritative — it persists across
// devices, cleared cookies, and return visits. Fall back to the first-touch
// cookie only for anonymous visitors with no account sponsor yet. (Reading
// the cookie alone was orphaning buyers to root when the cookie was absent.)
const s = await auth.fromRequest(req);
const acct = s && s.email ? await accounts.byEmail(s.email) : null;
const tok = (acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor'] || '';
const spd = await resolveSponsorDetailed(tok); let sponsorId = spd.id;
let sponsorBlocked = null; // set only for transient/unknown failures now: the client refuses the transaction
let sponsorRouted = null; // set when an unactivated sponsor was walked past: the client tells the buyer, then proceeds
if (acct && acct.sponsorRef && !sponsorId && spd.reason === 'notActivated') {
const w = await walkUpActivatedSponsor(tok);
if (w.reason === 'rpc') sponsorBlocked = 'rpc';
else {
const catchId = Number(siteConfig().defaultSponsorId) || 1;
sponsorId = w.id;
sponsorRouted = { from: spd.name || null, to: w.id ? w.name : 'the company (#' + catchId + ')', toId: w.id || catchId, skipped: w.skipped.map(x => x.name) };
if (u.searchParams.get('intent') === 'buy') sponsorRoutedAlert(acct.email, spd, sponsorRouted, w.skipped); // the dashboard's display-only pre-check never alerts (Marty, 2026-09-21)
}
} else if (acct && acct.sponsorRef && !sponsorId && spd.reason !== 'none') { sponsorBlocked = spd.reason; if (u.searchParams.get('intent') === 'buy') sponsorBlockedAlert(acct.email, Object.assign({ tok }, spd)); }
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; }
// holding tank (2026-10-27): a signed-in member with no sponsor and no member number is never bound under the
// fallback. Network sponsor first (LinkSpin), else the hold (the buy and activate buttons refuse on tankHold).
let tankHold = null;
if (!sponsorId && acct && !acct.sponsorRef && !acct.memberId) {
try {
const h = await tank.holdFor(acct);
if (h && h.aligned) { const a2 = await accounts.byEmail(acct.email); const sp2 = await resolveSponsorDetailed(a2 && a2.sponsorRef); if (sp2.id && !(await payoutChainBlocked(sp2.id, 2))) sponsorId = sp2.id; else tankHold = { since: null, until: null }; } // aligned: their sponsor's position (or held while it is not usable yet)
else if (h && h.hold) tankHold = h.hold;
} catch (e) { tankHold = { since: null, until: null }; }
if (tankHold) sponsorBlocked = 'tankHold';
// NEVER hold a purchase (Marty 2026-10-27): a buyer with no sponsor anywhere goes ahead under the catch position;
// the hold only stops a plain 'switch on payouts' with nothing bought. Alignment above still ran first.
if (tankHold && u.searchParams.get('intent') === 'buy') { tankHold = null; if (sponsorBlocked === 'tankHold') sponsorBlocked = null; }
}
// orphan fallback: an unresolvable/absent sponsor (dead link, no link) lands
// the new member under the configured catch position (#1) instead of root
if (!sponsorId && !tankHold && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1;
let name = null, avatarUrl = null, own = false;
// the join page names the owner of the LINK it was opened with (?ref=token), not the visitor's own
// sponsor: a member previewing their own invite page was seeing their upline's name (Jim, 2026-09-13)
let showTok = String(u.searchParams.get('ref') || '').trim().toLowerCase();
if (showTok && JOIN_ALIASES[showTok]) showTok = JOIN_ALIASES[showTok];
const nameTok = showTok || tok;
if (nameTok) {
const t = nameTok.toLowerCase();
let a = await accounts.byCode(t); if (!a) a = await accounts.byUsername(t);
if (!a && /^\d+$/.test(nameTok)) a = await accounts.byMemberId(Number(nameTok));
if (a) { name = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : null); avatarUrl = a.avatarUrl || null; own = !!(acct && a.email === acct.email); var bio = null, cobrand = false; try { cobrand = (await ads.milestonesOf(a.email)).includes('level3'); if (cobrand && await hasBought(a)) bio = a.bio ? String(a.bio).slice(0, 220) : null; } catch (e) {} }
}
// "You're joining the line of X" must only greet someone who is actually about to
// join. The last-touch sponsor cookie lives 30 days, so an EXISTING member who once
// clicked a teammate's link was being told on the sign-in page that logging in would
// place them under that person (Marty, 2026-09-17). Alarming, and untrue: their
// sponsor locked at their first purchase and nothing here can move it.
// Show it when they just arrived through a link (?ref= in the URL), or when the cookie
// is there AND this browser has never had an account. Attribution itself is untouched.
let invited = !!showTok;
if (!invited && tok) { try { invited = !(await fraud.hasAccountOnDevice(req)); } catch (e) { invited = true; } }
if (acct) invited = false; // already a member: they are not joining anybody's line
return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, tankHold, sponsorName: spd.name || null, invited, name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand });
}
if (p === '/api/stats' && req.method === 'GET') {
let members = 0; try { members = await chain.memberCount(); } catch (e) {}
return json(res, 200, Object.assign({ onchainMembers: members, siteAccounts: await accounts.count() }, chain.totals()));
}
// -- 24/7 assistant
if (p === '/api/chat' && req.method === 'POST') {
const ip = req.socket.remoteAddress || 'x';
if (chatLimited(ip)) return json(res, 429, { error: 'Give it a minute, then ask again.' });
const b = await readBody(req);
const r = await chatbot.answer(b.message, b.history);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/chat/kb-stamp' && req.method === 'GET') { // qa/chatbot-sync.mjs: the newest knowledge-base change (Central day) and the entry count
return json(res, 200, await kb.stamp(), { 'Cache-Control': 'no-store' });
}
// -- help desk, public side (2026-10-16, tickets.js): /support form, the private no-login ticket link, the chatbot hand-off
if (p === '/api/inbound/email' && req.method === 'POST') { // SendGrid Inbound Parse: secret key in the URL, always 200 once it matches
const k = inbound.key();
if (!k || u.searchParams.get('k') !== k) { req.resume(); return json(res, 403, { error: 'forbidden' }); }
const chunks = []; let n = 0, tooBig = false;
await new Promise(done => { req.on('data', c => { n += c.length; if (n > 12e6) tooBig = true; else chunks.push(c); }); req.on('end', done); req.on('error', done); });
if (tooBig) { console.log('inbound email: too big, dropped'); return json(res, 200, { ok: true }); }
try { console.log('inbound email:', await inbound.handle(Buffer.concat(chunks), req.headers['content-type'])); } catch (e) { console.error('inbound email', e.message); }
return json(res, 200, { ok: true });
}
if (p === '/api/telegram/support' && req.method === 'POST') { // the support bot's webhook: secret header checked inside, always 200
let b = {}; try { b = await readBody(req); } catch (e) {}
try { await supportbot.handle(req, b); } catch (e) { console.error('supportbot', e.message); }
return json(res, 200, { ok: true });
}
if (p === '/api/support' && req.method === 'POST') {
const b = await readBody(req);
const s = await auth.fromRequest(req);
const acct = s && s.email ? await accounts.byEmail(s.email) : null; // signed in: the ticket is theirs, whatever was typed
const email = acct ? acct.email : String(b.email || '').trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'That email address does not look right.' });
if (!acct) { const iss = await newEmailIssue(email); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); } // replies must reach them
if (!acct) { const mo = await memberOnlyTicket(email); if (mo) return json(res, mo.status, mo.body); }
const guard = supportGuard(req, b, email);
if (guard) return json(res, guard.status, guard.body);
const r = await tickets.create({ source: 'public', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, subject: b.subject, category: b.category, body: b.body });
if (r.error) return json(res, 400, r);
return json(res, 200, { ok: true, ref: r.ticket.ref, token: r.token, member: !!acct });
}
m = /^\/api\/support\/t\/([A-Za-z0-9_.-]{20,80})(\/reply)?$/.exec(p);
if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) {
const t = await tickets.byToken(m[1]);
if (!t) return json(res, 404, { error: 'This ticket link is not valid. Open the newest email about your ticket, or send a new one.' });
if (req.method === 'GET') return json(res, 200, await tickets.memberView(t));
const b = await readBody(req);
if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' });
const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, via: 'link' });
return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket));
}
if (p === '/api/support/chatbot' && req.method === 'POST') {
const b = await readBody(req);
const s = await auth.fromRequest(req);
const acct = s && s.email ? await accounts.byEmail(s.email) : null;
const email = acct ? acct.email : String(b.email || '').trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'Add your email so Marty can reply.', needEmail: true });
if (acct) { if (supportFlood('em:' + email, 5, 3600000)) return json(res, 429, { error: 'You have sent several tickets in the last hour. Open Help in your dashboard to add to one.' }); }
else { const mo = await memberOnlyTicket(email); if (mo) return json(res, mo.status, mo.body); const guard = supportGuard(req, b, email); if (guard) return json(res, guard.status, guard.body); }
const tr = Array.isArray(b.transcript) ? b.transcript : [];
const turns = tr.slice(-8).map(x => ((x && x.who === 'me') ? 'Me: ' : 'Assistant: ') + String((x && x.text) || '').replace(/\s+/g, ' ').trim().slice(0, 600)).filter(x => x.length > 6);
const firstQ = tr.find(x => x && x.who === 'me' && String(x.text || '').trim());
const note = String(b.note || '').trim().slice(0, 2000);
const body = (note ? note + '\n\n' : '') + (turns.length ? 'From the chat assistant:\n' + turns.join('\n') : '(sent from the chat assistant)');
const r = await tickets.create({ source: 'chatbot', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, category: 'Other',
subject: 'Chat: ' + (firstQ ? String(firstQ.text).replace(/\s+/g, ' ').trim().slice(0, 100) : 'question for support'), body });
if (r.error) return json(res, 400, r);
return json(res, 200, { ok: true, ref: r.ticket.ref, member: !!acct, link: acct ? '/my#help?t=' + r.ticket.ref : '/support/t/' + r.token });
}
// -- accounts: email + password is the normal join path (wallet comes
// out only at purchase / payout-activation time and gets linked then)
if (p === '/api/signup' && req.method === 'POST') {
const b = await readBody(req);
if (fraud.isBlocked(b.email)) return json(res, 403, { error: 'This address cannot open an account.' });
{ const iss = await newEmailIssue(String(b.email || '').trim().toLowerCase()); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); }
const pendS = pendingSponsor.get(String(b.email || '').trim().toLowerCase());
const ref = pageTok(b.ref) || parseCookies(req)['iap.sponsor'] || (pendS && pendS.ref) || ''; // last-touch attribution, locked at account creation
const r = await accounts.signup(b.email, b.password, ref);
if (r.error) return json(res, 400, r);
pendingSponsor.del(String(b.email || '').trim().toLowerCase());
// sponsor is notified once the new member picks a username (onboarding),
// so the email can name them — see /api/my/profile
if (b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent
const token = await auth.mintSession({ email: r.account.email });
return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) });
}
if (p === '/api/login' && req.method === 'POST') {
const b = await readBody(req);
const r = await accounts.login(b.email, b.password);
if (r.error) return json(res, 400, r);
let memberId = 0;
if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (e) {} }
const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId });
return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) });
}
// -- passwordless: email code sign-in (signup and login are the same act)
if (p === '/api/auth/email/start' && req.method === 'POST') {
const b = await readBody(req);
const e = String(b.email || '').trim().toLowerCase();
const devHdr = fraud.deviceOf(req) ? undefined : { 'Set-Cookie': fraud.deviceCookie(fraud.newDeviceId(), IS_PROD) }; // browser id for one-account-per-person checks
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' });
if (fraud.isBlocked(e)) return json(res, 403, { error: 'This address cannot open an account.' });
{ const iss = await newEmailIssue(e); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); }
const prev = emailCodes.get(e);
if (prev && Date.now() < prev.nextAt) { console.log('signup-guard cooldown', clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }, devHdr); }
const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited
if (guard) return json(res, guard.status, guard.body, devHdr);
const code = String(Math.floor(100000 + Math.random() * 900000));
emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 });
{ const ck = parseCookies(req); const bound = pageTok(b.ref) || ck['iap.sponsor'] || '';
if (bound && !(await accounts.byEmail(e))) pendingSponsor.set(e, { ref: bound, via: pageTok(b.ref) ? (String(b.angle || '').toLowerCase().slice(0, 20) || ck['iap.angle'] || 'page') : (ck['iap.angle'] || ''), joinedRef: decodeURIComponent(ck['iap.ref'] || '') || null }); }
if (mailer.hasKey()) {
try { await mailer.sendCode(e, code); } catch (err) {
console.error('sendCode failed', err.message);
return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }, devHdr);
}
return json(res, 200, { ok: true, sent: true }, devHdr);
}
if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }, devHdr);
return json(res, 503, { error: 'Email sign-in is not configured yet.' });
}
if (p === '/api/auth/email/verify' && req.method === 'POST') {
const b = await readBody(req);
const e = String(b.email || '').trim().toLowerCase();
const rec = emailCodes.get(e);
if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' });
rec.tries += 1;
if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); }
if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' });
emailCodes.delete(e);
const pend = pendingSponsor.get(e);
const ref = pageTok(b.ref) || parseCookies(req)['iap.sponsor'] || (pend && pend.ref) || '';
const via = parseCookies(req)['iap.angle'] || (pend && pend.via) || '';
const joinedRef = decodeURIComponent(parseCookies(req)['iap.ref'] || '') || (pend && pend.joinedRef) || null;
if (ref && !parseCookies(req)['iap.sponsor']) console.log('sponsor recovered without cookie', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'ref', ref, pageTok(b.ref) ? '(page token)' : '(remembered from the code request)');
if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' });
let fraudFlags = [];
const existing = await accounts.byEmail(e);
const claim = accounts.isUnclaimedShell(existing); // a waiting LinkSpin account: this sign-in is its owner's real sign-up
if (!existing || claim) { // anti-fraud checks apply to NEW accounts only (Marty, 2026-09-16: one account per person)
let spAcct = null; if (claim) { try { spAcct = await accounts.sponsorOf(e); } catch (err) {} } else if (ref) { try { spAcct = await accounts.byCode(String(ref).toLowerCase()); if (!spAcct) spAcct = await accounts.byUsername(String(ref).toLowerCase()); } catch (err) {} }
const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e);
fraudFlags = fc.flags;
// an approved exception is worth a log line: it is the difference between "the guard
// is broken" and "Marty said yes to this person"
if (fc.allowlisted) console.log('signup allowed by exception list', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'via', fc.allowedBy);
if (fc.block) { console.log('signup blocked', fc.flags.join(','), clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); fraudAlert(e, fc, spAcct, true); return json(res, 403, { error: fc.block }); }
}
const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged
if (r.error) return json(res, 400, r);
if (r.created) pendingSponsor.del(e);
if (claim) await claimShell(e, existing, ref);
if (r.created || claim) { fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); }
else fraud.recordSeen(e, req).catch(() => {});
// the lead is in the door: queue the getting-started sequence (opt-in box is pre-checked on both forms)
if (r.created && (b.followups || b.newsletter)) drip.enqueue(e, ref, via).catch(() => {});
// a wallet-only session (signed with a wallet, no account) finishing setup:
// adopt that wallet into the email account so member #, purchases and
// payouts stay attached, then retire the wallet-only session
const prior = await auth.fromRequest(req);
if (prior && prior.address && !prior.email) {
const lr = await accounts.linkWallet(e, prior.address);
if (lr.error) return json(res, 400, lr);
r.account = lr.account || await accounts.byEmail(e);
await auth.logout(req);
}
if (r.created) { sendWelcome(e, ref).catch(() => {}); } // sponsor notified at username set (/api/my/profile)
// partner promo code carried on the join link: redeem once per account (ignored if invalid/used)
try {
const pc = parseCookies(req)['iap.promo'];
if (pc) {
const pref = parseCookies(req)['iap.promoref'] ? decodeURIComponent(parseCookies(req)['iap.promoref']) : '';
const g = await promos.redeem(pc, e, 'link', pref);
if (g.ok) { const paid = await payPromo(e, todayCT()); console.log('promo redeemed', g.code, 'day 1:', paid.map(x => x.amount).join('+') || 0, 'of', g.credits, e, pref ? 'from ' + pref : ''); }
}
} catch (err) { console.error('promo redeem', err.message); }
// legacy bridge: a listed former Faucet Wave / Tier One Ads member gets welcome-back credits once
if (r.created && /^(fw|t1)-(adv|earn)$/.test(via)) {
try { const g = legacy.grant(e, siteConfig()); if (g) { await ads.addEarned(e, g.credits, { log: { kind: 'grant', note: 'Welcome-back credits (' + g.brand + ')' } }); console.log('legacy grant', g.brand, g.seg, g.credits, e); } }
catch (err) { console.error('legacy grant', err.message); }
}
if (r.created && b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent, new joins only
let memberId = 0;
if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} }
const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId });
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ clutterhunt: '/api/my/clutterhunt', spellwheel: '/api/my/spellwheel', polybreak: '/api/my/polybreak', polminer: '/api/my/polminer', warpwares: '/api/my/warpwares', polywarriors: '/api/my/polywarriors', driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
}
// -- in-game sign-in (2026-10-03): see GAME_AUTH. Mirrors /api/auth/email/start + verify, minus cookies.
if (p.startsWith('/api/game/auth/') && req.method === 'OPTIONS') { res.writeHead(204, gameCors(req)); return res.end(); }
// the login ad inside a game's sign-in kit, after a fresh sign-in (2026-10-18). CORS only for the GAME_AUTH
// origins of the named game (dev mode: localhost); the dashboard route stays same-origin.
if (p === '/api/game/ads/login' && (req.method === 'GET' || req.method === 'OPTIONS')) {
const g = gameOf(req, u.searchParams.get('game'));
const cors = g ? Object.assign(gameCors(req), { 'Access-Control-Allow-Methods': 'GET, OPTIONS' }) : { Vary: 'Origin' };
if (req.method === 'OPTIONS') { res.writeHead(204, cors); return res.end(); }
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
const ad = await loginAdFor(req, String(u.searchParams.get('game')));
if (ad && g.frames === false) ad.frameable = false;
return json(res, 200, { ad }, cors);
}
if (p === '/api/game/auth/start' && req.method === 'POST') {
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
req.gameDev = gameDevOf(b);
const e = String(b.email || '').trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' }, cors);
if (fraud.isBlocked(e)) return json(res, 403, { error: 'This address cannot open an account.' }, cors);
{ const iss = await newEmailIssue(e); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }, cors); }
const prev = emailCodes.get(e);
if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }, cors);
const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited
if (guard) return json(res, guard.status, guard.body, cors);
const code = String(Math.floor(100000 + Math.random() * 900000));
emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 });
const ref = pageTok(b.ref);
const srcTag = String(b.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30); // paid-traffic source the game saw (2026-10-03)
if (!(await accounts.byEmail(e))) pendingSponsor.set(e, { ref: ref || '', via: String(b.game), joinedRef: g.host() + (srcTag ? '/' + srcTag : '') });
console.log('game-signin code', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'ref ' + ref : '');
if (mailer.hasKey()) {
try { await mailer.sendCode(e, code); } catch (err) { console.error('sendCode failed', err.message); return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }, cors); }
return json(res, 200, { ok: true, sent: true }, cors);
}
if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }, cors);
return json(res, 503, { error: 'Email sign-in is not configured yet.' }, cors);
}
if (p === '/api/game/auth/verify' && req.method === 'POST') {
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
req.gameDev = gameDevOf(b);
const e = String(b.email || '').trim().toLowerCase();
const rec = emailCodes.get(e);
if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }, cors);
rec.tries += 1;
if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }, cors); }
if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }, cors);
emailCodes.delete(e);
if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }, cors);
const pend = pendingSponsor.get(e);
const ref = pageTok(b.ref) || (pend && pend.ref) || '';
const via = String(b.game); const srcTag = String(b.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30);
const joinedRef = (pend && pend.joinedRef) || (g.host() + (srcTag ? '/' + srcTag : '')); // e.g. driprunner.app/adsterra
let fraudFlags = [];
const existing = await accounts.byEmail(e);
const claim = accounts.isUnclaimedShell(existing); // a waiting LinkSpin account: this sign-in is its owner's real sign-up
if (!existing || claim) { // one account per person, exactly as on the dashboard
let spAcct = null; if (claim) { try { spAcct = await accounts.sponsorOf(e); } catch (err) {} } else if (ref) { try { spAcct = await accounts.byCode(ref); if (!spAcct) spAcct = await accounts.byUsername(ref); } catch (err) {} }
const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e);
fraudFlags = fc.flags;
if (fc.allowlisted) console.log('signup allowed by exception list', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'via', fc.allowedBy);
if (fc.block) { console.log('signup blocked (game)', b.game, fc.flags.join(','), clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); fraudAlert(e, fc, spAcct, true); return json(res, 403, { error: fc.block }, cors); }
}
const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged
if (r.error) return json(res, 400, r, cors);
if (claim) { await claimShell(e, existing, ref); fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); }
if (r.created) {
pendingSponsor.del(e);
fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false);
if (b.newsletter) { drip.enqueue(e, ref, via).catch(() => {}); sendy.subscribe(e, '').catch(() => {}); }
sendWelcome(e, ref).catch(() => {});
console.log('game-signin new account', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'sponsor ' + ref : 'no sponsor');
} else fraud.recordSeen(e, req).catch(() => {});
const acct = r.account || await accounts.byEmail(e);
return json(res, 200, Object.assign(await gameAnswer(g, b.game, acct), { created: !!r.created }), cors);
}
if (p === '/api/game/auth/username' && req.method === 'POST') {
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
const pass = gamePassOpen(b.pass); if (!pass) return json(res, 401, { error: 'Your sign-in expired. Start again with your email.' }, cors);
const before = await accounts.byEmail(pass.e); if (!before) return json(res, 404, { error: 'Account not found.' }, cors);
if (!before.username) {
const r = await accounts.setUsername(pass.e, b.username);
if (r.error) return json(res, 400, r, cors);
const acct = await accounts.byEmail(pass.e); // first username: the sponsor hears now, as from the dashboard
notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {});
if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() });
}
return json(res, 200, await gameAnswer(g, b.game, await accounts.byEmail(pass.e)), cors);
}
// remembered sign-in (2026-10-19): the kit's 29-day pass for this game becomes a fresh hand-off token, no code
if (p === '/api/game/auth/resume' && req.method === 'POST') {
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
const pass = gamePassOpen(b.pass);
if (!pass || (pass.g && pass.g !== b.game)) return json(res, 401, { error: 'Your sign-in expired. Start again with your email.' }, cors);
if (fraud.isSuspended(pass.e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }, cors);
const acct = await accounts.byEmail(pass.e); if (!acct) return json(res, 404, { error: 'Account not found. Start again with your email.' }, cors);
return json(res, 200, await gameAnswer(g, b.game, acct), cors);
}
// the game's nudges ("Add your wallet", "Level up") post the pass here in a new tab: signed in on arrival
if (p === '/api/game/enter' && req.method === 'POST') {
let f; try { f = new URLSearchParams((await readRaw(req, 4096)).toString('utf8')); } catch (e) { f = new URLSearchParams(); }
const pass = gamePassOpen(f.get('p'));
const to = ['overview', 'wallet', 'buy', 'earn', 'promo', 'games', 'profile', 'campaigns'].includes(f.get('to')) ? f.get('to') : 'overview';
if (!pass || fraud.isSuspended(pass.e)) { res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store' }); return res.end(); }
const acct = await accounts.byEmail(pass.e); if (!acct) { res.writeHead(303, { Location: '/my', 'Cache-Control': 'no-store' }); return res.end(); }
let memberId = acct.memberId || 0;
if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} }
const token = await auth.mintSession({ email: acct.email, address: acct.address, memberId });
res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store', 'Set-Cookie': auth.sessionCookie(token) }); return res.end();
}
// -- wallet auth: link-to-account when an email session exists, or
// wallet-first sign-in (no UI door since 2026-09-09; a wallet-only session
// is walked to the email card, which adopts the wallet on verify)
if (p === '/api/auth/challenge' && req.method === 'POST') {
const b = await readBody(req);
const r = auth.makeChallenge(b.address);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/auth/verify' && req.method === 'POST') {
const b = await readBody(req);
const r = await auth.verifyChallenge(b.address, b.signature);
if (r.error) return json(res, 400, r);
let memberId = 0;
try { memberId = await chain.memberIdByAccount(r.address); } catch (e) {}
const s = await auth.fromRequest(req);
if (s && s.email && b.asPosition) {
// Qualified Start: a second (third…) wallet on the same account. It becomes
// its own on-chain member under this member's id when it buys; the session
// stays on the main wallet.
// policy (Marty, 2026-09-10): positions exist to qualify, so at most five per account, and a
// wallet that is already registered on-chain under anything other than this account's main
// member is refused (a position-under-position chain would recapture 70% of a self-buy)
const MAX_POS = 5;
const have = await accounts.positions(s.email);
if (!have.find(p => p.address === r.address.toLowerCase()) && have.length >= MAX_POS)
return json(res, 400, { error: 'You can link up to ' + MAX_POS + ' positions, which is everything Qualified Start needs. Once qualified, buy from your main wallet so your sponsor is paid in full.' });
if (memberId) {
const mainId = await auth.refreshMemberId(s);
let mm = null; try { mm = await chain.member(memberId); } catch (e) {}
if (mm && mainId && mm.sponsorId !== mainId)
return json(res, 400, { error: 'That wallet is already registered on-chain under ' + (mm.sponsorId ? 'member #' + mm.sponsorId : 'no sponsor') + ', not under your main member #' + mainId + '. Only positions registered directly under you can be linked.' });
}
const pr = await accounts.addPosition(s.email, r.address);
if (pr.error) return json(res, 400, pr);
if (memberId) await accounts.setPositionMember(r.address, memberId);
return json(res, 200, { ok: true, position: true, address: r.address, memberId });
}
if (s && s.email) {
const lr = await accounts.linkWallet(s.email, r.address);
if (lr.error) return json(res, 400, lr);
await auth.updateSession(s.token, { address: r.address, memberId });
return json(res, 200, { ok: true, linked: true, address: r.address, memberId, next: parseCookies(req)['iap.return'] === 'polhunter' ? '/api/my/polhunter' : null });
}
const acct = await accounts.byAddress(r.address);
if (!acct && await accounts.positionOwner(r.address))
return json(res, 400, { error: 'That wallet is a linked position on an account. Sign in with that account\'s email instead.' });
const token = await auth.mintSession({ email: acct ? acct.email : null, address: r.address, memberId });
return json(res, 200, { ok: true, address: r.address, memberId },
{ 'Set-Cookie': auth.sessionCookie(token) });
}
if (p === '/api/auth/logout' && req.method === 'POST') {
await auth.logout(req);
return json(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie() });
}
if (p === '/api/gas' && req.method === 'GET') {
try { return json(res, 200, await chain.suggestedFees()); }
catch (e) { return json(res, 200, {}); }
}
if (p === '/api/me' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s) return json(res, 200, { signedIn: false });
const memberId = await auth.refreshMemberId(s);
let acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
// holding tank (2026-10-27): someone the network already knows is placed under that sponsor first (tank.js alignToNetwork)
if (acct && !acct.sponsorRef && !acct.memberId && !memberId) { try { if (await tank.alignToNetwork(acct)) acct = (await accounts.byEmail(acct.email)) || acct; } catch (e) {} }
const spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id;
let sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason !== 'none') ? spdMe.reason : null;
let sponsorRouted = null;
if (sponsorBlocked === 'notActivated') { // never hold a buyer for an unactivated sponsor: walk up the line
const w = await walkUpActivatedSponsor(acct.sponsorRef);
if (w.reason === 'rpc') sponsorBlocked = 'rpc';
else { sponsorBlocked = null; sponsorId = w.id; sponsorRouted = { from: spdMe.name || null, to: w.id ? w.name : 'the company', toId: w.id || (Number(siteConfig().defaultSponsorId) || 1) }; }
}
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0;
const _defSpon = Number(siteConfig().defaultSponsorId) || 1;
// a holding-tank member is never bound under the fallback: held for an adopter (24 h at most, then the rotation)
let tankHold = null, sponsorFallback = false; // sponsorFallback: no real sponsor resolved (the one-tap ?activate=1 flow never auto-starts then)
if (!sponsorId && !memberId && acct && !acct.sponsorRef && !acct.memberId) { try { const h = await tank.holdFor(acct); if (h && h.hold) tankHold = h.hold; } catch (e) { tankHold = { since: null, until: null }; } }
if (tankHold) sponsorBlocked = 'tankHold';
else if (!sponsorId && memberId !== _defSpon) { sponsorId = _defSpon; sponsorFallback = true; } // orphan fallback → #1 (never self-sponsor)
if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {});
const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'polminer', 'warpwares', 'shardsofvalor'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : null, sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
address: s.address || (acct && acct.address) || null, memberId,
username: (acct && acct.username) || null,
refCode: (acct && acct.code) || null, sponsorId, tankHold, sponsorFallback,
// profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned)
avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null,
socials: (acct && acct.socials) || null,
wallOffers: parseWallOffers(acct),
lineBannerUrl: (acct && acct.lineBannerUrl) || null, lineTargetUrl: (acct && acct.lineTargetUrl) || null };
// BixPay (2026-10-29): the member's own partner link plus the one their pages resolve to (own > sponsor chain > network)
if (bixpay.live()) { try { const r = await bixpay.resolve(acct); const tok = (acct && (acct.username || acct.code)) || ''; out.bix = { live: true, own: (acct && acct.bixPartnerLink) || null, link: r.link, whose: r.whose, name: r.name, using: bixpay.usingLine(r), go: { wallet: bixpay.goLink('wallet'), overview: bixpay.goLink('overview'), promo: bixpay.goLink('promo', tok) }, announce: bixpay.announcing(), clicks: bixpay.memberClicks(acct && acct.email) }; } catch (e) { out.bix = { live: true, error: true }; } }
else out.bix = { live: false };
if (memberId) {
try {
const mm = await chain.member(memberId);
out.buyerCount = mm.buyerCount;
out.onchainSponsorId = mm.sponsorId;
const bal = await ads.balances((await myMemberIds(s)).ids, s.email);
out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.earnedReserved = bal.earnedReserved; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available;
} catch (e) { out.chainReadError = true; }
}
return json(res, 200, out);
}
if (p === '/api/my/dashboard' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s) return json(res, 401, { error: 'Sign in first.' });
const memberId = await auth.refreshMemberId(s);
const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {});
let tankWaiting = null; // top of every Overview: people waiting for a sponsor (Marty, 2026-09-12)
try {
if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() };
const tw = tankWaitCache.list;
tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok, ready: tw.filter(w => w.ready).length };
} catch (e) {}
const sc0 = siteConfig();
const out = { memberId, tankWaiting, email: s.email || (acct && acct.email) || null,
pipeline: { live: pipeline.visible(sc0.pipelineMode, s.email || (acct && acct.email), ADMIN_EMAIL), mode: sc0.pipelineMode || 'off', eta: sc0.pipelineEta || '' },
address: s.address || (acct && acct.address) || null,
username: (acct && acct.username) || null,
refCode: (acct && acct.code) || null, lineBannerUrl: (acct && acct.lineBannerUrl) || null, /* the launch checklist mark reads it (was 7 of 8 with a banner set, 2026-09-14) */ credits: 0, buyerCount: 0,
earnedWei: '0', earnCount: 0, referrals: [], welcomeCredits: 0 };
if (out.email) {
// welcome credits unlock via the welcome tour when an upline with a
// line banner exists; members with no tour to walk get them instantly
const welcomed = await ads.welcomeGranted(out.email);
const tour = welcomed ? [] : (await uplineSlides(out.email)).filter(a => a.lineTargetUrl);
if (welcomed || !tour.length) { await ads.grantWelcome(out.email); out.welcomeCredits = ads.rates().welcomeCredits || 0; } // the welcome amount itself; the rest of the earned pool is viewing rewards, milestones and credits we add
else { out.welcomeCredits = 0; out.gauntletPending = true; }
}
if (out.email) out.inboxUnread = await ads.unreadCount(out.email); // delivers pending solos too
if (out.email) { // sponsor chat: presence heartbeat + unread + my availability + direct sponsor
accounts.touchSeen(out.email).catch(() => {});
out.chatUnread = await messages.chatUnread(out.email);
out.chatAvailable = (acct && acct.chatAvailable !== false);
const spon = await accounts.sponsorOf(out.email);
if (spon && spon.email) out.sponsor = {
email: spon.email,
name: spon.username ? '@' + spon.username : (spon.memberId ? 'member #' + spon.memberId : 'your sponsor'),
online: (Date.now() - (spon.lastSeen || 0)) < 60000,
available: spon.chatAvailable !== false };
}
if (out.email) { // the one modal that interrupts: a human broadcast, or a money-at-stake alert
const un = await messages.newestUnread(out.email);
if (un) {
const nm = un.fromMember ? await accounts.namesForMembers([un.fromMember]) : {};
out.sponsorMsg = { id: un.id, subject: un.subject, body: un.body, kind: un.kind || 'broadcast',
fromName: (un.fromMember && nm[un.fromMember]) ? '@' + nm[un.fromMember] : (un.fromMember ? 'member #' + un.fromMember : 'your sponsor') };
}
}
if (memberId) {
try {
const mm = await chain.member(memberId);
out.buyerCount = mm.buyerCount;
const mine = await myMemberIds(s);
// linked positions are the member's own: their qualifying buyers count toward the account (Jim, 2026-09-14)
out.buyerCountMain = mm.buyerCount; out.buyerCountPositions = 0;
for (const id of mine.ids) if (id && id !== memberId) { try { out.buyerCountPositions += (await chain.member(id)).buyerCount || 0; } catch (e) {} }
out.buyerCountAll = out.buyerCountMain + out.buyerCountPositions; // badges count every position; levels the contract pays #main on depend on buyerCount alone
const bal = await ads.balances(mine.ids, s.email);
out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.earnedReserved = bal.earnedReserved; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available;
} catch (e) { out.chainReadError = true; }
let earned = 0n, n = 0;
for (const ev of chain.recentEvents(1e9)) { // whole history, not the last 600
if ((ev.type === 'TierPaid' && ev.recipientId === memberId) || (ev.type === 'AwardPaid' && ev.toId === memberId)) {
earned += BigInt(ev.amountWei); n += 1;
}
}
out.earnedWei = earned.toString();
out.earnCount = n;
}
// achievement milestones (same ladder as the Overview stepper) + one-time credit
// bonuses — computed AFTER buyerCount is read from chain above (else always 0)
{
const bc = out.buyerCountAll != null ? out.buyerCountAll : (out.buyerCount || 0);
const reached = [];
if (out.memberId) reached.push('payouts');
if (bc >= 1) reached.push('firstBuyer');
if (bc >= 2) reached.push('level2');
if (bc >= 5) reached.push('level3');
try { if (out.memberId && friday.earnedBadge(out.memberId)) reached.push('fridays'); } catch (e) {} // five Five Dollar Fridays in a row
try { if (out.email && gamepass.flag(out.email).until) reached.push('gamepass'); } catch (e) {} // ever held a Game Pass (2026-10-22)
try { if (out.email) for (const k of await refuel.badgesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // Monthly Refuel badges (2026-10-24)
try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned
out.milestonesReached = reached;
if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached);
}
// who joined through this member: their invite link uses username when set,
// else code, and the numeric id once on-chain — match all three
const refs = [];
if (acct && acct.code) refs.push(acct.code);
if (acct && acct.username) refs.push(acct.username);
if (memberId) refs.push(String(memberId));
const joined = await accounts.listByReferrer(refs);
const rTot = await ads.earnedTotals(joined.map(r => r.email)); // surf earnings per referral (Marty, 2026-09-29)
out.referrals = joined.map(r => ({
name: r.username || r.email.replace(/^(.).*(@.*)$/, '$1***$2'), // username, else privacy mask
joined: r.created,
lastSeen: r.lastSeen || 0,
wallet: !!r.address, activated: !!r.memberId,
earned: (rTot[r.email] || {}).earned || 0, balance: (rTot[r.email] || {}).balance || 0,
status: r.memberId ? 'payouts on' : r.address ? 'wallet linked' : 'joined free'
}));
out.isAdmin = !!(ADMIN_EMAIL && out.email && String(out.email).toLowerCase() === ADMIN_EMAIL); // shows the Admin link
out.wallUnlocked = wallUnlockedFor(out.buyerCount || 0); // how many wall positions are the member's own
return json(res, 200, out);
}
// -- linked positions (Qualified Start): list, refresh from chain, unlink
if (p === '/api/my/positions' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const acct = await accounts.byEmail(s.email);
const mainId = await auth.refreshMemberId(s);
const list = await accounts.positions(s.email);
const out = [];
const posIds = [mainId, ...list.map(p => p.memberId)].filter(Boolean);
let balPer = {}, credited = 0; try { const bb = await ads.balances(posIds, s.email); credited = bb.credited; for (const p of bb.per) balPer[p.memberId] = p.avail; } catch (e) {}
// every position's chain reads run side by side (2026-10-19: one after another took 3-8 s for members with several)
out.push(...await Promise.all(list.map(async pos => {
let id = pos.memberId;
if (!id) { try { id = await chain.memberIdByAccount(pos.address); if (id) await accounts.setPositionMember(pos.address, id); } catch (e) {} }
const row = { address: pos.address, memberId: id || 0, buyerCount: 0, counted: false, credits: 0, created: pos.created };
if (id) {
const [mm, blocked] = await Promise.all([chain.member(id).catch(() => null), payoutChainBlocked(id, 3).catch(() => false)]);
if (mm) { row.buyerCount = mm.buyerCount; row.counted = mm.countedAsBuyer; row.sponsorId = mm.sponsorId; }
row.credits = balPer[id] != null ? balPer[id] : 0;
row.noPayout = blocked; // linkage only: a buy from here would pay a listed wallet
}
return row;
})));
const main = { address: (acct && acct.address) || null, memberId: mainId, credits: 0, buyerCount: 0 };
if (mainId) {
main.credits = balPer[mainId] != null ? balPer[mainId] : 0;
try { main.buyerCount = (await chain.member(mainId)).buyerCount; } catch (e) {}
main.noPayout = await payoutChainBlocked(mainId, 3);
}
// live POL balances (the link signature proved the wallet is theirs) + a POL/USD rate from the catalog
const bal = async a => { try { return BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { return null; } };
if (main.address) main.balanceWei = await bal(main.address);
for (const row of out) row.balanceWei = await bal(row.address);
let polUsd = 0; try { const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {}
return json(res, 200, { main, positions: out, polUsd, totalCredits: main.credits + out.reduce((n, r) => n + r.credits, 0), credited });
}
if (p === '/api/my/positions/remove' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await accounts.removePosition(s.email, b.address);
return json(res, r.error ? 400 : 200, r);
}
// -- coaching: every direct's ladder rung, stalled flag, and what to say
// -- holding tank: waiting members, my adoptions, adopt, release (pay it forward)
// -- promo code typed on the dashboard
if (p === '/api/my/promo/redeem' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const g = await promos.redeem(b.code, s.email, 'dashboard', '');
if (g.error) return json(res, 400, g);
const paid = await payPromo(s.email, todayCT());
return json(res, 200, { ok: true, credits: g.credits, now: paid.reduce((n, x) => n + x.amount, 0), step: g.step, steps: g.steps, code: g.code, partner: g.partner });
}
// -- admin: member card. GET ?q= resolves email / @username / #id / share code / wallet;
// PATCH edits username, sponsor, main wallet or grants credits; DELETE removes a free account (2026-09-13)
if (p === '/api/admin/member' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const q = u.searchParams.get('q') || u.searchParams.get('email') || '';
const a = await adminMember.resolve(q);
if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' });
return json(res, 200, Object.assign(await adminMember.view(a.email), { pwPasses: pwPasses.get(String(a.email).toLowerCase()) || null })); // mint passes on the card (2026-10-10)
}
if (p === '/api/admin/member' && req.method === 'PATCH') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const e = String(b.email || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e);
if (!acct) return json(res, 404, { error: 'No such member.' });
if (b.username !== undefined) {
const un = String(b.username || '').trim().toLowerCase();
if (!/^[a-z0-9_]{3,20}$/.test(un)) return json(res, 400, { error: 'Username: 3 to 20 letters, numbers or underscore.' });
const r = await accounts.setUsername(e, un); if (r.error) return json(res, 400, r);
console.log('admin username', e, un);
}
if (b.sponsorRef !== undefined) { const r = await follow.setDeliberate(e, String(b.sponsorRef || '').trim(), 'admin', 'admin member card'); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); } // deliberate: follows to LinkSpin until bound
if (b.address !== undefined) {
const a = String(b.address || '').trim().toLowerCase();
if (a && !/^0x[0-9a-f]{40}$/.test(a)) return json(res, 400, { error: 'That is not a wallet address.' });
const r = await accounts.adminSetAddress(e, a || null); if (r.error) return json(res, 400, r);
let mid = 0; if (a) { try { mid = Number(await chain.memberIdByAccount(a)) || 0; } catch (x) {} }
await accounts.setMemberId(e, mid);
if (db.enabled()) await db.q('UPDATE sessions SET address=?, member_id=? WHERE email=?', [a || null, mid || null, e]).catch(() => {});
console.log('admin wallet swap', e, a || '(none)', 'member', mid);
}
if (b.grantCredits !== undefined) {
const n = Math.round(Number(b.grantCredits));
if (!(n > 0) || n > 100000) return json(res, 400, { error: 'Credits: a whole number from 1 to 100,000.' });
// The member sees this note in their Credit activity, so let the reason travel with
// the grant. A correction that reads "granted by admin" explains nothing; one that
// names itself is the difference between a refund and a mystery (Marty, 2026-09-17).
const why = String(b.note || '').trim().slice(0, 120) || 'Credits granted by admin';
// purchased: true returns PURCHASED credits (a refund of money the member paid) at purchase grade, so they keep their
// money value; without it the grant is ordinary earned credits (2026-10-04, the Shift AI refunds)
if (b.purchased === true) await ads.addEarned(e, n, { purchased: true, log: { kind: 'credit', note: why } });
else await ads.addEarned(e, n, { log: { kind: 'grant', note: why } });
console.log('admin credits', e, n, String(b.note || '').slice(0, 100));
}
return json(res, 200, await adminMember.view(e));
}
// -- link-farm scan (2026-10-30): last result + allowlist, run now (no Telegram), allow / unallow an email
if (p === '/api/admin/spamscan' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, spamscan.view()); }
if (p === '/api/admin/spamscan/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); await spamscan.run({ manual: true, quiet: true }); return json(res, 200, spamscan.view()); }
if (p === '/api/admin/spamscan/allow' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'Which email?' });
spamscan.setAllow(e, !b.remove); console.log('spamscan allowlist', b.remove ? 'removed' : 'added', e);
return json(res, 200, spamscan.view());
}
if (p === '/api/admin/member' && req.method === 'DELETE') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const e = String(u.searchParams.get('email') || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e);
if (!acct) return json(res, 404, { error: 'No such member.' });
if (acct.memberId) return json(res, 400, { error: 'Member #' + acct.memberId + ' is registered on-chain and cannot be deleted.' });
const pos = await accounts.positions(e); if (pos.some(x => x.memberId)) return json(res, 400, { error: 'This account owns a registered position and cannot be deleted.' });
const r = await accounts.removeAccount(e); if (r.error) return json(res, 400, r);
if (db.enabled()) await db.q('DELETE FROM sessions WHERE email=?', [e]).catch(() => {});
console.log('admin removed account', e);
return json(res, 200, { ok: true });
}
// -- release notes + roadmap (public read; admin write) (Marty, 2026-09-14)
if (p === '/api/releases' && req.method === 'GET') return json(res, 200, releases.publicView());
// -- promo toolkit: tiers by badge + the AI Copy Engine (Surge+), credits beyond the free allowance
if (p === '/api/my/toolkit' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await toolkit.status(s.email));
}
if (p === '/api/my/toolkit/generate' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await toolkit.generate(s.email, String(b.kind || ''), String(b.brief || ''), String(b.angle || 'plain'));
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/toolkit/template' && req.method === 'POST') { // Spark: one-tap campaign aimed at the member's link
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req); const memberId = await auth.refreshMemberId(s);
const r = await toolkit.template(s.email, memberId, (await myMemberIds(s)).ids, String(b.kind || ''), Number(b.budget) || 0);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/toolkit/split' && req.method === 'GET') { // Circuit: per-angle views/joins/buyers for the member's link
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await toolkit.split(s.email));
}
if (p === '/api/my/toolkit/videos' && req.method === 'GET') { // Circuit: Video Maker list
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await toolkit.videos(s.email));
}
if (p === '/api/my/toolkit/video' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await toolkit.makeVideo(s.email, String(b.slug || ''));
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/toolkit/team' && req.method === 'GET') { // Nexus: Leader Ops
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await toolkit.team(s.email));
}
if (p === '/api/my/toolkit/nudge' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req); const memberId = await auth.refreshMemberId(s);
const r = await toolkit.nudge(s.email, memberId, String(b.email || ''), String(b.text || ''));
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/toolkit/grant' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await toolkit.grant(s.email, String(b.email || ''), Number(b.credits) || 0);
if (r.ok) pushFeed({ type: 'Grant', from: r.fromName, to: r.toName, credits: r.credits, ts: Date.now() });
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/toolkit/promo' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await toolkit.partnerCode(s.email, String(b.code || ''), Number(b.credits) || 0);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/toolkit' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await toolkit.adminUsage());
}
if (p === '/api/leaderboard' && req.method === 'GET') { // public standings; signed-in members also get their own row
const s = await auth.fromRequest(req);
const period = ['week', 'month', 'all', 'lastweek', 'lastmonth'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week';
return json(res, 200, await leaderboard.view(period, s && s.email ? s.email : null));
}
if (p === '/api/admin/updates' && req.method === 'GET') { // member update emails: notes, audiences, log
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const since = updates.lastSentAt();
return json(res, 200, Object.assign({ notes: releases.notes().map(n => ({ id: n.id, title: n.title, date: n.date, fresh: !since || (n.created || 0) > since || (n.date && new Date(n.date + 'T12:00:00Z').getTime() > since) })), audiences: updates.AUDIENCES, counts: updates.countsSnapshot(), mailer: mailer.hasKey(), lastSentAt: since, draft: updates.draft() }, updates.status()));
}
if (p === '/api/admin/updates/draft' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { ok: true, draft: updates.saveDraft(await readBody(req)) });
}
if (p === '/api/admin/updates/preview' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
return json(res, 200, updates.compose({ subject: b.subject, intro: b.intro, closing: b.closing, noteIds: (b.noteIds || []).map(String) }, { email: ADMIN_EMAIL, username: 'you' }));
}
if (p === '/api/admin/updates/send' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = await updates.send({ subject: b.subject, intro: b.intro, closing: b.closing, image: b.image, imageLink: b.imageLink, noteIds: (b.noteIds || []).map(String), audience: b.audience, to: Array.isArray(b.to) ? b.to.slice(0, 5000) : null }, { test: !!b.test });
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/releases' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { notes: releases.notes(), roadmap: releases.roadmap(), tags: releases.TAGS, statuses: releases.STATUSES });
}
if (p === '/api/admin/releases' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = b.kind === 'roadmap' ? releases.saveRoadmap(b) : releases.saveNote(b);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/releases' && req.method === 'DELETE') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, releases.remove(u.searchParams.get('kind'), String(u.searchParams.get('id') || '')));
}
// -- admin: blog (list all incl. drafts, save/create, delete) (Marty, 2026-09-12)
if (p === '/api/admin/blog' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const slug = u.searchParams.get('slug');
if (slug) { const post = await blog.get(slug); return post ? json(res, 200, { post }) : json(res, 404, { error: 'No such post.' }); }
return json(res, 200, { syndication: syndicate.enabled(), posts: (await blog.listAll()).map(x => ({ slug: x.slug, title: x.title, status: x.status, tags: x.tags, publishedAt: x.publishedAt, updated: x.updated, views: x.views, excerpt: x.excerpt, cover: x.cover, syndicated: syndicate.statusOf(x.slug) })) });
}
if (p === '/api/admin/blog' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const before = b.existingSlug ? await blog.get(b.existingSlug) : null;
const r = await blog.save(b, b.existingSlug || null);
if (r.ok && r.post.status === 'published' && (!before || before.status !== 'published') && !b.noSyndicate) {
// first time this article goes live: push it to X + Instagram (never repeated for the same slug)
syndicate.publish(r.post).catch(e => console.error('syndication', e.message));
r.syndicating = syndicate.enabled();
}
r.syndicated = syndicate.statusOf(r.post.slug);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/blog/syndicate' && req.method === 'POST') { // manual: post (or retry) a published article
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const post = await blog.get(String(b.slug || ''));
if (!post) return json(res, 404, { error: 'No such post.' });
if (post.status !== 'published') return json(res, 400, { error: 'Publish the article first.' });
if (!syndicate.enabled()) return json(res, 400, { error: 'No Blotato key on the server.' });
const st = await syndicate.publish(post, { force: !!b.force });
return json(res, 200, { ok: true, syndicated: st });
}
if (p === '/api/admin/blog' && req.method === 'DELETE') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const slug = u.searchParams.get('slug'); if (!slug) return json(res, 400, { error: 'slug' });
return json(res, 200, await blog.remove(slug));
}
// -- admin: promo codes (create/update, switch on/off, redemptions)
if (p === '/api/admin/promos' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await promos.adminView());
}
if (p === '/api/admin/promos' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = await promos.create(b);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/promos' && req.method === 'PATCH') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = await promos.setActive(b.code, !!b.active);
return json(res, r.error ? 400 : 200, r);
}
// -- username suggestion for the required first step (Marty, 2026-09-12): email prefix, cleaned, unique
if (p === '/api/my/username-suggest' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
let base = String(s.email).split('@')[0].toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 18);
if (!/[a-z]/.test(base)) base = 'member' + base;
if (base.length < 3) base = (base + 'xyz').slice(0, 3);
let pick = base;
for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i;
return json(res, 200, { suggest: pick });
}
if (p === '/api/my/tank' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await tank.view(s.email));
}
// -- achievement badge -> Telegram (payments topic + the main group), once per badge per member.
// The browser composes the personalised image (canvas, same as Share) and posts it here.
if (p === '/api/my/badge-post' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const key = String(u.searchParams.get('key') || '');
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
if (!/^image\/jpeg/.test(String(req.headers['content-type'] || ''))) return json(res, 400, { error: 'Send the badge as a JPEG.' });
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
const held = await ads.milestonesOf(s.email);
if (!held.includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' });
const log = badgeLog(); const mine = log[s.email] || {};
if (mine[key]) return json(res, 200, { ok: true, already: true });
// manual re-posts (the button) are Marty's only; members' badges go out automatically on unlock
if (u.searchParams.get('manual') === '1' && s.email !== ADMIN_EMAIL) return json(res, 403, { error: 'Badges post automatically when they unlock.' });
const a = await accounts.byEmail(s.email);
const who = a && a.username ? '@' + a.username : (a && a.memberId ? 'member #' + a.memberId : 'a member');
const link = a && a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com';
const [label, sub] = BADGE_META[key];
const caption = '\u{1F3C6} <b>InstantAdPay</b> \u00b7 <b>' + who.replace(/[<>&]/g, '') + '</b> unlocked <b>' + label + '</b>: ' + sub + '\n' + link;
// the server draws the card (a phone's canvas can come out blank: cryptomonk, 2026-09-16); the upload is the fallback
try { const srv = await badge.render(key, a && a.username ? a.username : (a && a.memberId ? 'member #' + a.memberId : '')); if (srv) jpeg = srv; } catch (e) {}
const sc = siteConfig(); let sent = 0;
if (sc.telegramBotToken && sc.telegramEchoChatId) {
if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; // payments topic
if (String(sc.telegramBadgeGeneral || '1') !== '0' && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; // the main group (General)
}
mine[key] = { ts: Date.now(), sent }; log[s.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {}
pushFeed({ type: 'Badge', member: who, label, ts: Date.now() });
console.log('badge posted', s.email, key, 'sent', sent);
return json(res, 200, { ok: true, sent });
}
// -- member's own share: store the composed badge so a public page can carry it as the preview image
if (p === '/api/my/badge-image' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const key = String(u.searchParams.get('key') || '');
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
if (!(await ads.milestonesOf(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' });
const a = await accounts.byEmail(s.email);
if (!a || !a.username) return json(res, 400, { error: 'Pick a username first; the share page carries it.' });
try { const srv = await badge.render(key, a.username); if (srv) jpeg = srv; } catch (e) {}
fs.writeFileSync(path.join(UPLOADS_DIR, 'badge-' + a.username + '-' + key + '.jpg'), jpeg);
return json(res, 200, { ok: true, page: 'https://instantadpay.com/b/' + a.username + '/' + key, image: 'https://instantadpay.com/badge-img/' + a.username + '/' + key + '.jpg' });
}
if (p === '/api/admin/badge-repost' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const key = String(b.key || ''); const a = await accounts.byEmail(String(b.email || '').toLowerCase());
if (!a || !BADGE_META[key]) return json(res, 400, { error: 'Unknown member or badge.' });
if (!(await ads.milestonesOf(a.email)).includes(key) && !(key === 'gamepass' && gamepass.flag(a.email).until)) return json(res, 400, { error: 'That member has not unlocked that badge.' }); // the Game Pass badge is earned by holding a pass, recorded or not yet
const jpeg = await badge.render(key, a.username || ('member #' + a.memberId)); if (!jpeg) return json(res, 500, { error: 'Render failed.' });
const who = a.username ? '@' + a.username : 'member #' + a.memberId; const link = a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com';
const [label, sub] = BADGE_META[key];
const caption = '\u{1F3C6} <b>InstantAdPay</b> \u00b7 <b>' + who.replace(/[<>&]/g, '') + '</b> unlocked <b>' + label + '</b>: ' + sub + '\n' + link;
const sc = siteConfig(); let sent = 0;
if (sc.telegramBotToken && sc.telegramEchoChatId) {
if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++;
if (String(sc.telegramBadgeGeneral || '1') !== '0' && b.general !== false && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++;
}
const log = badgeLog(); const mine = log[a.email] || {}; mine[key] = { ts: Date.now(), sent, repost: true }; log[a.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {}
return json(res, 200, { ok: true, sent, bytes: jpeg.length });
}
if (p === '/api/my/badge-posted' && req.method === 'GET') { // which of my badges are already on Telegram
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, { posted: Object.keys(badgeLog()[s.email] || {}), canPost: s.email === ADMIN_EMAIL });
}
if (p === '/api/my/tank/adopt' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
if (fraud.excluded(s.email)) return json(res, 403, { error: 'Adoptions are not available on this account. Contact support at instantadpay.com/support.' });
const r = await tank.adopt(s.email, b.who, b.note);
if (r.ok) { // tell the payments topic who picked whom up (Marty, 2026-09-12)
tankPickupPost(r.adopterName, r.adopteeName, false);
}
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/tank/release' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await tank.release(s.email, b.email);
if (r.ok) { // the feed shows releases too, so a pickup-and-drop is visible for what it is (Marty, 2026-09-13)
pushFeed({ type: 'Released', sponsor: r.ownerName, member: r.memberName, ts: Date.now() });
try {
const sc = siteConfig();
const clean = t => String(t || '').replace(/[<>&]/g, '');
if (sc.telegramBotToken && sc.telegramEchoChatId)
telegramSend(sc.telegramEchoChatId, '\u{1FAA3} <b>InstantAdPay</b> \u00b7 <b>' + clean(r.ownerName) + '</b> returned <b>' + clean(r.memberName) + '</b> to the holding tank', sc.telegramEchoTopicId);
} catch (e) {}
}
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/tank/contacted' && req.method === 'POST') { // sponsor reached the lead off-site: reset the rescue clock
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await tank.markContacted(s.email, b.email);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/gift' && req.method === 'POST') { // PIF: log a wallet-to-wallet POL gift and tell the recipient
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await tank.recordGift(s.email, b.email, b.tx, b.pol);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/walletnudge' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, walletnudge.adminView()); }
if (p === '/api/admin/reach' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, reach.adminView()); }
if (p === '/api/admin/reach/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await reach.run({ dry: !!(b && b.dry) })); }
if (p === '/api/admin/lssync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, Object.assign(lssync.adminView(), { inbound: lsinbound.adminView(), conv: lsconv.adminView() })); }
if (p === '/api/admin/lsinbound' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, lsinbound.adminView()); }
// -- reverse registry sync from LinkSpin (2026-10-15): the same signed rows LinkSpin accepts from us (HMAC LS_SYNC_SECRET
// over ts + newline + raw body, 10-minute window). New people become waiting accounts with their LinkSpin line; existing
// accounts keep their sponsor and only get empty fields filled. No mail, no notices, no chain (lsinbound.js).
// -- Monthly Refuel partner calls from LinkSpin (signed like the registry): a LinkSpin package to record (the answer carries
// LinkSpin's grants for that member), the outbox of LinkSpin grants + reminders, acks, and one member's status for its card
if (p.startsWith('/api/partner/refuel/') && req.method === 'POST') {
const sg = await readLsSigned(req, 200000); if (!sg.body) return json(res, sg.status, { error: sg.error });
const b = sg.body; const op = p.slice('/api/partner/refuel/'.length);
if (op === 'purchase') {
const r = await refuel.record({ site: 'linkspin', email: b.email, tx: b.tx, cents: b.cents, credits: b.credits, ts: b.ts });
return json(res, 200, Object.assign({ ok: true }, r, { items: r.on ? await refuel.outbox('linkspin', b.email) : [] }));
}
if (op === 'outbox') return json(res, 200, { ok: true, on: refuel.cfg().on, items: refuel.cfg().on ? await refuel.outbox('linkspin') : [] });
if (op === 'ack') return json(res, 200, { ok: true, acked: await refuel.ack('linkspin', Array.isArray(b.refs) ? b.refs : []) });
if (op === 'status') return json(res, 200, Object.assign({ ok: true }, await refuel.view(b.email)));
if (op === 'goal') { const r = await refuel.setGoal(b.email, b.goal); return json(res, r.error ? 400 : 200, r); }
return json(res, 404, { error: 'unknown op' });
}
// -- the Engine Room, partner side: this site's facts for one member + the streak (LinkSpin builds its own panel from them)
// -- BixPay link for one member, the same resolver (own > sponsor chain > network), for LinkSpin / CTB cards (2026-10-29, read-only there)
if (p === '/api/partner/bixpay' && req.method === 'POST') {
const sg = await readLsSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
const email = String(sg.body.email || '').trim().toLowerCase(); if (!email) return json(res, 400, { error: 'Which member?' });
if (!bixpay.live()) return json(res, 200, { ok: true, live: false });
const a = await accounts.byEmail(email); const r = await bixpay.resolve(a);
return json(res, 200, { ok: true, live: true, own: (a && a.bixPartnerLink) || null, link: r.link, whose: r.whose, name: r.name, using: bixpay.usingLine(r), editUrl: 'https://instantadpay.com/my#profile', guide: 'https://instantadpay.com/bixpay' });
}
if (p === '/api/partner/engine' && req.method === 'POST') {
const sg = await readLsSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
const email = String(sg.body.email || '').trim().toLowerCase(); if (!email) return json(res, 400, { error: 'Which member?' });
const rv = await refuel.view(email);
return json(res, 200, { ok: true, refuel: rv, facts: rv.on ? await engine.facts({ site: 'iap', adminMember, ads, coach }, email) : null });
}
if (p === '/api/partner/registry' && req.method === 'POST') {
const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
const b = sg.body;
const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : [];
return json(res, 200, Object.assign({ ok: true }, await lsinbound.receive(rows)));
}
// -- sponsor check between InstantAdPay and LinkSpin (2026-10-22, sponsorfollow.js). Partner side: LinkSpin reads our
// facts and, on an admin's pick in ITS Sponsor check, asks us to apply a sponsor (refused when the member is bound here).
if (p === '/api/partner/sponsor-facts' && req.method === 'POST') {
const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
const emails = Array.isArray(sg.body.emails) ? sg.body.emails.slice(0, 5000) : null;
return json(res, 200, { ok: true, proto: SF.PROTO, platform: 'instantadpay', rows: await follow.facts(emails), view: followStore.view() });
}
if (p === '/api/partner/sponsor-apply' && req.method === 'POST') {
const sg = await readLsSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
const b = sg.body; const r = await follow.adminApply(b.email, b.sponsorEmail || null, { note: String(b.note || 'Sponsor check on LinkSpin').slice(0, 120) });
console.log('sponsor check (from LinkSpin)', b.email, '->', b.sponsorEmail || '(tank)', r.error || 'ok');
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/sponsor-check' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const mine = await follow.facts(); let peer = null, peerError = null;
try { peer = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-facts', { all: true }, 90000); } catch (e) { peerError = e.message; }
const mm = peer ? SF.mismatches(mine, peer.rows || []) : { shared: 0, same: 0, rows: [] };
return json(res, 200, Object.assign({ ok: true, at: Date.now(), here: 'instantadpay', peerError, follow: followStore.view(), peerFollow: peer ? peer.view : null }, mm), { 'Cache-Control': 'no-store' });
}
if (p === '/api/admin/sponsor-check/resolve' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const email = String(b.email || '').trim().toLowerCase();
if (!email) return json(res, 400, { error: 'Which member?' });
let r;
if (b.use === 'linkspin') { // LinkSpin's sponsor, applied HERE (refused when bound here)
const peer = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-facts', { emails: [email] }, 30000).catch(e => ({ error: e.message }));
if (peer.error) return json(res, 502, { error: 'Could not read LinkSpin: ' + peer.error });
const row = (peer.rows || [])[0]; if (!row) return json(res, 404, { error: email + ' has no LinkSpin account.' });
r = await follow.adminApply(email, row.sponsorEmail || null, { note: "Sponsor check: used LinkSpin's sponsor" });
} else if (b.use === 'instantadpay') { // our sponsor, applied ON LINKSPIN (LinkSpin refuses when bound there)
const row = (await follow.facts([email]))[0]; if (!row) return json(res, 404, { error: email + ' has no InstantAdPay account.' });
r = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-apply', { email, sponsorEmail: row.sponsorEmail || null, note: "Sponsor check on InstantAdPay: used InstantAdPay's sponsor" }, 30000).catch(e => ({ error: e.message }));
} else return json(res, 400, { error: 'use must be instantadpay or linkspin' });
console.log('sponsor check resolve', email, b.use, r.error || 'ok');
return json(res, r.error ? 400 : 200, r);
}
// -- help desk for LinkSpin (2026-10-16): LinkSpin has no desk of its own; its Help screen, /support page, private ticket
// link and chat hand-off all proxy here, signed like the registry rows. LinkSpin runs the person-facing guards (sign-in,
// honeypot, form age, icon check) and vouches for the email; this side only ever touches platform 'linkspin' tickets
// (LS- refs). Replies to the requester point at LinkSpin (tickets.js BRAND), never an InstantAdPay notice.
m = /^\/api\/partner\/support\/(create|list|view|reply|token|token-reply)$/.exec(p);
if (m && req.method === 'POST') {
const sg = await readLsSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
const b = sg.body, op = m[1];
const email = String(b.email || '').trim().toLowerCase();
const mine = async () => { const t = await tickets.byRef(b.ref); return t && t.platform === 'linkspin' && t.email === email ? t : null; };
const byTok = async () => { const t = await tickets.byToken(b.token); return t && t.platform === 'linkspin' ? t : null; };
if (op === 'create') {
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'That email address does not look right.' });
if (supportFlood('ls:' + email, 8, 3600000)) return json(res, 429, { error: 'You have sent several tickets in the last hour. Add to one of those instead.' }); // backstop behind LinkSpin's own limits
const r = await tickets.create({ platform: 'linkspin', source: ['form', 'public', 'chatbot'].includes(b.source) ? b.source : 'public', email, name: b.name, username: b.username, subject: b.subject, category: b.category, body: b.body });
return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, ref: r.ticket.ref, token: r.token });
}
if (op === 'list') return json(res, 200, { tickets: await tickets.memberList(email, 'linkspin'), unread: await tickets.memberUnread(email, 'linkspin'), categories: tickets.CATEGORIES });
const t = op === 'view' || op === 'reply' ? await mine() : await byTok();
if (!t) return json(res, 404, { error: op.startsWith('token') ? 'This ticket link is not valid. Open the newest email about your ticket, or send a new one.' : 'Ticket not found.' });
if (op === 'view' || op === 'token') return json(res, 200, await tickets.memberView(t));
if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' });
const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, via: op === 'token-reply' ? 'link' : 'web' });
return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket));
}
if (p === '/api/admin/lssync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await lssync.tick(!!(b && b.force))); }
if (p === '/api/admin/walletnudge/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await walletnudge.tick()); }
if (p === '/api/admin/tank' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await tank.adminView());
}
// -- admin Traffic tab: page views + join-page views + signups + $20 buyers, by referring
// domain / first-touch source, by landing page, by angle and by day (Marty, 2026-09-12)
// login-ad showings per Central day, dashboard vs games (2026-10-18: a week of combined sign-ins before the cap decision)
if (p === '/api/admin/login-shows' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { days: await loginShows.report(Number(u.searchParams.get('days')) || 14), slots: await ads.loginSlots() });
}
if (p === '/api/admin/traffic' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const days = Math.min(365, Math.max(1, Number(u.searchParams.get('days')) || 30));
const bix = bixpay.adminView(days); try { for (const m of bix.members) { const a = await accounts.byEmail(m.email); m.name = a ? (a.username ? '@' + a.username : a.email) : m.email; } } catch (e) {} // BixPay clicks per surface and per member (2026-10-29)
const since = Date.now() - days * 86400000, sinceDay = new Date(since).toISOString().slice(0, 10);
const hosts = {}, paths = {}, daily = {}, angles = {};
const H = k => (hosts[k] = hosts[k] || { source: k, hits: 0, joinViews: 0, signups: 0, registered: 0, buyers: 0 });
const Dy = k => (daily[k] = daily[k] || { day: k, hits: 0, signups: 0 });
for (const r of await traffic.rows(sinceDay)) { H(r.host).hits += r.n; paths[r.path] = (paths[r.path] || 0) + r.n; Dy(r.day).hits += r.n; }
for (const v of await coach.viewsSince(since)) { H(v.ref || 'direct').joinViews += 1; const a = angles[v.angle || 'plain'] = angles[v.angle || 'plain'] || { angle: v.angle || 'plain', views: 0, signups: 0 }; a.views += 1; }
const buyerIds = new Set(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'BuyerCounted' && ev.newBuyerId) buyerIds.add(ev.newBuyerId);
for (const a of await accounts.listAll(5000)) {
if (!a.created || a.created < since) continue;
const h = H(a.joinedRef || 'direct'); h.signups += 1; if (a.memberId) h.registered += 1; if (a.memberId && buyerIds.has(a.memberId)) h.buyers += 1;
Dy(new Date(a.created).toISOString().slice(0, 10)).signups += 1;
const k = a.joinedVia || 'plain'; angles[k] = angles[k] || { angle: k, views: 0, signups: 0 }; angles[k].signups += 1;
}
const sources = Object.values(hosts).sort((x, y) => (y.hits + y.joinViews + y.signups * 10) - (x.hits + x.joinViews + x.signups * 10));
return json(res, 200, { starter: starter.adminView(), bixpay: Object.assign(bix, { live: bixpay.live() }), days, sources, paths: Object.entries(paths).map(([path, hits]) => ({ path, hits })).sort((x, y) => y.hits - x.hits),
angles: Object.values(angles).sort((x, y) => y.views - x.views), daily: Object.values(daily).sort((x, y) => x.day < y.day ? -1 : 1),
totals: { hits: sources.reduce((n, s) => n + s.hits, 0), joinViews: sources.reduce((n, s) => n + s.joinViews, 0), signups: sources.reduce((n, s) => n + s.signups, 0), buyers: sources.reduce((n, s) => n + s.buyers, 0) } });
}
if (p === '/api/my/coach' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const cv = await coach.coachView(s.email);
for (const d of cv.directs) if (d.free) { try { d.rescue = await tank.rescueInfo(s.email, await accounts.byEmail(d.email)); } catch (e) {} } // dormant-lead clock
return json(res, 200, cv);
}
// -- link stats: views, joins and buyers per angle link
if (p === '/api/my/linkstats' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await coach.linkStats(s.email));
}
// -- prospects: the member's own follow-up list
// -- Pipeline: the follow-up board (stages from the ledger and the site; notes, follow-ups, tags from the sponsor)
if (p === '/api/my/pipeline' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const sc = siteConfig();
if (!pipeline.visible(sc.pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 200, { live: false, eta: sc.pipelineEta || '' });
const b = await pipeline.board(s.email);
return json(res, 200, Object.assign({ live: true }, b), { 'Cache-Control': 'no-store' });
}
if (p === '/api/my/pipeline/note' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (!pipeline.visible(siteConfig().pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 403, { error: 'The Pipeline is not open yet.' });
const r = await pipeline.save(s.email, await readBody(req));
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/prospects' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, { prospects: await coach.prospects(s.email), statuses: coach.STATUSES });
}
if (p === '/api/my/prospects' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await coach.saveProspect(s.email, await readBody(req));
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/prospects/remove' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await coach.removeProspect(s.email, b.id);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/profile' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const before = await accounts.byEmail(s.email);
// a username is permanent once set: the invite link, the public wall and every
// banner already printed carry it (Marty, 2026-09-10)
if (before && before.username && String(b.username || '').trim().toLowerCase() !== String(before.username).toLowerCase())
return json(res, 400, { error: 'Your username is locked. Your invite link, your public page and any banners you shared all carry @' + before.username + '. Contact support (instantadpay.com/support) if it truly has to change.' });
const r = await accounts.setUsername(s.email, b.username);
// First time a username is set (onboarding): now there's a real name to
// show, so notify the sponsor here rather than at signup (where it'd just
// say "a new member"). Fires once — only on the empty→set transition.
if (!r.error && before && !before.username && b.username) {
const acct = await accounts.byEmail(s.email);
notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {});
// everyone's dashboard: "@name just joined" (and whether they are waiting in the tank)
if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() });
}
return json(res, r.error ? 400 : 200, r);
}
// -- earn credits by viewing ads (attention-gated daily claim)
if (p === '/api/my/earn' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await ads.viewStatus(s.email));
}
// fraud-guarded view flow: the server issues a single-use token when it
// serves the ad, and only counts the view if the dwell elapsed on the
// SERVER clock. Client-side focus tracking pauses the countdown; this is
// the floor a script cannot cheat past.
if (p === '/api/my/earnview' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const status = await ads.viewStatus(s.email);
if (status.views >= status.target || status.claimed) return json(res, 200, { ad: null, status });
const type = String(u.searchParams.get('type') || 'banner');
// members never see (or earn from) their own campaigns in the viewer
const ad = await ads.serve(type === 'text' ? 'text' : 'banner', Object.assign({ excludeEmail: s.email }, viewerGeo(req)));
if (!ad) return json(res, 200, { ad: null, status });
const token = crypto.randomBytes(16).toString('hex');
// the viewer tab frames the advertiser's REAL url (no click counted for a paid view)
earnTokens.set(s.email, { token, ts: Date.now(), adId: ad.id,
targetUrl: await ads.targetOf(ad.id), adName: ad.title || ad.name || null });
return json(res, 200, { ad, token, viewUrl: '/view/' + token, status });
}
// the viewer tab asks where to point the frame (does not consume the token)
if (p === '/api/my/viewinfo' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const t = earnTokens.get(s.email);
if (!t || t.token !== String(u.searchParams.get('token') || ''))
return json(res, 400, { error: 'That view is no longer open. Head back to the dashboard and load the next ad.' });
return json(res, 200, { targetUrl: t.targetUrl, adName: t.adName || null,
dwell: ads.rates().viewDwellSeconds || 10 });
}
// human check: handed out only once the dwell has elapsed on the SERVER clock
if (p === '/api/my/viewchallenge' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const t = earnTokens.get(s.email);
if (!t || t.token !== String(u.searchParams.get('token') || ''))
return json(res, 400, { error: 'That view is no longer open.' });
const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000;
const age = Date.now() - t.ts;
if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) });
if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); }
const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5);
const answer = Math.floor(Math.random() * pick.length);
t.challenge = { answer };
return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) });
}
if (p === '/api/my/adview' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const t = earnTokens.get(s.email);
const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000;
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That view did not check out. Load the next ad and let it finish.' });
const age = Date.now() - t.ts;
if (age < dwellMs - 400) return json(res, 400, { error: 'Watch the full ad first.' });
if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); }
// the human check must be solved on the same token
if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true });
if (Number(b.answer) !== t.challenge.answer) {
t.attempts = (t.attempts || 0) + 1;
t.challenge = null; // force a fresh challenge for the next try
if (t.attempts >= 3) { earnTokens.delete(s.email); return json(res, 400, { error: 'Three misses — that view is void. Head back and load the next ad.' }); }
return json(res, 400, { error: 'Wrong pick.', retry: true });
}
earnTokens.delete(s.email); // single use
return json(res, 200, await ads.recordView(s.email));
}
// -- Friday Bonus Hunts (2026-09-26). The member's own progress, for the Earn tab card.
if (p === '/api/my/friday-bank' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await fridaybank.bankFor(s.email));
}
// PolHunter asks, server to server, signed with the same shared secret as the hand-off:
// sig = HMAC-SHA256(HUNT_SSO_SECRET, 'fridaybank:' + email + ':' + ts), ts within 5 minutes.
if (p === '/api/hunt/friday-bank' && req.method === 'GET') {
const secret = String(process.env.HUNT_SSO_SECRET || '').trim();
if (secret.length < 32) return json(res, 503, { error: 'not connected' });
const q = new URL(req.url, 'http://x').searchParams;
const email = String(q.get('email') || '').trim().toLowerCase(), ts = Number(q.get('ts') || 0), sig = String(q.get('sig') || '');
if (!email || !ts || Math.abs(Date.now() - ts) > 300000) return json(res, 400, { error: 'stale or missing' });
const want = crypto.createHmac('sha256', secret).update('fridaybank:' + email + ':' + ts).digest('hex');
if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) return json(res, 401, { error: 'bad signature' });
return json(res, 200, await fridaybank.bankFor(email));
}
// -- PolHunter hand-off (2026-09-19): sign the member across; polhunter.com verifies with the shared secret
if (p === '/api/my/polhunter' && req.method === 'GET') { gamestats.handoff('polhunter');
const s = await auth.fromRequest(req);
// not signed in: to sign-in, keeping a PolHunter share link's ?ref so the newcomer's sponsor holds (the viral-link rule on /my sets it)
if (!s || !s.email) { const ref = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); res.writeHead(302, { Location: '/my' + (ref ? '?ref=' + ref : '') }); return res.end(); }
const secret = String(process.env.HUNT_SSO_SECRET || '').trim(); const huntUrl = String(process.env.HUNT_URL || 'https://polhunter.com').replace(/\/+$/, '');
if (secret.length < 32) return json(res, 503, { error: 'PolHunter is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const memberId = (acct && acct.memberId) || s.memberId || 0;
if (!memberId) { res.writeHead(302, { Location: '/my#wallet' }); return res.end(); }
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
// the sponsor rides across too (Marty, 2026-09-23): PolHunter pays a referral bounty, and the
// person who gets it has to be the one this member actually joined under here, not a cookie
// PolHunter guessed at. sponsorRef is the upline's username or code, matching /join/<ref>.
let sponsorRef = (acct && acct.sponsorRef) || '';
const payload = JSON.stringify({ iat: Date.now(), exp: Date.now() + 5 * 60000, nonce: crypto.randomBytes(12).toString('hex'), memberId: Number(memberId), email: s.email, wallet: (acct && acct.address) || s.address || null, username: (acct && acct.username) || null, sponsorRef: sponsorRef || null, joinedAt: (acct && acct.created) || null,
// where they first arrived from, so PolHunter can pay a bounty only for people it sent
joinedRef: (acct && acct.joinedRef) || null, gamePass: gamepass.flag(s.email) });
const tok = b64u(payload) + '.' + b64u(crypto.createHmac('sha256', secret).update(payload).digest());
res.writeHead(302, { Location: huntUrl + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end(); // the loop is closed
}
// -- Drip Runner hand-off (2026-09-30): sign the member across, the game verifies with the shared secret
if (p === '/api/my/driprunner' && req.method === 'GET') { gamestats.handoff('driprunner');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': 'iap.return=driprunner; Path=/; SameSite=Lax; Max-Age=1800' + (IS_PROD ? '; Secure' : ''), 'Cache-Control': 'no-store' }); return res.end(); } // sign in first, then straight back into the game
if (DR_SECRET().length < 32) return json(res, 503, { error: 'Drip Runner is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const memberId = (acct && acct.memberId) || s.memberId || 0;
const tok = drMint({ memberId: Number(memberId), email: s.email, wallet: (acct && acct.address) || s.address || null, username: (acct && acct.username) || null,
sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }); // the game credits referrals to the IAP sponsor
res.writeHead(302, { Location: DR_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end();
}
// -- PolyWarriors hand-off (2026-10-05): sign the member across; the game verifies with PW_SSO_SECRET
// PolyWarriors weekly member-fight season prizes (Marty 2026-10-05): the game signs one claim per week and place; InstantAdPay
// decides the amount (setting pwWeeklyPrize, default '1000,500,250' earned credits) and pays each week+place once.
// admin: credit or remove PolyWarriors mint passes on an account (support fixes), logged in the pass history
if (p === '/api/admin/pw/pass' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(), n = Math.round(Number(b.n) || 0);
if (!e || !n || Math.abs(n) > 20) return json(res, 400, { error: 'email and n (1-20, or negative to remove) required' });
const left = pwPassAdd(e, n, 'admin:' + String(b.why || 'support').slice(0, 80));
console.log('polywarriors admin pass', e, n > 0 ? '+' + n : n, 'left', left, b.why || '');
return json(res, 200, { ok: true, email: e, passes: left });
}
if (p === '/api/game/pw/prize' && req.method === 'POST') {
const b = await readBody(req); const r = pwOpen(b.t);
if (r.error) return json(res, 400, { error: r.error });
const c = r.claims, place = Number(c.place), week = String(c.week || '');
if (c.kind !== 'pw-prize' || !(place >= 1 && place <= 3) || !/^\d{4}-\d{2}-\d{2}$/.test(week) || !c.email) return json(res, 400, { error: 'bad claim' });
if (Math.abs(Date.now() - new Date(week + 'T12:00:00Z').getTime()) > 14 * 86400000) return json(res, 400, { error: 'stale week' });
const k = week + ':' + place; if (pwPrizes.get(k)) return json(res, 200, { ok: true, already: true });
const acct = await accounts.byEmail(String(c.email).toLowerCase()); if (!acct) return json(res, 404, { error: 'no account' });
const amts = String(siteConfig().pwWeeklyPrize || '1000,500,250').split(',').map(x => Math.max(0, Math.round(Number(x) || 0)));
const credits = Math.min(amts[place - 1] || 0, 5000); if (!credits) return json(res, 200, { ok: true, credits: 0 });
pwPrizes.set(k, { email: acct.email, credits, at: Date.now() });
await ads.addEarned(acct.email, credits, { log: { kind: 'bonus', note: 'PolyWarriors weekly season: #' + place + ' (week of ' + week + ')', ref: 'pwprize:' + k } });
console.log('polywarriors weekly prize', k, acct.email, credits);
return json(res, 200, { ok: true, credits });
}
if (p === '/api/my/polywarriors' && req.method === 'GET') { gamestats.handoff('polywarriors');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'polywarriors', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (PW_SECRET().length < 32) return json(res, 503, { error: 'PolyWarriors is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = pwMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null });
res.writeHead(302, { Location: PW_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- SpellWheel hand-off (2026-10-04): sign the member across; the game verifies with SW_SSO_SECRET
if (p === '/api/my/polybreak' && req.method === 'GET') { gamestats.handoff('polybreak');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'polybreak', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (PB_SECRET().length < 32) return json(res, 503, { error: 'PolyBreak is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = pbMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorRef: (acct && acct.sponsorRef) || null });
res.writeHead(302, { Location: PB_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- POL Miner hand-off (2026-10-28): sign the member across; the game verifies with POLMINER_SSO_SECRET
// -- Warp & Wares hand-off (2026-10-29): sign the member across; the game verifies with WW_SSO_SECRET
if (p === '/api/my/warpwares' && req.method === 'GET') { gamestats.handoff('warpwares');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'warpwares', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (WW_SECRET().length < 32) return json(res, 503, { error: 'Warp & Wares is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = wwMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorRef: (acct && acct.sponsorRef) || null });
res.writeHead(302, { Location: WW_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
if (p === '/api/my/polminer' && req.method === 'GET') { gamestats.handoff('polminer');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'polminer', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (PM_SECRET().length < 32) return json(res, 503, { error: 'POL Miner is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = pmMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorRef: (acct && acct.sponsorRef) || null });
res.writeHead(302, { Location: PM_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
if (p === '/api/my/spellwheel' && req.method === 'GET') { gamestats.handoff('spellwheel');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'spellwheel', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (SW_SECRET().length < 32) return json(res, 503, { error: 'SpellWheel is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = swMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null });
res.writeHead(302, { Location: SW_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- ClutterHunt hand-off (2026-10-03): sign the member across; the game verifies with SEEK_SSO_SECRET
if (p === '/api/my/clutterhunt' && req.method === 'GET') { gamestats.handoff('clutterhunt');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'clutterhunt', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (SEEK_SECRET().length < 32) return json(res, 503, { error: 'ClutterHunt is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = seekMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null });
res.writeHead(302, { Location: SEEK_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- Shards of Valor hand-off (2026-10-18): sign the member across; the game verifies with SOV_SSO_SECRET
if (p === '/api/my/shardsofvalor' && req.method === 'GET') { gamestats.handoff('shardsofvalor');
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'shardsofvalor', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (SOV_SECRET().length < 32) return json(res, 503, { error: 'Shards of Valor is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = sovMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null });
res.writeHead(302, { Location: SOV_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- Gem Kingdom hand-off (2026-10-01): sign the member across; the game verifies with GK_SSO_SECRET
if (p === '/api/my/gemkingdom' && req.method === 'GET') { gamestats.handoff('gemkingdom');
const s = await auth.fromRequest(req);
// a newcomer from a Gem Kingdom feed post carries the poster's ?ref through to /my, where the viral-link rule sets the sponsor
const gkRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (gkRef ? '?ref=' + encodeURIComponent(gkRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'gemkingdom', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (GK_SECRET().length < 32) return json(res, 503, { error: 'Gem Kingdom is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = gkMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null });
res.writeHead(302, { Location: GK_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- the Crown shop checkout: confirm, spend the credits, sign a receipt back to the game
if (p === '/gk/shop' && req.method === 'GET') {
const t = u.searchParams.get('t') || ''; const r = gkOpen(t);
if (r.error) return gkPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="sub">' + gkEsc(r.error) + '</p><a class="btn blue" href="' + GK_URL() + '/play?open=shop">Back to Gem Kingdom</a>');
const c = r.claims; if (c.kind !== 'gk-buy' || !c.order || !(c.credits > 0) || !(c.crowns > 0)) return gkPage(res, 400, 'Order problem', '<h1>That is not a Crown order</h1>');
const done = gkOrders.get(c.order);
if (done && done.status === 'paid') { const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: c.email, crowns: c.crowns, credits: c.credits, paid: done.paid != null ? done.paid : c.credits, ref: done.campaignId }, 24 * 3600000); res.writeHead(302, { Location: c.ret + '?t=' + rc, 'Cache-Control': 'no-store' }); return res.end(); }
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.gkshop', t, 7200), gkCookie('iap.return', 'gkshop', 1800)] }); return res.end(); }
if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Different account', '<h1>Different account</h1><p class="sub">This order was started by the Gem Kingdom player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account in both places.</p><a class="btn blue" href="' + GK_URL() + '/play">Back to Gem Kingdom</a>');
const { ids } = await myMemberIds(s); const bal = await ads.balances(ids, s.email);
const free = (bal.earned || 0) + (bal.credited || 0); const best = (bal.per || []).slice().sort((a, b) => b.avail - a.avail)[0] || { avail: 0 };
const can = free >= c.credits || best.avail >= c.credits; const usable = Math.max(free, best.avail);
const dollars = '$' + (c.credits / 100).toFixed(c.credits % 100 ? 2 : 0);
const head = '<p class="sub">Gem Kingdom &middot; Crown Shop</p><h1>' + gkEsc(c.label || 'Crowns') + '</h1><div class="big">' + Number(c.crowns) + ' Crowns</div>'
+ '<div class="row"><span>Price</span><span>' + Number(c.credits).toLocaleString('en-US') + ' ad credits (' + dollars + ')</span></div>'
+ '<div class="row"><span>Your available credits</span><span>' + Number(bal.available || 0).toLocaleString('en-US') + '</span></div>';
if (can) {
const csrf = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase());
return gkPage(res, 200, 'Confirm your Crowns', head + '<form method="post" action="/gk/shop/confirm"><input type="hidden" name="t" value="' + gkEsc(t) + '"><input type="hidden" name="csrf" value="' + csrf + '"><button class="btn" type="submit">Spend ' + Number(c.credits).toLocaleString('en-US') + ' credits</button></form>'
+ '<a class="alt" href="' + GK_URL() + '/play?open=shop">Cancel and go back</a><p class="fine">Crowns are game items. They have no cash value and cannot be withdrawn. The credits come off your ad balance and show in your Credit activity.</p>');
}
const need = c.credits - usable;
return gkPage(res, 200, 'More credits needed', head + '<p class="warn">You need ' + need.toLocaleString('en-US') + ' more credits for this pack' + (bal.available >= c.credits ? ' (some of your credits are already budgeted to live campaigns or spread across positions)' : '') + '.</p>'
+ '<a class="btn" href="/gk/shop/topup?t=' + encodeURIComponent(t) + '">Buy a credit package</a><a class="btn blue" href="' + GK_URL() + '/play?open=shop">Pick a smaller pack</a>'
+ '<p class="fine">A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.</p>');
}
// ---- PolyWarriors paid mints: every mint after the free first one comes with a new $5+ package purchase
if (p === '/pw/mint' && req.method === 'GET') {
const t = u.searchParams.get('t') || ''; const r = pwOpen(t);
if (r.error) return gkPage(res, 400, 'Mint problem', '<h1>That mint did not work</h1><p class="sub">' + gkEsc(r.error) + '</p><a class="btn blue" href="' + PW_URL() + '/play">Back to PolyWarriors</a>');
const c = r.claims; if (c.kind !== 'pw-mint' || !c.order || !(c.serial > 0)) return gkPage(res, 400, 'Mint problem', '<h1>That is not a mint order</h1>');
const done = pwOrders.get(c.order);
if (done && done.status === 'paid') {
// a visible hand-back instead of a silent redirect chain (Zachary's iPad sat on the mint form after a pass mint,
// 2026-10-12): the page says the mint is done, returns to the game by itself, and keeps a button in case it does not.
const rc = pwReceipt(c.order, done); const back = (pwIsGameUrl(done.ret) ? done.ret : PW_URL() + '/api/iap/mint-receipt') + '?t=' + rc;
res.setHeader('Set-Cookie', gkCookie('iap.pwmint', '', 0));
return gkPage(res, 200, 'Minted', '<p class="sub">PolyWarriors &middot; Mint to your wallet</p><h1>' + gkEsc(done.label || ('Warrior #' + done.serial)) + '</h1><div class="big">Minting now</div>'
+ '<p class="sub">Your warrior is on its way to the wallet on your InstantAdPay account. Taking you back to the game.</p>'
+ '<a class="btn blue" href="' + gkEsc(back) + '">Back to PolyWarriors</a>'
+ '<p class="fine">If this page stays, tap the button. The game shows the warrior as On Polygon once the transaction confirms, usually within a minute.</p>', '<meta http-equiv="refresh" content="2;url=' + gkEsc(back) + '">');
}
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.pwmint', t, PW_MINT_COOKIE_S), gkCookie('iap.return', 'pwmint', 1800)] }); return res.end(); }
if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Different account', '<h1>Different account</h1><p class="sub">This mint was started by the PolyWarriors player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account and tap Mint again.</p>');
// the order waits here until a new package purchase from this account lands on chain (oldest waiting order first)
if (!done) pwOrders.set(c.order, { status: 'waiting', email: String(s.email).toLowerCase(), serial: Number(c.serial), label: String(c.label || '').slice(0, 60), ret: c.ret, cb: c.cb, ts: Date.now() });
res.setHeader('Set-Cookie', gkCookie('iap.pwmint', t, PW_MINT_COOKIE_S));
const have = pwPassN(String(s.email).toLowerCase());
if (have > 0) {
const csrf = pwSign('pass:' + c.order + ':' + String(s.email).toLowerCase());
return gkPage(res, 200, 'Mint your warrior', '<p class="sub">PolyWarriors &middot; Mint to your wallet</p><h1>' + gkEsc(c.label || ('Warrior #' + c.serial)) + '</h1><div class="big">' + have + ' mint pass' + (have === 1 ? '' : 'es') + '</div>'
+ '<form method="post" action="/pw/mint/pass" onsubmit="var b=this.querySelector(\'button\');b.disabled=true;b.textContent=\'Minting… one moment\';b.style.opacity=.7"><input type="hidden" name="t" value="' + gkEsc(t) + '"><input type="hidden" name="csrf" value="' + csrf + '"><button class="btn" type="submit">Use 1 mint pass and mint</button></form>'
+ '<a class="alt" href="/pw/mint/leave">Cancel and go back</a><p class="fine">You earned these passes with your package purchases: one mint for every $5. The game pays the network fee.</p>');
}
return gkPage(res, 200, 'Mint your warrior', '<p class="sub">PolyWarriors &middot; Mint to your wallet</p><h1>' + gkEsc(c.label || ('Warrior #' + c.serial)) + '</h1><div class="big">Comes with a $5 package</div>'
+ '<p class="sub">Your first mint was free. After that, every $5 of new ad packages earns one mint: $5 mints this warrior, $10 earns 2 mints, $20 earns 4, and any extra mints stay on your account for next time. You keep every package\'s ad credits.</p>'
+ '<a class="btn" href="/my?from=polywarriors#buy">Buy a $5 package</a><a class="btn blue" href="/pw/mint/leave">Back to PolyWarriors</a>'
+ '<p class="fine">Buy while this mint is waiting and it mints to your wallet automatically. Credits you already have cannot be used for mints. The game pays the network fee.</p>');
}
if (!IS_PROD && p === '/api/dev/pw-purchase' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, { order: await pwMintOnEvent({ type: 'Purchase', priceCents: Number(b.cents) || 500, buyerId: 0, tx: '0x' + crypto.randomBytes(32).toString('hex'), ts: Date.now(), devEmail: b.email }) }); } // local tests only
if (p === '/pw/mint/pass' && req.method === 'POST') {
const f = await gkFormBody(req); const t = f.get('t') || ''; const r = pwOpen(t);
if (r.error) return gkPage(res, 400, 'Mint problem', '<h1>That mint did not work</h1><p class="sub">' + gkEsc(r.error) + '</p>');
const c = r.claims; const s = await auth.fromRequest(req); const e = s && s.email ? String(s.email).toLowerCase() : '';
if (!e || e !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Sign in', '<h1>Please sign in again</h1><a class="btn blue" href="/pw/mint?t=' + encodeURIComponent(t) + '">Continue</a>');
const want = pwSign('pass:' + c.order + ':' + e), got = String(f.get('csrf') || '');
if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return gkPage(res, 403, 'Mint problem', '<h1>That form expired</h1><a class="btn blue" href="/pw/mint?t=' + encodeURIComponent(t) + '">Try again</a>');
const o = pwOrders.get(c.order);
// the redirect goes out at once; the game is told in the background (and the GET below hands the member's own browser the
// receipt too, so the mint never waits on this callback). Marty's phone sat on this form on 2026-10-09 while the mint had
// already gone through.
if (o && o.status === 'waiting' && pwPassN(e) > 0) { pwPassAdd(e, -1, 'mint:' + c.order); pwOrders.set(c.order, Object.assign({}, o, { status: 'paid', tx: 'pass', cents: 500, paidAt: Date.now() })); pwDeliver(c.order).catch(() => {}); }
res.writeHead(303, Object.assign({ Location: '/pw/mint?t=' + encodeURIComponent(t), 'Cache-Control': 'no-store' }, pwOrders.get(c.order) && pwOrders.get(c.order).status === 'paid' ? { 'Set-Cookie': gkCookie('iap.pwmint', '', 0) } : {})); return res.end();
}
if (p === '/pw/mint/leave' && req.method === 'GET') { res.writeHead(302, { Location: PW_URL() + '/play', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.pwmint', '', 0), gkCookie('iap.return', '', 0)] }); return res.end(); } // the waiting order stays; a later package still completes the mint
if (p === '/pw/mint/dismiss' && req.method === 'POST') { res.writeHead(204, { 'Set-Cookie': [gkCookie('iap.pwmint', '', 0), gkCookie('iap.return', '', 0)] }); return res.end(); } // the dashboard bar's x
if (p === '/pw/mint/resume' && req.method === 'GET') { const t = parseCookies(req)['iap.pwmint']; res.writeHead(302, { Location: t ? '/pw/mint?t=' + encodeURIComponent(t) : PW_URL() + '/play', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); }
if (p === '/gk/shop/topup' && req.method === 'GET') { // the detour to Buy packages, remembered for the way back
const t = u.searchParams.get('t') || ''; if (gkOpen(t).error) { res.writeHead(302, { Location: '/my#buy' }); return res.end(); }
res.writeHead(302, { Location: '/my#buy', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.gkshop', t, 7200) }); return res.end();
}
if (p === '/gk/shop/resume' && req.method === 'GET') {
const t = parseCookies(req)['iap.gkshop']; res.writeHead(302, { Location: t ? '/gk/shop?t=' + encodeURIComponent(t) : GK_URL() + '/play?open=shop', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
if (p === '/gk/shop/confirm' && req.method === 'POST') {
const f = await gkFormBody(req); const t = f.get('t') || ''; const r = gkOpen(t);
if (r.error) return gkPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="sub">' + gkEsc(r.error) + '</p>');
const c = r.claims; const s = await auth.fromRequest(req);
if (!s || !s.email || String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Sign in', '<h1>Please sign in again</h1><a class="btn blue" href="/gk/shop?t=' + encodeURIComponent(t) + '">Continue</a>');
const want = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); const got = String(f.get('csrf') || '');
if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return gkPage(res, 403, 'Order problem', '<h1>That form expired</h1><a class="btn blue" href="/gk/shop?t=' + encodeURIComponent(t) + '">Try again</a>');
const prev = gkOrders.get(c.order);
if (prev && (prev.status === 'paid' || (prev.status === 'paying' && Date.now() - prev.ts < 60000))) { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); }
gkOrders.set(c.order, { status: 'paying', email: s.email, ts: Date.now() });
const { ids } = await myMemberIds(s);
const out = await ads.gamePurchase(s.email, ids, c.credits, 'Gem Kingdom: ' + c.crowns + ' Crowns', GK_URL());
if (out.error) { gkOrders.delete(c.order); if (out.error === 'short') { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); } return gkPage(res, 500, 'Order problem', '<h1>Something went wrong</h1><p class="sub">' + gkEsc(out.error) + '</p>'); }
gkOrders.set(c.order, { status: 'paid', email: s.email, campaignId: out.campaignId, paid: out.paid, ts: Date.now() });
console.log('gemkingdom crowns', s.email, c.crowns, 'for', c.credits, 'credits (' + out.paid + ' purchased), campaign', out.campaignId);
const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: String(c.email).toLowerCase(), crowns: Number(c.crowns), credits: Number(c.credits), paid: Number(out.paid), ref: out.campaignId }, 24 * 3600000);
gkCallback(c.cb, rc); // the server copy; the redirect below is the fast path
const ret = String(c.ret || '').startsWith(GK_URL() + '/') ? c.ret : GK_URL() + '/api/iap/receipt';
// a 200 page, not a 302: CSP form-action 'self' blocks a form POST from redirecting to another site (the page just sat there)
const back = gkEsc(ret + '?t=' + rc);
res.setHeader('Set-Cookie', gkCookie('iap.gkshop', '', 0));
return gkPage(res, 200, 'Crowns added', '<meta http-equiv="refresh" content="1;url=' + back + '"><p class="sub">Gem Kingdom · Crown Shop</p><h1>Paid!</h1><div class="big">+' + Number(c.crowns).toLocaleString('en-US') + ' Crowns</div><p class="sub">Taking you back to your kingdom...</p><a class="btn" href="' + back + '">Back to Gem Kingdom</a>');
}
// -- Spooky Doors hand-off (2026-10-02): sign the member across; the game verifies with SD_SSO_SECRET
// -- Spooky Doors promo card in Promo tools (2026-10-02): shown on the same season window as the Games card (admin preview
// before the start). The member's link is SD_URL/?ref=<username>, built in the page from their own username.
if (p === '/api/my/spookydoors/promo' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL);
const ss = seasonState(SD_SEASON, todayCT(), admin);
if (ss === 'hidden') return json(res, 200, { show: false });
return json(res, 200, { show: true, preview: ss === 'preview', base: SD_URL(), image: SD_URL() + '/og-spookydoors.jpg', season: { start: SD_SEASON.start, end: SD_SEASON.end } });
}
if (p === '/api/my/spookydoors' && req.method === 'GET') { gamestats.handoff('spookydoors');
const s = await auth.fromRequest(req);
// a newcomer from a Spooky Doors post carries the poster's ?ref through to /my, where the viral-link rule sets the sponsor
const sdRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (sdRef ? '?ref=' + encodeURIComponent(sdRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'spookydoors', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (SD_SECRET().length < 32) return json(res, 503, { error: 'Spooky Doors is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = sdMint({ kind: 'sso', memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || s.address || null,
sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }, 5 * 60000);
res.writeHead(302, { Location: SD_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- Road Agent hand-off (2026-10-07): sign the member across; the game verifies with RA_SSO_SECRET
if (p === '/api/my/roadagent' && req.method === 'GET') { gamestats.handoff('roadagent');
const s = await auth.fromRequest(req);
const raRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (raRef ? '?ref=' + encodeURIComponent(raRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'roadagent', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
if (RA_SECRET().length < 32) return json(res, 503, { error: 'Road Agent is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const tok = gMint(DOOR_GAMES().roadagent, { kind: 'sso', memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || s.address || null,
sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }, 5 * 60000);
res.writeHead(302, { Location: RA_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
// -- the Spooky Doors costume shop checkout: the Crown shop flow with a Halloween coat (confirm, spend, signed receipt back)
if (p === '/sd/shop' && req.method === 'GET') {
const t = u.searchParams.get('t') || ''; const r = sdOpen(t, 'That order has expired. Go back to Spooky Doors and open the costume shop again.');
if (r.error) return sdPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="warn">' + gkEsc(r.error) + '</p><a class="btn blue" href="' + SD_URL() + '/play?open=shop">Back to Spooky Doors</a>');
const c = r.claims; if (c.kind !== 'sd-buy' || !c.order || !c.item || !(Number(c.credits) > 0) || !c.email) return sdPage(res, 400, 'Order problem', '<h1>That is not a costume order</h1><a class="btn blue" href="' + SD_URL() + '/play?open=shop">Back to Spooky Doors</a>');
const label = String(c.label || c.item).slice(0, 60);
const done = sdOrders.get(c.order);
if (done && done.status === 'paid') { const rc = sdMint({ kind: 'sd-receipt', order: c.order, email: String(c.email).toLowerCase(), item: String(c.item), credits: Number(c.credits), paid: done.paid != null ? done.paid : Number(c.credits), ref: done.campaignId }, 24 * 3600000); const ret = sdIsGameUrl(c.ret) ? c.ret : SD_URL() + '/api/iap/receipt'; res.writeHead(302, { Location: ret + '?t=' + rc, 'Cache-Control': 'no-store' }); return res.end(); }
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.sdshop', t, 7200), gkCookie('iap.return', 'sdshop', 1800)] }); return res.end(); }
if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return sdPage(res, 403, 'Different account', '<h1>Different account</h1><p>This order was started by the Spooky Doors player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account in both places.</p><a class="btn blue" href="' + SD_URL() + '/play">Back to Spooky Doors</a>');
const { ids } = await myMemberIds(s); const bal = await ads.balances(ids, s.email);
const free = (bal.earned || 0) + (bal.credited || 0); const best = (bal.per || []).slice().sort((a, b) => b.avail - a.avail)[0] || { avail: 0 };
const can = free >= c.credits || best.avail >= c.credits; const usable = Math.max(free, best.avail);
const dollars = '$' + (c.credits / 100).toFixed(c.credits % 100 ? 2 : 0);
const head = '<p class="sub">Spooky Doors &middot; Costume shop</p><h1>' + gkEsc(label) + '</h1>'
+ '<div class="row"><span>Price</span><span>' + Number(c.credits).toLocaleString('en-US') + ' ad credits (' + dollars + ')</span></div>'
+ '<div class="row"><span>Your available credits</span><span>' + Number(bal.available || 0).toLocaleString('en-US') + '</span></div>';
if (can) {
const csrf = sdSign('csrf:' + c.order + ':' + String(s.email).toLowerCase());
return sdPage(res, 200, 'Confirm your costume', head + '<form method="post" action="/sd/shop/confirm"><input type="hidden" name="t" value="' + gkEsc(t) + '"><input type="hidden" name="csrf" value="' + csrf + '"><button class="btn" type="submit">Spend ' + Number(c.credits).toLocaleString('en-US') + ' credits</button></form>'
+ '<a class="alt" href="' + SD_URL() + '/play?open=shop">Cancel and go back</a><p class="fine">Costumes are game items for this Halloween season. They have no cash value and cannot be withdrawn. The credits come off your ad balance and show in your Credit activity.</p>');
}
const need = c.credits - usable;
return sdPage(res, 200, 'More credits needed', head + '<p class="warn">You need ' + need.toLocaleString('en-US') + ' more credits for this costume' + (bal.available >= c.credits ? ' (some of your credits are already budgeted to live campaigns or spread across positions)' : '') + '.</p>'
+ '<a class="btn" href="/sd/shop/topup?t=' + encodeURIComponent(t) + '">Buy a credit package</a><a class="btn blue" href="' + SD_URL() + '/play?open=shop">Back to the costume shop</a>'
+ '<p class="fine">A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.</p>');
}
if (p === '/sd/shop/topup' && req.method === 'GET') { // the detour to Buy packages, remembered for the way back
const t = u.searchParams.get('t') || ''; if (sdOpen(t).error) { res.writeHead(302, { Location: '/my#buy' }); return res.end(); }
res.writeHead(302, { Location: '/my#buy', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.sdshop', t, 7200) }); return res.end();
}
if (p === '/sd/shop/resume' && req.method === 'GET') {
const t = parseCookies(req)['iap.sdshop']; res.writeHead(302, { Location: t ? '/sd/shop?t=' + encodeURIComponent(t) : SD_URL() + '/play?open=shop', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
}
if (p === '/sd/shop/confirm' && req.method === 'POST') {
const f = await gkFormBody(req); const t = f.get('t') || ''; const r = sdOpen(t, 'That order has expired. Go back to Spooky Doors and open the costume shop again.');
if (r.error) return sdPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="warn">' + gkEsc(r.error) + '</p>');
const c = r.claims; if (c.kind !== 'sd-buy' || !c.order || !c.item || !(Number(c.credits) > 0)) return sdPage(res, 400, 'Order problem', '<h1>That is not a costume order</h1>');
const s = await auth.fromRequest(req);
if (!s || !s.email || String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return sdPage(res, 403, 'Sign in', '<h1>Please sign in again</h1><a class="btn blue" href="/sd/shop?t=' + encodeURIComponent(t) + '">Continue</a>');
const want = sdSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); const got = String(f.get('csrf') || '');
if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return sdPage(res, 403, 'Order problem', '<h1>That form expired</h1><a class="btn blue" href="/sd/shop?t=' + encodeURIComponent(t) + '">Try again</a>');
const prev = sdOrders.get(c.order);
if (prev && (prev.status === 'paid' || (prev.status === 'paying' && Date.now() - prev.ts < 60000))) { res.writeHead(302, { Location: '/sd/shop?t=' + encodeURIComponent(t) }); return res.end(); }
sdOrders.set(c.order, { status: 'paying', email: s.email, ts: Date.now() });
const label = String(c.label || c.item).slice(0, 60);
const { ids } = await myMemberIds(s);
const out = await ads.gamePurchase(s.email, ids, Number(c.credits), 'Spooky Doors: ' + label, SD_URL());
if (out.error) { sdOrders.delete(c.order); if (out.error === 'short') { res.writeHead(302, { Location: '/sd/shop?t=' + encodeURIComponent(t) }); return res.end(); } return sdPage(res, 500, 'Order problem', '<h1>Something went wrong</h1><p class="warn">' + gkEsc(out.error) + '</p>'); }
sdOrders.set(c.order, { status: 'paid', email: s.email, campaignId: out.campaignId, paid: out.paid, ts: Date.now() });
console.log('spookydoors costume', s.email, c.item, 'for', c.credits, 'credits, campaign', out.campaignId);
const rc = sdMint({ kind: 'sd-receipt', order: c.order, email: String(c.email).toLowerCase(), item: String(c.item), credits: Number(c.credits), paid: Number(out.paid), ref: out.campaignId }, 24 * 3600000);
sdShopCallback(c.cb, rc); // the server copy; the redirect below is the fast path
const ret = sdIsGameUrl(c.ret) ? c.ret : SD_URL() + '/api/iap/receipt';
// a 200 page, not a 302: CSP form-action 'self' blocks a form POST from redirecting to another site
const back = gkEsc(ret + '?t=' + rc);
res.setHeader('Set-Cookie', gkCookie('iap.sdshop', '', 0));
return sdPage(res, 200, 'Costume ready', '<meta http-equiv="refresh" content="1;url=' + back + '"><p class="sub">Spooky Doors &middot; Costume shop</p><h1>Paid!</h1><div class="big">' + gkEsc(label) + '</div><p>Taking you back to the street...</p><a class="btn" href="' + back + '">Back to Spooky Doors</a>');
}
// -- PassiveDrip card on the Earn tab (Marty, 2026-10-01: "It's an earning site", not a game). Members see it when
// site config passivedripLive is 'on'; until then only the admin sees it, marked preview.
if (p === '/api/my/passivedrip/card' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const live = String(siteConfig().passivedripLive || 'off') === 'on';
const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL);
if ((!live && !admin) || PD_SECRET().length < 32) return json(res, 200, { show: false });
const acct = await accounts.byEmail(s.email); const memberId = (acct && acct.memberId) || s.memberId || 0;
let progress = null; try { progress = await pdProgress(memberId, s.email); } catch (e) {}
return json(res, 200, { show: true, preview: !live, line: progress && progress.line || null });
}
// -- PassiveDrip hand-off (2026-10-01): sign the member across; PassiveDrip verifies with the shared secret.
// wallet = the signature-verified main wallet (accounts.linkWallet runs only after /api/auth/verify), offered there, never imposed.
if (p === '/api/my/passivedrip' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': 'iap.return=passivedrip; Path=/; SameSite=Lax; Max-Age=1800' + (IS_PROD ? '; Secure' : ''), 'Cache-Control': 'no-store' }); return res.end(); } // sign in first, then straight across
if (PD_SECRET().length < 32) return json(res, 503, { error: 'PassiveDrip is not connected yet.' });
const acct = await accounts.byEmail(s.email);
const memberId = (acct && acct.memberId) || s.memberId || 0;
let sponsorEmail = null; try { const up = await uplineSlides(s.email, 1); sponsorEmail = (up[0] && up[0].email) || null; } catch (e) {}
const tok = pdMint({ memberId: Number(memberId), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorEmail });
res.writeHead(302, { Location: PD_URL() + '/iap-signin.php?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end();
}
// -- Drip Runner refuel: a real verified visit (advertiser charged as usual); the player gets fuel, not credits
if (p === '/api/refuel/open' && req.method === 'GET') {
// Drip Runner refuels and Gem Kingdom continues (2026-10-03) share this flow; the token's secret says which game
let r = drOpen(u.searchParams.get('t')), game = 'driprunner';
if (r.error) { const g = gkOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'gemkingdom') { r = g; game = 'gemkingdom'; } }
if (r.error) { const g = seekOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'seek') { r = g; game = 'seek'; } }
if (r.error) { const g = swOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'spellwheel') { r = g; game = 'spellwheel'; } }
if (r.error) { const g = pbOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'polybreak') { r = g; game = 'polybreak'; } }
if (r.error) { const g = pmOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'polminer') { r = g; game = 'polminer'; } }
if (r.error) { const g = wwOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'warpwares') { r = g; game = 'warpwares'; } }
if (r.error) return json(res, 400, { error: r.error });
const c = r.claims; if (c.kind !== 'refuel' || !c.nonce || !c.email || !c.ret) return json(res, 400, { error: 'That is not a refuel link.' });
if (game === 'gemkingdom' && !String(c.ret).startsWith(GK_URL() + '/')) return json(res, 400, { error: 'That is not a Gem Kingdom link.' });
if (game === 'seek' && !seekIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a ClutterHunt link.' });
if (game === 'spellwheel' && !swIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a SpellWheel link.' });
if (game === 'polybreak' && !pbIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a PolyBreak link.' });
if (game === 'polminer' && !pmIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a POL Miner link.' });
if (game === 'warpwares' && !wwIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a Warp & Wares link.' });
const vkind = game === 'warpwares' ? 'dock' : 'refuel'; // a Warp & Wares sponsor dock has its own visit kind and daily cap (ads.js VISIT_KINDS)
const G = game === 'warpwares' ? { game: 'Warp & Wares', label: 'sponsor dock' } : game === 'polminer' ? { game: 'POL Miner', label: 'supply crate' } : game === 'polybreak' ? { game: 'PolyBreak', label: 'one more paddle' } : game === 'gemkingdom' ? { game: 'Gem Kingdom', label: 'continue' } : game === 'seek' ? { game: 'ClutterHunt', label: 'hint' } : game === 'spellwheel' ? { game: 'SpellWheel', label: 'hint' } : { game: 'Drip Runner', label: 'refuel' };
for (const [n, v] of refuelTokens) if (v.ts + 30 * 60000 < Date.now()) refuelTokens.delete(n);
let t = refuelTokens.get(c.nonce);
if (t && t.done) return json(res, 200, Object.assign({ done: true, ret: t.doneRet || t.ret }, G));
if (!t) {
const email = String(c.email).toLowerCase();
const status = await ads.visitStatus(email, vkind); // refuels (and docks) have their own daily allowance
if (status.count >= status.cap) return json(res, 200, Object.assign({ none: true, why: 'cap', ret: c.ret }, G));
// 2026-10-28 (Marty): a sponsor never seen first, then one seen longest ago after the cooldown (doorRepeatDays), then a
// member video, then a house sponsor (one of Marty's programs, never the game the player is in), so the visit is never empty
const ad = await ads.serveVisit(email, viewerGeo(req), { kind: vkind });
if (ad) t = { kind: 'visit', email, memberId: Number(c.memberId), id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false };
else { // every visit pack already visited: a member video ad instead (2026-09-30)
const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req)));
if (!v) {
const h = await doorHousePick(email, c.username, G.game);
if (!h) return json(res, 200, Object.assign({ none: true, why: 'empty', ret: c.ret }, G));
t = { kind: 'house', email, memberId: Number(c.memberId), id: 0, program: h.name, title: h.title, target: h.target, ts: Date.now(), ret: c.ret, challenge: null, done: false };
}
else t = { kind: 'video', email, memberId: Number(c.memberId), id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false };
}
t.game = game; t.cb = c.cb || null;
refuelTokens.set(c.nonce, t);
}
if (t.kind === 'video') return json(res, 200, Object.assign({ mode: 'video', title: t.title, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }, G));
return json(res, 200, Object.assign({ mode: 'visit', house: t.kind === 'house' || undefined, title: t.title, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }, G));
}
if (p === '/api/refuel/challenge' && req.method === 'GET') {
const t = refuelTokens.get(String(u.searchParams.get('n') || ''));
if (!t || t.done) return json(res, 400, { error: 'That refuel is no longer open.' });
const dwellMs = (t.kind === 'video' ? t.secs : (ads.rates().visitDwellSeconds || 8)) * 1000; const age = Date.now() - t.ts;
if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) });
const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); const answer = Math.floor(Math.random() * pick.length);
t.challenge = { answer };
return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) });
}
if (p === '/api/refuel/done' && req.method === 'POST') {
const b = await readBody(req); const nonce = String(b.n || ''); const t = refuelTokens.get(nonce);
if (!t || t.done) return json(res, 400, { error: 'That refuel is no longer open.' });
if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true });
if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; return json(res, 400, { error: 'Wrong pick.', retry: true }); }
let credits;
if (t.kind === 'video') {
const st = await ads.visitStatus(t.email, t.game === 'warpwares' ? 'dock' : 'refuel'); if (st.count >= st.cap) return json(res, 400, { error: t.game === 'warpwares' ? 'That is today\u2019s sponsor docks. More at midnight Central.' : 'That is today\u2019s refuels. More at midnight Central.' });
if (!(await ads.markRefuelVideo(t.email, t.id, t.game === 'warpwares' ? 'dock' : undefined))) return json(res, 400, { error: 'You already refuelled on this video. Go back and try again for another.' });
const tier = await ads.chargeVideoView(t.id); // the advertiser is charged one view, as on the Watch tab
if (!tier) return json(res, 400, { error: 'That video just ran out of budget. Go back and try again.' });
await ads.markVideoSeen(t.email, t.id); credits = tier.cost;
} else if (t.kind === 'house') { // a house sponsor: no advertiser, no pool income, but it is one of the day's refuels
const r = await ads.markHouseVisit(t.email, t.game === 'warpwares' ? 'dock' : 'refuel');
if (r.error) return json(res, 400, { error: r.error });
credits = 0;
} else {
const r = await ads.completeVisit(t.email, t.id, { reward: false, kind: t.game === 'warpwares' ? 'dock' : undefined, note: t.game === 'warpwares' ? 'Warp & Wares sponsor dock' : t.game === 'polminer' ? 'POL Miner supply crate' : t.game === 'polybreak' ? 'PolyBreak paddle' : t.game === 'gemkingdom' ? 'Gem Kingdom continue' : t.game === 'seek' ? 'ClutterHunt hint' : t.game === 'spellwheel' ? 'SpellWheel hint' : 'Drip Runner refuel' });
if (r.error) return json(res, 400, r);
credits = ads.rates().visitCostPerVisit || 3;
{ const camp = await ads.campaignById(t.id).catch(() => null); if (camp && camp.house) credits = 0; } // a house ad costs nobody anything: no POL pool income (2026-10-03)
}
t.done = true;
if (t.game === 'warpwares') { // Warp & Wares sponsor dock: signed receipt to the game's callback and on the ret page; the game pays bonus turns, never POL
const receipt = wwMint({ kind: 'ww-dock', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000);
const posted = await wwCallback(t.cb, receipt);
t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'Warp & Wares', label: 'sponsor dock' });
}
if (t.game === 'polminer') { // POL Miner supply crate: signed receipt to the game's callback and on the ret page (the crate is a gameplay boost, never POL)
const receipt = pmMint({ kind: 'pm-crate', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000);
const posted = await pmCallback(t.cb, receipt);
t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'POL Miner', label: 'supply crate' });
}
if (t.game === 'polybreak') { // PolyBreak one more paddle: signed receipt to the game's callback and on the ret page
const receipt = pbMint({ kind: 'pb-paddle', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000);
const posted = await pbCallback(t.cb, receipt);
t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'PolyBreak', label: 'one more paddle' });
}
if (t.game === 'spellwheel') { // SpellWheel hint: signed receipt to the game's callback and on the ret page
const receipt = swMint({ kind: 'sw-hint', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000);
const posted = await swCallback(t.cb, receipt);
t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'SpellWheel', label: 'hint' });
}
if (t.game === 'seek') { // ClutterHunt hint: signed receipt to the game's callback and on the ret page
const receipt = seekMint({ kind: 'seek-hint', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000);
const posted = await seekCallback(t.cb, receipt);
t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'ClutterHunt', label: 'hint' });
}
if (t.game === 'gemkingdom') { // signed receipt to the game's callback (server copy) and on the ret page (fast path)
const receipt = gkMint({ kind: 'gk-continue', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000);
const posted = await gkCallback(t.cb || (GK_URL() + '/api/continue/callback'), receipt);
t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'Gem Kingdom', label: 'continue' });
}
const posted = await drCallback({ nonce, memberId: t.memberId, campaignId: t.id, credits });
const receipt = drMint({ kind: 'refuel-receipt', nonce, campaignId: t.id, credits }, 15 * 60000);
t.doneRet = t.ret + '&ok=1&r=' + encodeURIComponent(receipt);
return json(res, 200, { ok: true, posted, ret: t.doneRet });
}
// -- Spooky Doors door: a real verified visit of kind 'door' (own daily cap, advertiser charged as usual); the player gets candy, not credits
if (p === '/api/door/open' && req.method === 'GET') {
const r = doorOpen(u.searchParams.get('t')); if (r.error) return json(res, 400, { error: r.error });
const c = r.claims; if (c.kind !== 'door' || !c.nonce || !c.email || !gameUrlOk(r.game, c.ret)) return json(res, 400, { error: 'That is not a door link.' });
for (const [n, v] of doorTokens) if (v.ts + 30 * 60000 < Date.now()) doorTokens.delete(n);
let t = doorTokens.get(c.nonce);
if (t && t.done) return json(res, 200, { done: true, ret: t.doneRet || t.ret });
const email = String(c.email).toLowerCase();
const status = await ads.visitStatus(email, 'door'); // doors have their own daily allowance
if (!t) {
if (status.count >= status.cap) return json(res, 200, { none: true, why: 'cap', ret: sdJoin(c.ret, 'cap=1') });
// door packs + Golden Doors first (golden, then doors; once per player per Central day), then the existing chain
const pack = await ads.serveDoorPack(email, viewerGeo(req));
const ad = pack || await ads.serveVisit(email, viewerGeo(req), { kind: 'door' }); // doors may repeat a campaign after doorRepeatDays
if (ad) t = { kind: 'visit', game: r.game, email, memberId: Number(c.memberId) || 0, id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false,
credits: pack ? pack.credits : (ads.rates().visitCostPerVisit || 3), golden: !!(pack && pack.golden), bonus: (pack && pack.golden) ? sdGoldenBonus() : 0 };
else { // every visit pack already visited: a member video ad instead, one door per video per person
const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req)));
if (v) t = { kind: 'video', game: r.game, email, memberId: Number(c.memberId) || 0, id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false };
else { // nothing left on the street: a house ad (one of Marty's programs, a smaller treat); none=1 only when the list is empty
const h = await doorHousePick(email, c.username);
if (!h) return json(res, 200, { none: true, why: 'empty', ret: sdJoin(c.ret, 'none=1') });
t = { kind: 'house', game: r.game, email, memberId: Number(c.memberId) || 0, id: 0, program: h.name, title: h.title, target: h.target, ts: Date.now(), ret: c.ret, challenge: null, done: false };
}
}
t.host = t.kind === 'house' ? null : await sdHost(t.id);
doorTokens.set(c.nonce, t);
}
const doors = { used: status.count, cap: status.cap, game: t.game || 'spookydoors', gameName: DOOR_GAMES()[t.game || 'spookydoors'].name };
if (t.kind === 'video') return json(res, 200, { mode: 'video', title: t.title, host: t.host || null, doors, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) });
if (t.kind === 'house') return json(res, 200, { mode: 'visit', house: true, program: t.program, title: t.title, host: null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) });
return json(res, 200, Object.assign({ mode: 'visit', title: t.title, host: t.host || null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000), credits: t.credits || (ads.rates().visitCostPerVisit || 3) }, t.golden ? { golden: true, bonus: t.bonus } : {}));
}
if (p === '/api/door/challenge' && req.method === 'GET') {
const n = String(u.searchParams.get('n') || ''); const t = doorTokens.get(n);
if (!t || t.done) return json(res, 400, { error: 'That door is no longer open.' });
const dwellMs = (t.kind === 'video' ? t.secs : (ads.rates().visitDwellSeconds || 8)) * 1000; const age = Date.now() - t.ts;
if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) });
const pick = DOOR_CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); const answer = Math.floor(Math.random() * pick.length);
t.challenge = { answer }; doorTokens.set(n, t);
return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) });
}
if (p === '/api/door/done' && req.method === 'POST') {
const b = await readBody(req); const nonce = String(b.n || ''); const t = doorTokens.get(nonce);
if (!t || t.done) return json(res, 400, { error: 'That door is no longer open.' });
if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true });
if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; doorTokens.set(nonce, t); return json(res, 400, { error: 'Wrong pick.', retry: true }); }
const st = await ads.visitStatus(t.email, 'door');
if (st.count >= st.cap) return json(res, 400, { error: 'That is today\u2019s doors. More at midnight Central.', cap: true, ret: sdJoin(t.ret, 'cap=1') });
let credits;
if (t.kind === 'video') {
if (!(await ads.markRefuelVideo(t.email, t.id, 'door'))) return json(res, 400, { error: 'You already knocked on this video. Go back and try another door.' });
const tier = await ads.chargeVideoView(t.id); // the advertiser is charged one view, as on the Watch tab
if (!tier) return json(res, 400, { error: 'That video just ran out of budget. Go back and try another door.' });
await ads.markVideoSeen(t.email, t.id); credits = tier.cost;
} else if (t.kind === 'house') { // no advertiser and no campaign imps, but it uses one of today's doors
const r = await ads.markHouseDoor(t.email);
if (r.error) return json(res, 400, { error: r.error, cap: true, ret: sdJoin(t.ret, 'cap=1') });
credits = 0;
} else {
const r = await ads.completeVisit(t.email, t.id, { reward: false, kind: 'door', note: 'Spooky Doors door' });
if (r.error) return json(res, 400, r);
credits = r.unit || ads.rates().visitCostPerVisit || 3; // the per-door price actually charged (door pack 4, Golden Door 6, a visit pack 3)
if (t.golden && r.golden === false) t.golden = false; // the season closed between open and done: an ordinary door
}
t.done = true;
const host = t.host || null;
const house = t.kind === 'house' ? { house: true, program: t.program } : {}; // a house ad: credits 0, host null, campaignId 0
const gold = (t.kind === 'visit' && t.golden) ? { golden: true, bonus: t.bonus } : {}; // a Golden Door: the game adds `bonus` candy
const gk = t.game || 'spookydoors';
const posted = await gameCallback(gk, Object.assign({ nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold));
const receipt = gMint(DOOR_GAMES()[gk], Object.assign({ kind: 'door-receipt', nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold), 24 * 3600000);
t.doneRet = sdJoin(t.ret, 'ok=1&r=' + encodeURIComponent(receipt));
doorTokens.set(nonce, t);
return json(res, 200, Object.assign({ ok: true, posted, host, credits, ret: t.doneRet }, house, gold));
}
// -- cross-promo strip (2026-10-03): the list every game reads, and the counted hop between games
// -- the public games page (2026-10-10, Marty: a page to send people): every game, open ones first, dated ones after
// featured PolyWarriors listings for the games page, fetched server-side (the page CSP allows no cross-origin calls), cached 60 s
if (p === '/api/public/pw-featured' && req.method === 'GET') {
const now = Date.now(); if (!global.__pwFeat || now - global.__pwFeat.at > 60000) { try { const r = await fetch(String(process.env.PW_URL || 'https://www.polywarriors.com').replace(/\/+$/, '') + '/api/public/featured', { signal: AbortSignal.timeout(6000) }); global.__pwFeat = { at: now, body: r.ok ? await r.json() : { featured: [] } }; } catch (e) { global.__pwFeat = { at: now, body: { featured: [] } }; } }
return json(res, 200, global.__pwFeat.body, { 'Cache-Control': 'public, max-age=60' });
}
if (p === '/api/public/games/all' && req.method === 'GET') {
const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean));
const day = todayCT(), S = STRIP(); const lbl = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); };
const out = [];
for (const g of GAMES()) {
if (g.season && day >= g.season.end) continue; // a finished season is gone
// a seasonal game shows its 'Opens' date only once it is in gamesLive (Turkey Drop's rule, 2026-10-28; Warp & Wares the same)
const soon = !!(g.soon && day < g.soon.opens), preSeason = !!(g.season && day < g.season.start && live.has(g.slug));
const isLive = !soon && !(g.season && day < g.season.start) && live.has(g.slug);
if (!isLive && !soon && !preSeason) continue; // not live and no date: not announced yet
out.push({ slug: g.slug, name: g.name, tag: g.tag, blurb: g.blurb, pays: g.pays, art: /^https?:/.test(g.art) ? g.art : 'https://instantadpay.com' + g.art, artPos: g.artPos || 'center', live: isLive, video: isLive && g.video ? g.video : null,
opens: soon ? g.soon.label : preSeason ? 'Opens ' + lbl(g.season.start) : null, season: g.season && isLive ? { ends: lbl(g.season.end, true) } : null, open: S[g.slug] ? S[g.slug].open : null, host: S[g.slug] ? S[g.slug].host : null });
}
return json(res, 200, { games: out }, { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=300' });
}
// Today's POL price in US dollars for the member pages (Marty, 2026-10-22, Brian's ask): the same rate the contract prices
// packages with (its Chainlink POL/USD feed), cached 5 minutes on the server, so browsers never call a price service.
if (p === '/api/public/polusd' && req.method === 'GET') { let usd = 0; try { usd = await polUsdLive(); } catch (e) {} return json(res, 200, { usd, at: polUsdCache.at || Date.now() }, { 'Cache-Control': 'public, max-age=60' }); }
if (p === '/api/public/games' && req.method === 'GET') return json(res, 200, { games: stripGames() }, { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=300' });
{ const mg = /^\/g\/([a-z]{3,20})$/.exec(p); if (mg && req.method === 'GET') {
const g = GAMES().find(x => x.slug === mg[1]); const S = STRIP()[mg[1]];
if (!g || !S) { res.writeHead(302, { Location: '/my#games', 'Cache-Control': 'no-store' }); return res.end(); }
const from = String(u.searchParams.get('from') || '').toLowerCase().replace(/[^a-z]/g, '').slice(0, 20); const src = STRIP()[from];
traffic.hit('/g/' + g.slug, req.headers.referer || (src ? 'https://' + src.host + '/' : ''), req.headers['user-agent']); // Traffic tab: host = sending game, path g/<slug>
const s = await auth.fromRequest(req);
res.writeHead(302, { Location: (s && s.email) ? g.play : S.open, 'Cache-Control': 'no-store' }); return res.end(); // signed in here: straight into the game, signed in
} }
// -- Game Pass + account-wide POL caps (2026-10-16, docs/GAME-PASS.md section 3a) --------------------------------------------
// Partner auth: each game signs with the shared secret it already holds (its *_SSO_SECRET), 10-minute window.
// GET ...?game=<slug>&m=<memberId>&e=<email>&ts=<ms>&sig=hex sig = HMAC-SHA256(secret, 'player:' + who + ':' + ts), who = memberId when > 0, else the lowercased email
// POST JSON body with `game`, headers X-Game-Ts (ms) + X-Game-Sig sig = HMAC-SHA256(secret, ts + '\n' + rawBody)
// The pass is per ACCOUNT (email): a linked position's member id resolves to the owner's account. Games fail closed.
if (p === '/api/partner/player' && req.method === 'GET') {
const game = String(u.searchParams.get('game') || '').toLowerCase(); const chk = gpPartnerCheck(game);
if (chk.error) return json(res, chk.code, { error: chk.error });
const m = Number(u.searchParams.get('m')) || 0, e = String(u.searchParams.get('e') || '').trim().toLowerCase(), ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || '');
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' });
if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:' + (m > 0 ? String(m) : e) + ':' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' });
const r = await gpResolve(m, e); if (!r) return json(res, 404, { error: 'no such member', pass: { active: false, until: null, tier: null, tiers: { weekly: null, explorer: null, champion: null } } });
const now = gpDevNow(u.searchParams.get('devDay'));
return json(res, 200, { ok: true, memberId: r.memberId, username: r.acct.username || null, wallet: r.acct.address || null, suspended: fraud.isSuspended(r.email),
pass: gamepass.flag(r.email, now), caps: gamepass.capsFor(r.email, now, game), gamePassEnabled: gamepass.cfg().enabled });
}
if ((p === '/api/partner/polgrant' || p === '/api/partner/polgrant/void' || p === '/api/partner/tournament/paid') && req.method === 'POST') {
let raw; try { raw = (await readRaw(req, 16384)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
const game = String(b.game || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error });
const ts = String(req.headers['x-game-ts'] || ''), sig = String(req.headers['x-game-sig'] || '');
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' });
if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update(ts + '\n' + raw).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' });
if (p === '/api/partner/tournament/paid') { const r = gamepass.markPaid(b.week, b.place, b.tx, game); if (!r.error) console.log('gamepass prize paid', b.week, '#' + b.place, 'by', game, String(b.tx || '').slice(0, 14)); return json(res, r.error ? 400 : 200, r); }
const r = await gpResolve(b.memberId, b.email); if (!r) return json(res, 404, { error: 'no such member' });
const now = gpDevNow(b.devDay);
if (p.endsWith('/void')) return json(res, 200, gamepass.voidGrant({ game, ref: b.ref }));
if (fraud.isSuspended(r.email)) return json(res, 200, { allowed: 0, deferred: 0, pass: false, day: gamepass.dayKey(now), suspended: true }); // nothing is recorded: a cleared account replays the ref later
const out = gamepass.grant({ email: r.email, game, kind: b.kind, pol: b.pol, ref: b.ref, now });
if (!out.error && out.capHit && !out.repeat) console.log('gamepass cap hit', out.capHit, game, r.email.replace(/^(.).*(@.*)$/, '$1***$2'), out.pass ? 'pass' : 'free', out.enforced ? 'enforced' : 'recorded');
return json(res, out.error ? 400 : 200, out);
}
if (p === '/api/partner/tournament/pending' && req.method === 'GET') { // prize rows the games still have to pay out in POL (admin session may read too)
if (!isAdmin(req)) {
const game = String(u.searchParams.get('game') || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error });
const ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || '');
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' });
if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:tournament:' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' });
}
const rows = gamepass.pending();
return json(res, 200, { ok: true, rows, pending: rows }); // `rows` is what the games' polgrant.js tournamentPending() reads; `pending` is the admin pane's name
}
if (p === '/api/my/gamepass' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
// 2026-10-25 (Marty): the member card shows every account exactly what a member sees, the admin's included; tier testing lives in Admin > Game Pass
return json(res, 200, gamepass.view(s.email, gpDevNow(u.searchParams.get('devDay'))));
}
if (p === '/api/my/gamepass/buy' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (fraud.isSuspended(s.email)) return json(res, 403, { error: 'This account is suspended.' });
const b = await readBody(req);
// 2026-10-22 (Marty): no pass is ever bought with credits. Buy only opens a waiting order; a FRESH package purchase of at least the
// tier price, by one of this member's own positions, fulfils it (gamepass.onEvent), so the sponsor and team are paid as usual.
// tier: weekly (missing) | explorer | champion | sovereign | legend; every tier above weekly is refused unless sovTiers is on, for every
// account (2026-10-25: the admin tests hidden tiers from Admin > Game Pass, POST /api/admin/gamepass/test-buy, not from the member card)
const r = gamepass.buy(s.email, gpDevNow(b.devDay), b.tier);
return json(res, r.error ? 400 : 200, r);
}
// Admin > Game Pass tier test (2026-10-25, Marty): every tier as members will see it, with the admin's OWN account's state, and a
// test buy of a tier that is not on sale yet (opens the same waiting order a member gets; a fresh package on /my fulfils it).
// Always the signed-in admin's own account (the bearer password falls back to ADMIN_EMAIL); never another member's.
if (p.startsWith('/api/admin/gamepass/') && ['/api/admin/gamepass/preview', '/api/admin/gamepass/test-buy', '/api/admin/gamepass/test-cancel', '/api/admin/gamepass/test-comp'].includes(p)) {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const as = adminFromRequest(req); const me = String((as && as.email) || ADMIN_EMAIL || '').trim().toLowerCase();
if (!me) return json(res, 400, { error: 'No admin account email (ADMIN_EMAIL) is set.' });
if (p === '/api/admin/gamepass/preview' && req.method === 'GET') return json(res, 200, Object.assign({ email: me, test: true }, gamepass.view(me, gpDevNow(u.searchParams.get('devDay')), { preview: true })));
if (req.method === 'POST') {
const b = await readBody(req); const tier = String(b.tier || 'weekly').toLowerCase(); if (!gamepass.TIERS.includes(tier)) return json(res, 400, { error: 'unknown tier' });
if (p === '/api/admin/gamepass/test-buy') { const r = gamepass.buy(me, gpDevNow(b.devDay), tier, { preview: true }); if (!r.error) console.log('gamepass admin test order', tier, me); return json(res, r.error ? 400 : 200, Object.assign({ email: me, test: true }, r)); }
if (p === '/api/admin/gamepass/test-cancel') { const r = gamepass.cancelOrder(me, tier); if (r.order) console.log('gamepass admin test order cancelled', tier, me); return json(res, 200, Object.assign({ email: me }, r)); }
if (p === '/api/admin/gamepass/test-comp') { const r = gamepass.comp(me, 'admin tier test', tier); console.log('gamepass admin test comp', tier, me); return json(res, 200, Object.assign({ ok: true, email: me, test: true }, r)); }
}
}
if (!IS_PROD && p === '/api/dev/gamepass-purchase' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, { order: await gamepass.onEvent({ type: 'Purchase', priceCents: Number(b.cents) || 500, buyerId: 0, tx: /^0x[0-9a-f]{64}$/.test(String(b.tx || '')) ? b.tx : '0x' + crypto.randomBytes(32).toString('hex'), ts: Date.now(), devEmail: b.email, devMinedAt: Number(b.minedAt) || 0, devNow: Number(b.now) || 0 }) }); } // local tests only (minedAt fakes the block time, now the fulfilment time, tx replays a hash)
if (p === '/api/admin/gamepass/stats' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, gamepass.adminStats()); }
if (p === '/api/admin/gamepass/comp' && req.method === 'POST') { // support: give an account a pass week without a purchase
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'email required' });
const tier = String(b.tier || 'weekly').toLowerCase(); if (!gamepass.TIERS.includes(tier)) return json(res, 400, { error: 'unknown tier' });
const r = gamepass.comp(e, String(b.why || 'support').slice(0, 80), tier); console.log('gamepass comp', tier, e, b.why || ''); return json(res, 200, Object.assign({ ok: true, email: e }, r));
}
if (p === '/api/admin/gamepass/revoke' && req.method === 'POST') { // support refund only: ends one tier now (never automatic); the record keeps what it was
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'email required' });
const r = gamepass.revoke(e, String(b.tier || '').toLowerCase(), String(b.why || 'support').slice(0, 80)); if (!r.error) console.log('gamepass revoke', r.tier, e, b.why || '');
return json(res, r.error ? 400 : 200, Object.assign({ email: e }, r));
}
if (p === '/api/admin/gamepass/tournament/run' && req.method === 'POST') { // settle a week by hand (the Monday job normally does this)
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req);
const at = /^\d{4}-\d{2}-\d{2}$/.test(String(b.week || '')) ? Date.parse(b.week + 'T17:00:00Z') : Date.now() - 7 * 86400000;
const r = await gamepass.runTournament(at, { force: !!b.force }); return json(res, r.error ? 400 : 200, r);
}
// -- Games hub (2026-10-01): the registry is here, the live list is site config (gamesLive)
if (p === '/api/my/games' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean));
const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL);
const acct = await accounts.byEmail(s.email); const memberId = (acct && acct.memberId) || s.memberId || 0;
const out = []; const day = todayCT();
const dayLabel = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); };
for (const g of GAMES()) {
// a seasonal game (2026-10-02) shows only while today (Central) is in [start, end); before start the admin sees a preview, after end nobody
// testers (env GAMES_TESTERS, usernames or emails; Marty 2026-10-07) get the Play button on a coming-soon game before it opens
const tester = isGameTester(acct, s.email);
if (g.soon && day < g.soon.opens && !tester) { out.push(Object.assign({}, g, { live: false, preview: false, soon: g.soon.label, play: null })); continue; } // coming soon: shown to all, not playable
if (g.soon && day < g.soon.opens && tester) { out.push(Object.assign({}, g, { live: false, preview: true, previewNote: 'testing · ' + g.soon.label.toLowerCase(), soon: null })); continue; } // soon cleared: the client prints a soon card's label where the Play button goes
const ss = seasonState(g.season, day, admin); if (ss === 'hidden') continue;
const seasonPreview = ss === 'preview';
const isLive = live.has(g.slug); if (!isLive && !admin && !tester) continue;
// soon: null once the opening day arrives: the registry's {opens,label} object must not reach the client, which prints x.soon
// as the button label (SpellWheel showed "[object Object]" on the morning of 2026-10-10)
const card = Object.assign({}, g, { live: isLive, preview: !isLive || seasonPreview, soon: null });
if (g.season) { card.season = Object.assign({}, g.season, { opens: dayLabel(g.season.start), ends: dayLabel(g.season.end, true) }); if (seasonPreview) card.previewNote = 'preview, opens ' + card.season.opens; }
if (g.progress && (memberId || g.slug === 'passivedrip')) { try { card.progress = await g.progress(memberId, s.email); } catch (e) {} }
out.push(card);
}
return json(res, 200, { games: out.map(g => { const c = Object.assign({}, g); if (typeof c.progress === 'function') delete c.progress; return c; }) });
}
if (p === '/api/my/claim' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await ads.claimDaily(s.email);
if (!r.error) { try { const paid = await payPromo(s.email, todayCT()); if (paid.length) r.promo = paid; } catch (e) { console.error('promo drip', e.message); } }
return json(res, r.error ? 400 : 200, r);
}
// -- downline lineage: 3 levels, usernames+IDs; email only for directs
if (p === '/api/my/line' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const levels = await accounts.downline(s.email, 3);
// what each person has paid THIS member so far: sum of TierPaid events where
// this member is the recipient and that person is the buyer (all indexed events)
// ...counting payouts to every position this account owns (main id + linked positions)
const myId = await auth.refreshMemberId(s);
const own = (await accounts.positions(s.email)).filter(p => p.memberId);
const myIds = new Set([myId, ...own.map(p => p.memberId)].filter(Boolean));
const earnedBy = {};
const qualified = new Set(); // members the contract counted as this account's qualifying buyers ($20+)
if (myIds.size) {
for (const ev of chain.recentEvents(1e9)) {
if (ev.type === 'TierPaid' && myIds.has(ev.recipientId) && ev.buyerId)
earnedBy[ev.buyerId] = (BigInt(earnedBy[ev.buyerId] || '0') + BigInt(ev.amountWei)).toString();
if (ev.type === 'BuyerCounted' && myIds.has(ev.sponsorId) && ev.newBuyerId) qualified.add(ev.newBuyerId);
}
}
// who sponsored each person (Marty, 2026-09-14): resolve sponsorRef tokens (username, share code or member id) against the line itself
const meAcct = await accounts.byEmail(s.email); const byTok = {};
const label = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member');
for (const a of [meAcct, ...levels.flatMap(L => L.members)].filter(Boolean)) { const n = label(a); if (a.username) byTok[String(a.username).toLowerCase()] = n; if (a.code) byTok[String(a.code).toLowerCase()] = n; if (a.memberId) byTok[String(a.memberId)] = n; }
const sponsorOf = m => { const t = String(m.sponsorRef || '').toLowerCase(); if (!t) return null; if (meAcct && (t === String(meAcct.username || '').toLowerCase() || t === String(meAcct.code || '').toLowerCase() || t === String(meAcct.memberId || ''))) return 'you'; return byTok[t] || ('@' + t); };
// a member's linked positions are theirs too: a qualifying buy from one of them lights their chip
const posIds = {}; for (const m of levels.flatMap(L => L.members)) { try { posIds[m.email] = (await accounts.positions(m.email)).map(p => p.memberId).filter(Boolean); } catch (e) { posIds[m.email] = []; } }
const idsOf = m => [m.memberId, ...(posIds[m.email] || [])].filter(Boolean);
// Clinton's ask (2026-09-14): on levels 2 and 3 show who has made their $20+ buy (counted for their own
// sponsor) and how many qualifying buyers of their own they have, so a leader can see who is one short
const lTot = await ads.earnedTotals(levels.flatMap(L => L.members.map(m => m.email))); // surf earnings per person (Marty, 2026-09-29)
const onchain = {};
for (const m of levels.flatMap(L => L.members)) { let bought = false, buyers = 0; for (const id of idsOf(m)) { const mm = await cachedMember(id); if (mm) { if (mm.countedAsBuyer) bought = true; buyers += mm.buyerCount || 0; } } onchain[m.email] = { bought, buyers }; }
const out = levels.map(L => ({ level: L.level, members: L.members.map(m => ({
bought: onchain[m.email].bought, buyers: onchain[m.email].buyers,
memberId: m.memberId || 0,
sponsor: sponsorOf(m),
name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member',
ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels
email: L.level === 1 ? m.email : null, // directs only
joined: m.created,
lastSeen: m.lastSeen || 0,
wallet: !!m.address, activated: !!m.memberId,
earned: (lTot[m.email] || {}).earned || 0, balance: (lTot[m.email] || {}).balance || 0,
qualified: idsOf(m).some(id => qualified.has(id)),
earnedWei: idsOf(m).reduce((n, id) => n + BigInt(earnedBy[id] || '0'), 0n).toString() })) }));
// the member's own linked positions sit on level 1 too, labelled as theirs
if (own.length) {
if (!out.find(L => L.level === 1)) out.unshift({ level: 1, members: [] });
const L1 = out.find(L => L.level === 1);
own.forEach((p, i) => L1.members.push({ memberId: p.memberId, name: 'You · position ' + (i + 2), own: true,
email: null, joined: p.created, earnedWei: earnedBy[p.memberId] || '0' }));
}
return json(res, 200, { levels: out, counts: out.map(L => L.members.length) });
}
// -- who is working: one downline member's activity, any of the three levels (Clinton, 2026-09-14)
if (p === '/api/my/line/activity' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const ref = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40);
const a = ref ? await accounts.byCode(ref) : null;
if (!a || !(await accounts.isDownlineOf(s.email, a.email, 3))) return json(res, 404, { error: 'Not in your line.' });
const now = Date.now();
const out = { name: a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'), joined: a.created, lastSeen: a.lastSeen || 0, quietDays: Math.floor((now - Math.max(a.created || 0, a.lastSeen || 0)) / 86400000), wallet: !!a.address, memberId: a.memberId || 0 };
try { const c = await coach.describe(a, now); out.rung = c.label; out.next = c.next; out.stalled = c.stalled; out.buyerCount = c.buyerCount || 0; } catch (e) {}
try { const v = await ads.viewStatus(a.email); out.viewsToday = v.views; out.target = v.target; out.claimedToday = v.claimed; out.streakDay = v.claimed ? v.streakDay : Math.max(0, v.streakDay - 1); } catch (e) {}
try { const cs = await ads.listCampaigns(a.email); out.campaigns = cs.length; out.campaignsActive = cs.filter(c => c.status === 'active').length; out.imps = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0); } catch (e) {}
try { const ls = await coach.linkStats(a.email); out.linkViews30 = (ls.angles || []).reduce((n, r) => n + (r.views30 || 0), 0); out.linkViews = ls.totalViews || 0; out.joins = ls.totalJoins || 0; } catch (e) {}
try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; }
try { out.badges = await ads.milestonesOf(a.email); } catch (e) { out.badges = []; }
try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; }
return json(res, 200, out);
}
// -- broadcast a message to your downline (1/day), on-site inbox + email
if (p === '/api/my/broadcast' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const subject = String(b.subject || '').trim().slice(0, 160);
const body = ads.sanitizeRich(b.body);
const plain = body.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
if (!subject) return json(res, 400, { error: 'Give your message a subject.' });
if (plain.length < 10) return json(res, 400, { error: 'Write a message first.' });
const last = await messages.lastBroadcastAt(s.email);
if (Date.now() - last < 24 * 3600 * 1000)
return json(res, 429, { error: 'You can send one broadcast a day. Try again in ' + Math.ceil((24 * 3600 * 1000 - (Date.now() - last)) / 3600000) + 'h.' });
const depth = b.scope === 'direct' ? 1 : 3;
const levels = await accounts.downline(s.email, depth);
const recipients = [...new Set(levels.flatMap(L => L.members.map(m => m.email)).filter(Boolean))];
if (!recipients.length) return json(res, 400, { error: 'No one in your line to message yet.' });
const memberId = s.memberId || await auth.refreshMemberId(s);
await messages.deliver(memberId, s.email, recipients, subject, body);
// email each recipient too (best-effort; never blocks the on-site delivery)
if (mailer.hasKey()) {
const who = (await accounts.byEmail(s.email));
const from = who && who.username ? '@' + who.username : 'your sponsor';
for (const to of recipients) {
mailer.send(to, 'Message from ' + from + ': ' + subject,
plain + '\n\n— sent via your InstantAdPay upline. Read it in your dashboard: https://instantadpay.com/my#line')
.catch(() => {});
}
}
return json(res, 200, { ok: true, sent: recipients.length });
}
// -- help desk, member side (2026-10-16): the Help pane lists, opens and answers this member's tickets
if (p === '/api/my/support' && (req.method === 'GET' || req.method === 'POST')) {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (req.method === 'GET') return json(res, 200, { tickets: await tickets.memberList(s.email, 'iap'), unread: await tickets.memberUnread(s.email, 'iap'), categories: tickets.CATEGORIES }); // LinkSpin tickets live in LinkSpin's Help
const b = await readBody(req);
if (supportFlood('em:' + String(s.email).toLowerCase(), 5, 3600000)) return json(res, 429, { error: 'You have opened several tickets in the last hour. Add to one of those instead.' });
const a = await accounts.byEmail(s.email);
const r = await tickets.create({ source: 'form', email: s.email, name: (a && a.username) || '', username: a && a.username, subject: b.subject, category: b.category, body: b.body, attachments: b.attachments });
return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, ref: r.ticket.ref });
}
m = /^\/api\/my\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p);
if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const t = await tickets.byRef(m[1]);
if (!t || t.email !== String(s.email).toLowerCase() || t.platform !== 'iap') return json(res, 404, { error: 'Ticket not found.' });
if (req.method === 'GET') return json(res, 200, await tickets.memberView(t));
const b = await readBody(req);
if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' });
const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, attachments: b.attachments });
return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket));
}
// -- sponsor messages: this member's inbox from their upline
if (p === '/api/my/messages' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const items = await messages.inbox(s.email);
const names = await accounts.namesForMembers([...new Set(items.map(i => i.fromMember).filter(Boolean))]);
for (const i of items) i.fromName = (i.fromMember && names[i.fromMember]) ? '@' + names[i.fromMember]
: i.fromMember ? 'member #' + i.fromMember : 'your upline';
return json(res, 200, { items, unread: items.filter(i => !i.read).length });
}
m = /^\/api\/my\/messages\/(\d+)\/read$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await messages.markRead(s.email, m[1]));
}
// ── SPONSOR CHAT (two-way): presence-aware 1:1 threads up/down the line ──
const chatOnline = ts => (Date.now() - (ts || 0)) < 60000;
const chatName = a => !a ? 'member' : (a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'));
// lightweight presence heartbeat (called on a timer while the dashboard is open)
if (p === '/api/my/ping' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 200, { ok: true, chatUnread: 0 });
accounts.touchSeen(s.email).catch(() => {});
return json(res, 200, { ok: true, chatUnread: await messages.chatUnread(s.email) });
}
// training center content (admin-curated via data/training.json)
if (p === '/api/training' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s) return json(res, 401, { error: 'Sign in first.' });
let items = [];
try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'training.json'), 'utf8')); if (Array.isArray(j)) items = j; } catch (e) {}
// a card with feature:'pipeline' waits for the switch, so the video can be ready before the tab opens (Marty, 2026-09-15)
const scT = siteConfig(); const launched = scT.launchAt && Date.now() >= new Date(scT.launchAt).getTime(); // feature:'polhunter' waits for the launch moment (Marty, 2026-09-20)
items = items.filter(it => !it.feature || (it.feature === 'pipeline' && pipeline.visible(scT.pipelineMode, s.email, ADMIN_EMAIL)) || (it.feature === 'polhunter' && launched));
if (!items.length) items = [{ title: 'Getting started with InstantAdPay',
desc: 'How the platform works, how every payout splits on-chain to real wallets, and how to build your line.',
docUrl: 'https://instantadpay.com/' }];
return json(res, 200, { items });
}
// daily login bonus (once/day, gentle streak) — granted after the login flow
if (p === '/api/my/login-bonus' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const cfg = siteConfig(); // comebackBonus (250) after comebackDays (7) away; 0 switches it off
return json(res, 200, await ads.grantLoginBonus(s.email, { comeback: cfg.comebackBonus == null ? 250 : Number(cfg.comebackBonus), comebackDays: cfg.comebackDays == null ? 7 : Number(cfg.comebackDays) }));
}
// -- rehearsal test-POL faucet: top a connected wallet up to 10 test-POL
// (anvil_setBalance, no key needed). Rehearsal-only, rate-limited.
if (p === '/api/my/faucet' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s) return json(res, 401, { error: 'Sign in first.' });
if (!siteConfig().rehearsal) return json(res, 400, { error: 'The faucet is only open during the rehearsal.' });
const b = await readBody(req);
const addr = String(b.address || '').trim().toLowerCase();
if (!/^0x[0-9a-f]{40}$/.test(addr)) return json(res, 400, { error: 'Connect your wallet first.' });
// Amoy is a public testnet: testers fund their own connected wallet from
// the public Amoy faucet (no server-minted balance). We just echo the
// address + faucet link; the client copies the address and opens it.
let balHex = '0x0'; try { balHex = await chain.rpc('eth_getBalance', [addr, 'latest']); } catch (e) {}
return json(res, 200, { ok: true, faucetUrl: 'https://faucet.polygon.technology/', address: addr, balanceWei: BigInt(balHex || '0x0').toString() });
}
// -- report an ad (auto-approved ads need a safety valve): store + notify admin
if (p === '/api/report-ad' && req.method === 'POST') {
const b = await readBody(req);
if (!Number(b.campaignId)) return json(res, 400, { error: 'Which ad?' });
const s = await auth.fromRequest(req);
const who = (s && s.email) || '';
const rec = await reports.add(b.campaignId, who, b.reason, b.note);
try {
const adminEmail = process.env.ADMIN_EMAIL || ''; // private env only — siteConfig is exposed via /api/config
if (adminEmail && mailer.hasKey()) {
mailer.send(adminEmail, 'Ad reported on InstantAdPay (campaign #' + rec.campaignId + ')',
'A member flagged an ad.\n\nCampaign: #' + rec.campaignId + '\nReason: ' + rec.reason
+ '\nReported by: ' + (who || 'anonymous') + '\nNote: ' + (String(b.note || '').slice(0, 500) || '(none)')
+ '\n\nPause or review it from the admin.').catch(() => {});
}
} catch (e) {}
return json(res, 200, { ok: true });
}
if (p === '/api/my/chat/send' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const me = s.email.toLowerCase();
const b = await readBody(req);
const to = String(b.to || '').trim().toLowerCase();
const text = String(b.body || '').replace(/<[^>]*>/g, '').replace(/\s+$/, '').slice(0, 2000).trim();
if (!to || to === me) return json(res, 400, { error: 'Pick who to message.' });
if (!text) return json(res, 400, { error: 'Write a message first.' });
const target = await accounts.byEmail(to);
if (!target) return json(res, 404, { error: 'No such member.' });
// authorize: existing thread, my direct sponsor, or someone in my downline
let ok = (await messages.thread(me, to, 0, 1)).length > 0;
if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === to); }
if (!ok) ok = await accounts.isDownlineOf(me, to);
if (!ok) return json(res, 403, { error: 'You can only message your direct sponsor or someone in your line.' });
if ((await accounts.getMutes(to)).map(x => String(x).toLowerCase()).includes(me))
return json(res, 403, { error: 'They are not accepting messages from you right now.' });
const memberId = s.memberId || await auth.refreshMemberId(s);
const msg = await messages.sendChat(memberId, me, to, text);
// email only when they are offline AND I have not messaged them in ~10 min (no mid-chat spam)
try {
if (mailer.hasKey() && !chatOnline(target.lastSeen)) {
const mine = (await messages.thread(me, to, 0, 400)).filter(x => x.id !== msg.id && String(x.fromEmail).toLowerCase() === me);
const lastMineTs = mine.length ? mine[mine.length - 1].sent : 0;
if (Date.now() - lastMineTs > 10 * 60 * 1000) {
const who = await accounts.byEmail(me);
const from = who && who.username ? '@' + who.username : 'someone in your InstantAdPay line';
mailer.send(to, 'New message from ' + from,
text.slice(0, 400) + '\n\n— reply in your dashboard: https://instantadpay.com/my').catch(() => {});
}
}
} catch (e) {}
return json(res, 200, { ok: true, message: { id: msg.id, sent: msg.sent, fromMe: true, body: text } });
}
if (p === '/api/my/chat/thread' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const me = s.email.toLowerCase();
const other = String(u.searchParams.get('with') || '').trim().toLowerCase();
const after = Number(u.searchParams.get('after')) || 0;
if (!other) return json(res, 400, { error: 'Who with?' });
// may view a thread I'm party to (existing), or one I'm allowed to start
let ok = (await messages.thread(me, other, 0, 1)).length > 0;
if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === other); }
if (!ok) ok = await accounts.isDownlineOf(me, other);
if (!ok) return json(res, 403, { error: 'Not your conversation.' });
const msgs = await messages.thread(me, other, after, 300);
await messages.markChatRead(me, other);
accounts.touchSeen(me).catch(() => {});
const oa = await accounts.byEmail(other);
const iMute = (await accounts.getMutes(me)).map(x => String(x).toLowerCase()).includes(other);
const theyMuteMe = (await accounts.getMutes(other)).map(x => String(x).toLowerCase()).includes(me);
return json(res, 200, {
messages: msgs.map(x => ({ id: x.id, fromMe: String(x.fromEmail).toLowerCase() === me, body: x.body, sent: x.sent })),
otherName: chatName(oa), online: oa ? chatOnline(oa.lastSeen) : false,
available: oa ? oa.chatAvailable !== false : true, iMute, blocked: theyMuteMe,
canMute: await accounts.isDownlineOf(me, other) });
}
if (p === '/api/my/chat/threads' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const list = await messages.threadList(s.email.toLowerCase());
for (const t of list) {
const a = await accounts.byEmail(t.email);
t.name = chatName(a); t.online = a ? chatOnline(a.lastSeen) : false;
}
list.sort((x, y) => (y.last.sent || 0) - (x.last.sent || 0));
const meAcct = await accounts.byEmail(s.email);
return json(res, 200, { threads: list, available: meAcct ? meAcct.chatAvailable !== false : true });
}
if (p === '/api/my/chat/available' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
return json(res, 200, await accounts.setChatAvailable(s.email, !!b.available));
}
if (p === '/api/my/chat/mute' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const target = String(b.email || '').trim().toLowerCase();
if (!target) return json(res, 400, { error: 'Who?' });
const allowed = (await accounts.isDownlineOf(s.email, target)) || (await messages.thread(s.email.toLowerCase(), target, 0, 1)).length > 0;
if (!allowed) return json(res, 403, { error: 'You can only mute someone in your line.' });
return json(res, 200, await accounts.setMute(s.email, target, !!b.muted));
}
// -- featured rotation: the live featured links + dilution stats
if (p === '/api/featured' && req.method === 'GET') {
const items = await ads.serveFeatured(viewerGeo(req));
try { const sv = await auth.fromRequest(req); ads.noteFeaturedViews(items, (sv && sv.email) || clientIp(req)).catch(() => {}); } catch (e) {} // count the view (per viewer per hour)
const names = await accounts.namesForMembers([...new Set(items.map(i => i.memberId).filter(Boolean))]);
for (const i of items) i.by = (i.memberId && names[i.memberId]) ? '@' + names[i.memberId] : (i.memberId ? 'member #' + i.memberId : null);
return json(res, 200, { items });
}
if (p === '/api/featured/stats' && req.method === 'GET') {
return json(res, 200, await ads.featuredStats());
}
// -- QR code (SVG) for any InstantAdPay URL — used on bio/wall pages
if (p === '/api/qr' && req.method === 'GET') {
const data = String(u.searchParams.get('d') || '').slice(0, 300);
if (!QR || !data) { res.writeHead(404, baseHeaders()); return res.end(); }
try {
const svg = await QR.toString(data, { type: 'svg', margin: 1, width: 240,
color: { dark: '#0e7d5f', light: '#f2fbf8' } }); // mint-green modules, still high-contrast for reliable scanning
res.writeHead(200, baseHeaders({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600' }));
return res.end(svg);
} catch (e) { res.writeHead(500, baseHeaders()); return res.end(); }
}
// -- profile: avatar + bio
if (p === '/api/my/profile-details' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const avatar = b.avatarUrl === undefined ? undefined : String(b.avatarUrl || '').trim();
if (avatar && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(avatar))
return json(res, 400, { error: 'Avatar must be an uploaded image or an https image URL.' });
const bio = b.bio === undefined ? undefined : String(b.bio || '').trim().slice(0, 600);
// socials: {platform: url}; keep only known platforms with valid https urls
let socials, cleanSoc = null;
if (b.socials !== undefined) {
const PLAT = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video'];
const clean = {};
for (const p of PLAT) {
const v = String((b.socials && b.socials[p]) || '').trim();
if (v && /^https:\/\/[^\s]+$/i.test(v) && v.length <= 300) clean[p] = v;
}
// intro video on the public wall: a YouTube, Vimeo or direct .mp4/.webm link only
if (clean.video && !/^https:\/\/((www\.|m\.)?youtube\.com\/(watch\?|shorts\/|embed\/)|youtu\.be\/|(www\.)?vimeo\.com\/\d+|player\.vimeo\.com\/video\/\d+|[^\s]+\.(mp4|webm)(\?|$))/i.test(clean.video))
return json(res, 400, { error: 'The intro video needs to be a YouTube link, a Vimeo link, or a direct .mp4 link.' });
socials = Object.keys(clean).length ? JSON.stringify(clean) : null;
cleanSoc = clean;
}
// prohibited-content policy (2026-10-30): gambling, adult, pharma, weapons and link-selling terms are refused in the bio and the social URLs
{ const pr = prohibited.checkFields(Object.assign({ bio }, cleanSoc || {}), 'InstantAdPay', { profile: true }); if (pr.error) { prohibited.logRefusal('profile-details', s.email, pr); return json(res, 400, { error: pr.error }); } }
// a bio is not a backlink: links go in the social fields. Exception, the quarantine rule: a brand-new free account (no wallet,
// no sponsor, under 24 h) whose first save plants a link is saved with profileQuarantined and never rendered publicly
const acct = await accounts.byEmail(s.email);
const quarantine = spamscan.shouldQuarantine(acct, bio, cleanSoc) ? true : undefined;
if (bio && prohibited.hasUrl(bio) && !quarantine) { prohibited.logRefusal('profile-details', s.email, { field: 'bio', reason: 'url' }); return json(res, 400, { error: prohibited.BIO_LINK_MSG }); }
const r = await accounts.setProfile(s.email, avatar, bio, socials, quarantine);
if (quarantine && !r.error) { console.log('profile quarantined', String(s.email).replace(/^(.).*(@.*)$/, '$1***$2'), prohibited.hasUrl(bio) ? 'bio-url' : 'social-link'); r.quarantined = true; r.notice = spamscan.QUARANTINE_NOTICE; }
return json(res, r.error ? 400 : 200, r);
}
// -- BixPay partner link (2026-10-29): Profile > BixPay card. Validated (bix.ibportal.io/auth/register, e=, a=1; the
// appId=3 card-customer link is refused with a message); empty clears it. Rides to LinkSpin in the profile row.
if (p === '/api/my/bixpay' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (!bixpay.live()) return json(res, 404, { error: 'Not open yet.' });
const b = await readBody(req);
const raw = String(b.link == null ? '' : b.link).trim();
if (!raw) { const r = await accounts.setBixLink(s.email, null); if (r.error) return json(res, 400, r); const rs = await bixpay.resolve(r.account); return json(res, 200, { ok: true, own: null, link: rs.link, whose: rs.whose, name: rs.name, using: bixpay.usingLine(rs) }); }
const v = bixpay.validate(raw);
if (!v.ok) return json(res, 400, { error: v.error, customerLink: v.error === bixpay.CUSTOMER_LINK_MSG });
const r = await accounts.setBixLink(s.email, v.link);
if (r.error) return json(res, 400, r);
return json(res, 200, { ok: true, own: v.link, link: v.link, whose: 'you', name: null, using: bixpay.usingLine({ whose: 'you' }) });
}
// -- the /bixpay guide's CTA: the viewer's resolved link (their own when signed in, else the ?ref / sponsor cookie's member, else network)
if (p === '/api/public/bixpay' && req.method === 'GET') {
if (!bixpay.live()) return json(res, 200, { live: false });
const s = await auth.fromRequest(req).catch(() => null);
let acct = (s && s.email && await accounts.byEmail(s.email)) || null;
const tok = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40) || String(parseCookies(req)['iap.sponsor'] || '').trim().toLowerCase().slice(0, 40);
const r = acct ? await bixpay.resolve(acct) : await bixpay.resolveRef(tok);
const owner = acct || (tok ? await refAccount(tok).catch(() => null) : null);
return json(res, 200, { live: true, whose: r.whose, name: r.name, using: bixpay.usingLine(r), go: bixpay.goLink('guide', owner ? (owner.username || owner.code) : ''), promoGo: owner ? bixpay.goLink('promo', owner.username || owner.code) : null, signedIn: !!acct });
}
// -- wall positions 2 & 3: the member's own offers, unlocked at 2 / 5 qualifying buyers
if (p === '/api/my/wall-offers' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const src = Array.isArray(b.offers) ? b.offers.slice(0, 2) : [];
const out = [];
for (let i = 0; i < 2; i++) {
const o = src[i] || {};
const targetUrl = String(o.targetUrl || '').trim();
const bannerUrl = String(o.bannerUrl || '').trim();
const title = String(o.title || '').trim().slice(0, 60);
if (targetUrl && !/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': the link must start with https://' });
if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': banner must be an uploaded image or an https image URL.' });
{ const pr = prohibited.checkFields({ title, targetUrl }, 'InstantAdPay'); if (pr.error) { prohibited.logRefusal('wall-offers', s.email, pr); return json(res, 400, { error: pr.error }); } }
out.push(targetUrl ? { title: title || null, bannerUrl: bannerUrl || null, targetUrl } : null);
}
const r = await accounts.setWallOffers(s.email, out.some(Boolean) ? JSON.stringify(out) : null);
return json(res, r.error ? 400 : 200, r);
}
// -- line banner: the member's viral slot on welcome tours + their wall
if (p === '/api/my/linebanner' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const target = String(b.targetUrl || '').trim();
if (!/^https?:\/\/[^\s]+$/i.test(target)) return json(res, 400, { error: 'Destination URL must start with http(s)://' });
{ const pr = prohibited.checkFields({ targetUrl: target }, 'InstantAdPay'); if (pr.error) { prohibited.logRefusal('linebanner', s.email, pr); return json(res, 400, { error: pr.error }); } }
const fc = await frameCheck(target); // welcome tours frame it full screen
if (!fc.ok) return json(res, 400, { error: fc.reason });
const banner = String(b.bannerUrl || '').trim();
if (banner && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(banner))
return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL.' });
const r = await accounts.setLineBanner(s.email, banner || null, target);
return json(res, r.error ? 400 : 200, r);
}
// -- welcome tour (gauntlet): meet the 3-level upline, then unlock welcome credits
if (p === '/api/my/gauntlet' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (await ads.welcomeGranted(s.email)) return json(res, 200, { pending: false });
const slides = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl)
.map((a, i) => ({ name: a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member',
bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl }));
if (!slides.length) return json(res, 200, { pending: false });
const token = crypto.randomBytes(16).toString('hex');
gauntletTokens.set(s.email, { token, ts: Date.now(), n: slides.length });
return json(res, 200, { pending: true, slides, dwell: 10, token });
}
if (p === '/api/my/gauntlet/complete' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const t = gauntletTokens.get(s.email);
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That tour is no longer open. Reload and try again.' });
if (Date.now() - t.ts < t.n * 10 * 1000 - 1500) return json(res, 400, { error: 'Give each site its ten seconds first.' });
gauntletTokens.delete(s.email);
await ads.grantWelcome(s.email);
return json(res, 200, { ok: true, credited: ads.rates().welcomeCredits || 0 });
}
// -- public banner wall
m = /^\/api\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p);
if (m && req.method === 'GET') {
const tok = m[1].toLowerCase();
let a = await accounts.byUsername(tok);
if (!a) a = await accounts.byCode(tok);
if (!a) return json(res, 404, { error: 'No wall under that name.' });
const ownName = a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member';
let bc = 0;
if (a.memberId) { try { bc = (await chain.member(a.memberId)).buyerCount || 0; } catch (e) {} }
const unlocked = wallUnlockedFor(bc);
const offers = parseWallOffers(a);
// uplines with a live banner, in order (an upline with nothing set is skipped, not shown empty)
const ups = (await uplineSlides(a.email, 2)).filter(x => x.lineTargetUrl)
.map(x => ({ name: x.username ? '@' + x.username : x.memberId ? 'member #' + x.memberId : 'a member',
bannerUrl: x.lineBannerUrl || null, targetUrl: x.lineTargetUrl, upline: true }));
const adAds = getAdminWallAds(); let ai = 0;
const houseAd = () => { if (!adAds.length) return null; const ad = adAds[ai++ % adAds.length]; return { name: ad.name || 'InstantAdPay', bannerUrl: ad.bannerUrl || null, targetUrl: ad.targetUrl || 'https://instantadpay.com/', admin: true }; };
const ladder = [{ name: ownName, bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl || null, own: true }];
for (let i = 1; i < 3; i++) {
const o = offers[i - 1];
if (i < unlocked && o && o.targetUrl) { ladder.push({ name: (o.title || ownName), bannerUrl: o.bannerUrl || null, targetUrl: o.targetUrl, own: true }); continue; }
const u = ups.shift(); if (u) { ladder.push(u); continue; }
const h = houseAd(); if (h) ladder.push(h);
}
const finalLadder = ladder.slice(0, 3);
// the wall owner's achievement badge (their highest reached tier)
let badge = null;
if (a.memberId) {
const t = bc >= 5 ? ['nexus', 'Nexus'] : bc >= 2 ? ['circuit', 'Circuit'] : bc >= 1 ? ['surge', 'Surge'] : ['spark', 'Spark'];
badge = { img: '/badges/badge-' + t[0] + '.jpg?v=2', label: t[1] };
}
const joinPath = '/join/' + (a.username || a.code);
// profile fields (bio, avatar, socials, intro video) only for a paying member; a free account's wall carries the name, the line's ads and the join call (2026-10-30)
const bought = await hasBought(a); // a purchase lifts the quarantine too: the notice promised the links after the first package
let socials = null; if (bought) { try { socials = a.socials ? JSON.parse(a.socials) : null; } catch (e) {} }
return json(res, 200, { name: a.username ? '@' + a.username : 'member #' + (a.memberId || 0), bought,
avatarUrl: bought ? (a.avatarUrl || null) : null, bio: bought ? (a.bio || null) : null, socials, badge,
joinUrl: joinPath, qrUrl: '/api/qr?d=' + encodeURIComponent('https://instantadpay.com' + joinPath), ladder: finalLadder, unlocked, buyerCount: bc });
}
// -- watch-to-earn video ads: serve one, then reward a server-clock-verified watch
if (p === '/api/my/videos' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const status = await ads.videoStatus(s.email);
if (status.left <= 0) return json(res, 200, { ad: null, status });
const orientation = String(u.searchParams.get('orientation') || ''); // 'portrait' = Shorts reel, 'landscape' = Watch videos tab
const ad = await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation }, viewerGeo(req))); // never your own video
if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13)
let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation, ignoreSeen: true }, viewerGeo(req)))); } catch (e) {}
// this surface is empty but the other one may not be: the Watch tab holds the landscape
// videos and Shorts holds the portrait ones, and they share one daily cap, so a member
// who runs the tab dry still has clips waiting (Marty, 2026-09-22)
let otherFormat = null;
if (status.left > 0 && (orientation === 'landscape' || orientation === 'portrait')) {
const alt = orientation === 'landscape' ? 'portrait' : 'landscape';
try { if (await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation: alt }, viewerGeo(req)))) otherFormat = alt === 'portrait' ? 'shorts' : 'watch'; } catch (e) {}
}
return json(res, 200, { ad: null, status, allWatched, otherFormat });
}
const token = crypto.randomBytes(16).toString('hex');
videoTokens.set(s.email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs });
return json(res, 200, { ad, token, status });
}
if (p === '/api/my/videowatch' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const t = videoTokens.get(s.email);
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That video is no longer open. Load the next one.' });
const age = Date.now() - t.ts;
if (age < t.secs * 1000 - 600) return json(res, 400, { error: 'Watch the full video first.' });
if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(s.email); return json(res, 400, { error: 'That watch went stale. Load a fresh video.' }); }
videoTokens.delete(s.email); // single use
if (await ads.hasWatchedVideoToday(s.email, t.id)) // once-per-day-per-video: no double earning
return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), already: true });
const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry
if (!tier) return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), gone: true });
await ads.addEarned(s.email, tier.reward, { log: { kind: 'earn', note: 'Watched a video (' + tier.secs + 's)' } });
await ads.markVideoSeen(s.email, t.id);
const status = await ads.recordVideoWatch(s.email);
return json(res, 200, { ok: true, credited: tier.reward, status });
}
// -- verified visits: view a member's site (new tab) for the dwell, pass a
// human check, and it counts as one guaranteed unique visit for the pack
if (p === '/api/my/visits' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const status = await ads.visitStatus(s.email);
if (status.count >= status.cap) return json(res, 200, { ad: null, status });
const ad = await ads.serveVisit(s.email, viewerGeo(req));
if (!ad) return json(res, 200, { ad: null, status });
const token = crypto.randomBytes(16).toString('hex');
visitTokens.set(s.email, { token, ts: Date.now(), id: ad.id });
return json(res, 200, { ad, token, status });
}
if (p === '/api/my/visitchallenge' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const t = visitTokens.get(s.email);
if (!t || t.token !== String(u.searchParams.get('token') || '')) return json(res, 400, { error: 'That visit is no longer open.' });
const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000;
const age = Date.now() - t.ts;
if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) });
if (age > 5 * 60 * 1000) { visitTokens.delete(s.email); return json(res, 400, { error: 'That visit went stale. Load a fresh one.' }); }
const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5);
const answer = Math.floor(Math.random() * pick.length);
t.challenge = { answer };
return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) });
}
if (p === '/api/my/visitdone' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const t = visitTokens.get(s.email);
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That visit did not check out. Load the next one.' });
const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000;
if (Date.now() - t.ts < dwellMs - 400) return json(res, 400, { error: 'Give the site the full visit first.' });
if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true });
if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; return json(res, 400, { error: 'Wrong pick.', retry: true }); }
visitTokens.delete(s.email);
const r = await ads.completeVisit(s.email, t.id);
if (r.error) return json(res, 400, r);
return json(res, 200, Object.assign(r, { status: await ads.visitStatus(s.email) }));
}
// -- onsite solo ads: member inbox with read rewards
if (p === '/api/my/inbox' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await ads.inboxList(s.email, viewerGeo(req));
const names = await accounts.namesForMembers([...new Set(r.items.map(i => i.fromMemberId).filter(Boolean))]);
for (const i of r.items) i.fromName = (i.fromMemberId && names[i.fromMemberId]) ? '@' + names[i.fromMemberId]
: i.fromMemberId ? 'member #' + i.fromMemberId : 'a member';
return json(res, 200, r);
}
m = /^\/api\/my\/inbox\/(\d+)$/.exec(p);
if (m && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await ads.inboxOpen(s.email, m[1]);
if (!r.error) {
const names = r.fromMemberId ? await accounts.namesForMembers([r.fromMemberId]) : {};
r.fromName = (r.fromMemberId && names[r.fromMemberId]) ? '@' + names[r.fromMemberId]
: r.fromMemberId ? 'member #' + r.fromMemberId : 'a member';
}
return json(res, r.error ? 404 : 200, r);
}
// media upload for solo ads: raw body, size-capped, magic-byte verified
if (p === '/api/my/upload' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return handleUpload(req, res, s.email);
}
m = /^\/api\/my\/inbox\/(\d+)\/visit$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await ads.markSoloVisit(s.email, m[1]);
return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/inbox\/(\d+)\/claim$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await ads.claimSoloRead(s.email, m[1]);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/activity' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s) return json(res, 401, { error: 'Sign in first.' });
const id = s.memberId || await auth.refreshMemberId(s);
if (!id) return json(res, 200, { memberId: 0, earnings: [], purchases: [], referrals: [] });
const evs = chain.recentEvents(1e9); // whole history (was the last 600 events: older members saw three empty boxes)
return json(res, 200, {
memberId: id,
earnings: (await attachNames(evs.filter(e => (e.type === 'TierPaid' && e.recipientId === id) || (e.type === 'AwardPaid' && e.toId === id)).slice(0, 300)))
.map(e => { const ov = e.type === 'AwardPaid' && override.txInfo(e.tx); return ov ? Object.assign({}, e, { override: true, overrideWeek: ov.week }) : e; }), // level-4 override label
purchases: await attachNames(evs.filter(e => e.type === 'Purchase' && e.buyerId === id).slice(0, 300)),
referrals: await attachNames(evs.filter(e => (e.type === 'MemberActivated' && e.sponsorId === id) || (e.type === 'BuyerCounted' && e.sponsorId === id)).slice(0, 300))
});
}
// -- ad engine (spec §8b v1: banners, text, login ads)
if (p === '/api/ads/slot' && req.method === 'GET') {
const t = String(u.searchParams.get('type') || 'banner');
if (t === 'login') return json(res, 200, { ad: await loginAdFor(req, 'dashboard') });
const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req)));
return json(res, 200, { ad });
}
m = /^\/api\/ads\/click\/(\d+)$/.exec(p);
if (m && req.method === 'GET') {
// an advertiser opening their own ad's link (from Campaigns, a preview, a test) is not a click: relay it uncounted (Marty, 2026-09-30)
let own = false, cm = null;
try { cm = await ads.campaignById(m[1]); } catch (e) {}
try { const s = cm && await auth.fromRequest(req); if (s && s.email) own = !!(cm.owner && String(cm.owner).toLowerCase() === String(s.email).toLowerCase()); } catch (e) {}
const target = own ? await ads.targetOf(m[1]) : await ads.click(m[1]);
if (!target) { res.writeHead(404, baseHeaders()); return res.end(); }
if (!own) coach.recordClick(m[1], req.headers.referer); // where the click happened
// conversion tracking (2026-10-23): every click, the owner's own too (flagged self, so they can test), gets a click id
// on the target URL as lsclk=<id>; the row goes to LinkSpin, which matches the advertiser's goal pixel to it
let loc = target;
// self for conversion tracking (2026-10-26): signed in as the owner, OR from a browser the owner signs in from (soft
// key). Only the conversion side; whether the click is counted and billed above stays the signed-in check.
if (cm) { try { const ip = clientIp(req); const selfConv = own || lsconv.isOwnerSk(cm.owner, lsconv.softKey(ip, req.headers['user-agent'])); const row = await lsconv.record(cm, req, { self: selfConv, target, ip, country: geo.countryOf(ip) || null }); loc = lsconv.withClickId(target, row.id); } catch (e) { console.error('lsconv record', e.message); } }
res.writeHead(302, baseHeaders({ Location: loc }));
return res.end();
}
// Campaigns > Conversion tracking: the member's goals and counts live on LinkSpin; these proxy the signed calls
// -- Monthly Refuel (2026-10-24): the member's refuel day, streak, next bonus and Pit Stop status ({ on:false } while switched off)
// -- the Refuel Kit (2026-10-24): personalized banners are public by URL (ad networks load them), rendered only for entitled members
if (p.startsWith('/kitimg/') && (req.method === 'GET' || req.method === 'HEAD')) {
const f = kit.servePath(p.slice(8)); if (!f) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
res.writeHead(200, { 'Content-Type': f.mime, 'Cache-Control': 'public, max-age=86400', 'Access-Control-Allow-Origin': '*' });
return req.method === 'HEAD' ? res.end() : fs.createReadStream(f.file).pipe(res);
}
if (p === '/api/my/kits' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await kit.myKits(s.email));
}
if (p === '/api/my/kits/render' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await kit.renderFor(s.email, String(b.month || ''), String(b.size || ''), b.variant === 'gif' ? 'gif' : 'still');
return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, url: r.url, abs: r.abs, size: r.size, variant: r.variant, bytes: r.bytes });
}
// -- the Engine Room (2026-10-24): InstantAdPay's facts + LinkSpin's (signed, cached a minute) + the streak, built into one panel
if (p === '/api/my/engine' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const rv = await refuel.view(s.email); if (!rv.on) return json(res, 200, { on: false });
const [own, peer] = await Promise.all([engine.facts({ site: 'iap', adminMember, ads, coach }, s.email), engineFromLinkSpin(s.email, u.searchParams.get('fresh') === '1')]);
return json(res, 200, engine.build({ site: 'iap', refuel: rv, iap: own, ls: peer, goal: rv.goal }));
}
if (p === '/api/my/engine/goal' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req); const r = await refuel.setGoal(s.email, b.goal); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/refuel' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await refuel.view(s.email));
}
if (p === '/api/my/conversions' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (!lsconv.on()) return json(res, 200, { ok: false, reason: 'off', error: 'Conversion tracking is not switched on yet. Your ads and clicks work as usual.' });
// cost per goal (30 days), 2026-10-26: the goals are LinkSpin's last 30 days, so the spend beside them is each
// campaign's spend over the same 30 days from the credit activity log (spend30), not its lifetime total
const since = Date.now() - 30 * 86400000; let sp = null;
try { sp = await ads.spendSince(s.email, since); } catch (e) { console.error('spendSince', e.message); }
try { return json(res, 200, Object.assign({}, await lsconv.summary(s.email, u.searchParams.get('fresh') === '1'), { ok: true, spendSince: since, spendDay: sp ? sp.day : null, spend30: sp ? sp.byCampaign : null })); }
catch (e) { return json(res, 200, { ok: false, reason: 'down', error: 'LinkSpin, the service that counts your conversions, did not answer just now. Your ads and clicks are fine. Try again in a minute.' }); }
}
if ((p === '/api/my/conversions/goal' || p === '/api/my/conversions/test') && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
if (!lsconv.on()) return json(res, 503, { error: 'Conversion tracking is not switched on yet.' });
const b = await readBody(req) || {};
const op = p.endsWith('/test') ? 'test' : String(b.op || '');
if (!['create', 'update', 'remove', 'test'].includes(op)) return json(res, 400, { error: 'Unknown action.' });
const f = {};
if (op !== 'create') { const px = String(b.px || '').trim().toLowerCase(); if (!/^px[0-9a-f]{10}$/.test(px)) return json(res, 400, { error: 'That pixel id does not look right.' }); f.px = px; }
if (op === 'create' || op === 'update') {
if (b.name != null) { const nm = String(b.name).trim().toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9_-]/g, '').slice(0, 32); if (!nm) return json(res, 400, { error: 'Give the goal a short name, like subscriber or sale (letters, numbers, dashes).' }); f.name = nm; }
else if (op === 'create') return json(res, 400, { error: 'Give the goal a short name, like subscriber or sale.' });
if (b.value != null && String(b.value).trim() !== '') { const v = Number(b.value); if (!isFinite(v) || v < 0 || v > 1e6) return json(res, 400, { error: 'The value should be a number, like 19.95, or left empty.' }); f.value = Math.round(v * 100) / 100; }
else if (op === 'update' && b.value != null) f.value = null;
}
try { return json(res, 200, Object.assign({ ok: true }, await lsconv.goalOp(s.email, op, f))); }
catch (e) { return json(res, e.plain && e.status && e.status < 500 ? 400 : 502, { error: e.plain ? e.message : 'LinkSpin did not answer just now. Nothing was changed. Try again in a minute.' }); }
}
if (p === '/api/my/trace' && req.method === 'GET') { // payment trace for yourself or anyone within 3 levels of you, either direction
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const mine = (await myMemberIds(s)).ids.filter(Boolean);
const who = String(u.searchParams.get('who') || '').trim().replace(/^[@#]/, '').toLowerCase();
let target = /^\d+$/.test(who) ? Number(who) : 0;
if (!target && who) { let a = await accounts.byUsername(who); if (!a) a = await accounts.byCode(who); if (a && a.memberId) target = a.memberId; }
if (!target && !who && mine.length) target = mine[0];
if (!target) return json(res, 400, { error: who ? 'No activated member called "' + who.slice(0, 40) + '". Use a member number or a username of someone who has bought a package.' : 'Enter a member number or username.' });
if (!mine.length) return json(res, 403, { error: 'Link a wallet and buy a package first; the trace works on chain positions.' });
const smap = sponsorMapFromIndex(chain.recentEvents(1e9));
const ok = mine.includes(target) || uplineIds(smap, target, 3).some(x => mine.includes(x)) || mine.some(m => uplineIds(smap, m, 3).includes(target));
if (!ok) return json(res, 403, { error: 'You can trace yourself, anyone up to 3 levels below you, and your own 3 uplines.' });
return json(res, 200, await tracePurchases(target, 30));
}
if (p === '/api/my/credits/activity' && req.method === 'GET') { // credit ledger: every earn and spend with a reason, newest first
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, { items: await ads.creditActivity(s.email, 40) });
}
if (p === '/api/my/campaigns' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const memberId = await auth.refreshMemberId(s);
const all = await ads.listCampaigns(s.email);
// archived ones keep their full stats but leave the working list (Marty, 2026-09-23)
const out = { campaigns: all.filter(c => c.status !== 'archived'), archived: all.filter(c => c.status === 'archived'),
rates: ads.rates(), bannerSizes: ads.bannerSizes() };
const ids = all.map(c => c.id); // archived included: their numbers are the whole point of keeping them
out.clickSources = await coach.clickSources(ids);
out.hours = await ads.hoursFor(ids); // on-site views per UTC hour, last 7 days
out.geo = await ads.geoFor(ids); // on-site serves per viewer country
out.doorStats = await ads.doorStats(all.filter(c => c.type === 'visits').map(c => c.id)); // Spooky Doors: doors opened + unique players per pack
{ const t = geo.tierLists(siteConfig()); out.tiers = { t1: [...t.t1], t2: [...t.t2] }; out.geoReady = geo.status().loaded; }
const pool = await ads.balances((await myMemberIds(s)).ids, s.email);
out.purchasedCredits = pool.total;
out.largestPosition = pool.best.avail; // a single campaign budget has to fit one position
out.positionCount = pool.per.length;
out.creditedCredits = pool.credited; // refunded/credited purchased money, free (counts inside purchasedCredits)
out.earnedCredits = pool.earned; // earned pool minus what live campaigns already hold
out.earnedReserved = pool.earnedReserved;
out.inCampaigns = pool.inCampaigns; // budget still to deliver across live campaigns
out.availableCredits = pool.available;
out.loginLine = await ads.loginQueueView(s.email); // login-ad slots: open now, the paid line, this member's places + estimated starts
return json(res, 200, out);
}
if (p === '/api/my/campaigns' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const memberId = await auth.refreshMemberId(s); // 0 is fine: earned credits fund banner/text
const b = await readBody(req);
if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { // banner/text surf views frame the target; login/video/solo/featured open in a new tab or play in our own player
if (b.type === 'banner' || (b.type === 'login' && b.imageUrl)) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); }
const fc = await frameCheck(b.targetUrl);
if (!fc.ok) return json(res, 400, { error: fc.reason });
}
if (String(b.type) === 'video') { const vc = await videoCheck(b.videoUrl); if (!vc.ok) return json(res, 400, { error: vc.reason }); }
{ const sb = await sbcheck.check(b.targetUrl); if (!sb.ok) return json(res, 400, { error: sb.reason }); }
{ const rc = await reach.check(b.targetUrl); if (!rc.ok) return json(res, 400, { error: rc.reason }); }
// charge the best-funded of the member's positions (main + Qualified Start
// wallets). A campaign burns from one member id, so the budget must fit inside it.
const ids = (await myMemberIds(s)).ids;
const pool = await ads.balances(ids, s.email);
const fundId = pool.best.memberId || memberId;
const earnedNow = String(b.type) !== 'login' ? pool.earned : 0;
const budget = Math.floor(Number(b.budget) || 0);
if (pool.per.length > 1 && budget > pool.best.avail + pool.credited + earnedNow && budget <= pool.total + earnedNow)
return json(res, 400, { error: 'Your credits are spread across ' + pool.per.length + ' positions and one campaign spends from one of them. The largest single position holds ' + pool.best.avail + ' credits: set the budget to that or less, or run two campaigns.' });
const r = await ads.createCampaign(s.email, fundId, b, ids);
return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/campaigns\/(\d+)\/topup$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const memberId = await auth.refreshMemberId(s);
const b = await readBody(req);
const positions = [memberId, ...(await accounts.positions(s.email).catch(() => [])).map(x => x.memberId)].filter(Boolean);
const r = await ads.topUpCampaign(s.email, memberId, m[1], b.credits, { positions, switchTo: Number(b.switchTo) || 0 });
return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/campaigns\/(\d+)\/extend$/.exec(p); // featured links: book more days (flat, charged now)
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const memberId = await auth.refreshMemberId(s);
const b = await readBody(req);
const r = await ads.extendFeatured(s.email, memberId, m[1], b.days);
return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/campaigns\/(\d+)\/(archive|unarchive)$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = m[2] === 'archive' ? await ads.archive(s.email, m[1]) : await ads.unarchive(s.email, m[1]);
return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/campaigns\/(\d+)\/(pause|resume)$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await ads.setStatus(s.email, m[1], m[2] === 'pause' ? 'paused' : 'active');
return json(res, r.error ? 400 : 200, r);
}
// prepaid login-ad line (2026-10-23): cancel a reservation before it starts (full refund), or edit it for free
m = /^\/api\/my\/campaigns\/(\d+)\/cancel-reservation$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await ads.cancelLoginReservation(s.email, m[1]);
return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/campaigns\/(\d+)\/edit-reservation$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
if (b.targetUrl !== undefined) {
const t = String(b.targetUrl || '').trim();
{ const sb = await sbcheck.check(t); if (!sb.ok) return json(res, 400, { error: sb.reason }); }
{ const rc = await reach.check(t); if (!rc.ok) return json(res, 400, { error: rc.reason }); }
}
if (b.imageUrl) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); }
const r = await ads.editLoginReservation(s.email, m[1], b);
return json(res, r.error ? 400 : 200, r);
}
// -- admin portal: email magic-code sign-in, allowlisted to ADMIN_EMAIL
if (p === '/api/admin/auth/start' && req.method === 'POST') {
const b = await readBody(req);
const e = String(b.email || '').trim().toLowerCase();
if (!ADMIN_EMAIL) return json(res, 503, { error: 'ADMIN_EMAIL is not set on the server.' });
if (!e || e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' });
const k = 'admin:' + e;
const prev = emailCodes.get(k);
if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' });
const code = String(Math.floor(100000 + Math.random() * 900000));
emailCodes.set(k, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 });
if (mailer.hasKey()) {
try { await mailer.sendCode(e, code); } catch (err) {
console.error('admin sendCode failed', err.message);
return json(res, 502, { error: 'Could not send the email. Try again in a minute.' });
}
return json(res, 200, { ok: true, sent: true });
}
if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code });
return json(res, 503, { error: 'Email sign-in is not configured yet.' });
}
if (p === '/api/admin/auth/verify' && req.method === 'POST') {
const b = await readBody(req);
const e = String(b.email || '').trim().toLowerCase();
const k = 'admin:' + e;
const rec = emailCodes.get(k);
if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' });
rec.tries += 1;
if (rec.tries > 6) { emailCodes.delete(k); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); }
if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' });
emailCodes.delete(k);
if (e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' });
const token = mintAdminSession(e);
return json(res, 200, { ok: true, email: e }, { 'Set-Cookie': adminCookie(token) });
}
if (p === '/api/admin/auth/logout' && req.method === 'POST') {
dropAdminSession(req);
return json(res, 200, { ok: true }, { 'Set-Cookie': clearAdminCookie() });
}
if (p === '/api/admin/me' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 200, { admin: false });
return json(res, 200, { admin: true, email: ADMIN_EMAIL });
}
// -- level-4 override (2026-10-17 dry run, payer 2026-10-23): ?week=YYYY-MM-DD (any day in the week) or ?from=&to= (ms); rows=1 adds
// every purchase. The answer carries the week's payout status (not planned / planning / planned / paying / held / paid, rows
// pending / sending / sent / paid / carried / rolled / review / failed) and the payer state (mode, ready, address, balance).
if (p === '/api/admin/override' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const from = Number(u.searchParams.get('from')), to = Number(u.searchParams.get('to'));
const r = from && to ? await override.report(from, to) : await override.week(u.searchParams.get('week') || '');
if (u.searchParams.get('rows') !== '1') delete r.rows;
r.payer = await override.payerStatus().catch(e => ({ error: e.message }));
r.dueWeeks = override.dueWeeks(true).slice(-8).map(w => override.weekStatus(w));
return json(res, 200, r, { 'Cache-Control': 'no-store' });
}
// "pay this week now": only when the live payer is ready; settles every closed week up to the one asked, in order
if (p === '/api/admin/override/pay' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const live = override.liveState(); if (!live.ready) return json(res, 400, { error: 'The payer is off: ' + live.why.join('; ') });
const b = await readBody(req); const wk = /^\d{4}-\d{2}-\d{2}$/.test(String(b.week || '')) ? String(b.week) : '';
return json(res, 200, await override.payDue({ force: true, week: wk || undefined }));
}
// a stuck row (review / failed): 'carry' after checking the payer wallet shows nothing went out, or 'paid' with the verified tx
if (p === '/api/admin/override/resolve' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = await override.resolve(String(b.week || ''), Number(b.memberId), String(b.action || ''), String(b.tx || ''));
return json(res, r && r.error ? 400 : 200, r);
}
// -- help desk, admin side (2026-10-16): the Support pane
if (p === '/api/admin/support/telegram/register' && req.method === 'POST') { // point @CTBTickets_bot's webhook at this server
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await supportbot.register('https://instantadpay.com/api/telegram/support'));
}
if (p === '/api/admin/support' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, Object.assign(await tickets.adminList({ status: u.searchParams.get('status'), platform: u.searchParams.get('platform'), category: u.searchParams.get('category'), q: u.searchParams.get('q') }),
{ categories: tickets.CATEGORIES, platforms: tickets.PLATFORMS }));
}
if (p === '/api/admin/support/counts' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await tickets.counts());
}
if (p === '/api/admin/support/templates' && (req.method === 'GET' || req.method === 'PUT')) {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const read = () => { const v = siteConfig().supportTemplates; let a = v; if (typeof v === 'string') { try { a = JSON.parse(v); } catch (e) { a = null; } } return Array.isArray(a) && a.length ? a : tickets.DEFAULT_TEMPLATES; };
if (req.method === 'GET') return json(res, 200, { templates: read() });
const b = await readBody(req);
const list = (Array.isArray(b.templates) ? b.templates : []).map(t => ({ name: String((t && t.name) || '').trim().slice(0, 60), body: String((t && t.body) || '').trim().slice(0, 3000) })).filter(t => t.name && t.body).slice(0, 30);
const cur = siteConfig(); cur.supportTemplates = list; fs.writeFileSync(SITE_FILE, JSON.stringify(cur, null, 2));
return json(res, 200, { ok: true, templates: read() });
}
// -- the assistant's knowledge base (2026-10-20, kb.js): Admin > Knowledge base, and "Save as KB entry" on a ticket reply
if (p === '/api/admin/kb' && (req.method === 'GET' || req.method === 'POST')) {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
if (req.method === 'GET') return json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }, { 'Cache-Control': 'no-store' });
const r = await kb.create(await readBody(req));
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/kb/test' && req.method === 'POST') { // which entry would answer this question, and what would ride along to the AI
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
return json(res, 200, await kb.test(b.question));
}
m = /^\/api\/admin\/kb\/([a-z0-9-]{1,64})$/.exec(p);
if (m) {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
if (req.method === 'GET') { const e = await kb.get(m[1]); return e ? json(res, 200, { entry: e }) : json(res, 404, { error: 'Entry not found.' }); }
if (req.method === 'PUT') { const r = await kb.update(m[1], await readBody(req)); return json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); }
if (req.method === 'DELETE') { const r = await kb.remove(m[1]); return json(res, r.error ? 404 : 200, r); }
return json(res, 405, { error: 'method' });
}
m = /^\/api\/admin\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p);
if (m) {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const t = await tickets.byRef(m[1]);
if (!t) return json(res, 404, { error: 'Ticket not found.' });
if (m[2] && req.method === 'POST') { const b = await readBody(req); const r = await tickets.addMessage(t.id, { author: 'admin', body: b.body, internal: !!b.internal, status: b.status, attachments: b.attachments }); if (r.error) return json(res, 400, r); }
else if (!m[2] && req.method === 'PATCH') { const r = await tickets.setFields(t.id, await readBody(req)); if (r.error) return json(res, 400, r); }
else if (m[2] || req.method !== 'GET') return json(res, 405, { error: 'method' });
const v = await tickets.adminView(t.id);
const a = await accounts.byEmail(v.ticket.email);
v.requester = a ? { member: true, email: a.email, username: a.username || '', memberId: a.memberId || 0, wallet: !!a.address, created: a.created || 0, lastSeen: a.lastSeen || 0 } : { member: false, email: v.ticket.email };
return json(res, 200, v);
}
// -- Refuel Kit admin: kits as data (month, theme, five base images), placeholder art from public/banners, personalization preview
if (p === '/api/admin/kits' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, { kits: kit.listKits(), sizes: kit.ORDER }); }
if (p === '/api/admin/kits' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const r = kit.saveKit(await readBody(req)); return json(res, r.error ? 400 : 200, r); }
if (p === '/api/admin/kits/placeholder' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, kit.usePlaceholder(String(b.month || ''))); }
if (p === '/api/admin/kits/upload' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
let buf; try { buf = await readRaw(req, 3 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large (3 MB max).' }); }
const r = kit.uploadBase(String(u.searchParams.get('month') || ''), String(u.searchParams.get('size') || ''), buf, req.headers['content-type']);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/kits/preview' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await kit.preview(String(u.searchParams.get('month') || ''), String(u.searchParams.get('size') || ''), String(u.searchParams.get('username') || 'yourname').replace(/[^a-z0-9_]/gi, '').slice(0, 24), u.searchParams.get('variant') === 'gif' ? 'gif' : 'still');
if (r.error) return json(res, 400, r);
res.writeHead(200, { 'Content-Type': { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[r.ext], 'Cache-Control': 'no-store' }); return fs.createReadStream(r.file).pipe(res);
}
if (p === '/api/admin/refuel' && req.method === 'GET') { // Monthly Refuel: settings, members on a streak, grants by kind, recent outbox rows
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refuel.stats());
}
if (p === '/api/admin/refuel/tick' && req.method === 'POST') { // run the daily pass now (misses, reminders, outbox)
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refuel.tick());
}
if (p === '/api/admin/refuel/member' && req.method === 'GET') { // one member's card, as they see it
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refuel.view(String(u.searchParams.get('email') || '')));
}
if (p === '/api/admin/refill' && req.method === 'GET') { // who was told their ads ran out, and what they did next
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, refill.stats());
}
if (p === '/api/admin/refill/reset' && req.method === 'POST') { // re-decide conversions under a corrected rule
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
return json(res, 200, refill.resetConversions(Array.isArray(b.kinds) ? b.kinds : null));
}
if (p === '/api/admin/refill/run' && req.method === 'POST') { // send the next batch now instead of waiting for the tick
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refill.tick());
}
if (p === '/api/admin/overview' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const camps = await ads.adminList();
const byStatus = {}, byType = {};
for (const c of camps) { byStatus[c.status] = (byStatus[c.status] || 0) + 1; byType[c.type] = (byType[c.type] || 0) + 1; }
let memberCount = null; try { memberCount = await chain.memberCount(); } catch (e) {}
const cc = chain.getConfig();
let bixLinks = 0; try { bixLinks = (await accounts.listAll(100000)).filter(a => a.bixPartnerLink).length; } catch (e) {} // members with a BixPay partner link (2026-10-29)
return json(res, 200, { accounts: await accounts.count(), memberCount, campaigns: camps.length, bixLinks, bixpayLive: bixpay.live(),
house: camps.filter(c => c.house).length, byStatus, byType,
openReports: await reports.openCount(), pendingBurns: (await ads.pendingBurns()).length,
followups: await drip.stats(),
chain: { contract: cc.contract, chainId: cc.chainId, chainName: cc.chainName, explorer: cc.explorer },
site: siteConfig(), rates: ads.rates() });
}
if (p === '/api/admin/members' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const members = await accounts.listAll(5000, { shells: true }); // waiting LinkSpin accounts included (2026-10-15); was 500: older members (igor147, joined 09-12) vanished from the table and its search once the site passed 500 accounts (Marty, 2026-09-29)
// resolve each sponsor token (username, share code or member #) to the sponsor's name
// the lookup covers EVERY account, not the page's slice: built from `members` it called every
// sponsor who joined before the newest 500 a dead link (144 of them, Marty 2026-09-23)
const byTok = {};
for (const m of await accounts.identities()) for (const t of [m.username, m.code, m.memberId ? String(m.memberId) : null]) if (t) byTok[String(t).toLowerCase()] = m;
for (const m of members) {
const t = String(m.sponsorRef || '').toLowerCase();
const sp = t ? byTok[t] : null;
m.sponsorName = sp ? (sp.username ? '@' + sp.username : (sp.memberId ? 'member #' + sp.memberId : sp.email)) : null;
m.sponsorVia = sp ? (t === String(sp.username || '').toLowerCase() ? 'username' : t === String(sp.code || '').toLowerCase() ? 'code' : 'member #') : (t ? 'unresolved' : '');
}
for (const m of members) { try { const ps = await accounts.positions(m.email); m.positions = ps.length; m.positionIds = ps.map(p => p.memberId).filter(Boolean); } catch (e) { m.positions = 0; } }
for (const m of members) { try { const sg = await fraud.get(m.email); m.flags = sg ? sg.flags : []; m.suspended = !!(sg && sg.suspended); m.lastIp = sg ? sg.lastIp : ''; } catch (e) { m.flags = []; m.suspended = false; } }
return json(res, 200, { members });
}
if (p === '/api/admin/members' && req.method === 'PATCH') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
if (!b.email) return json(res, 400, { error: 'Which member?' });
if (b.suspend !== undefined) { // anti-fraud switch: suspended accounts cannot sign in; flags keep them off the leaderboard and out of adoptions
if (b.suspend) await fraud.suspend(b.email, b.reason || 'duplicate account'); else await fraud.unsuspend(b.email);
if (b.flags) await fraud.addFlags(b.email, [].concat(b.flags));
return json(res, 200, { ok: true, signals: await fraud.get(b.email) });
}
if (b.flags !== undefined) { const f = b.flags === null ? (await fraud.clearFlags(b.email), []) : await fraud.addFlags(b.email, [].concat(b.flags)); return json(res, 200, { ok: true, flags: f }); }
const r = await follow.setDeliberate(b.email, b.sponsorRef, 'admin', 'admin members table'); // deliberate: follows to LinkSpin until bound
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/fraud' && req.method === 'GET') { // duplicate signals: shared browsers / IPs, flagged and suspended accounts
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, Object.assign(await fraud.report(), { allow: fraud.allowList(), block: fraud.blockList() }));
}
// Approved exceptions: people Marty has okayed to hold more than one account. Adding an
// address here stops the duplicate checks blocking or hard-flagging them, and stops them
// being dropped from the leaderboard or barred from adopting.
if (p === '/api/admin/fraud/block' && req.method === 'POST') {
const b = await readBody(req);
const r = b.remove ? fraud.blockRemove(b.email) : fraud.blockAdd(b.email, b.note, ADMIN_EMAIL || 'admin');
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/fraud/allow' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = b.remove ? fraud.allowRemove(b.email) : fraud.allowAdd(b.email, b.note, ADMIN_EMAIL || 'admin');
if (r.error) return json(res, 400, r);
console.log('fraud exception ' + (b.remove ? 'removed' : 'added') + ': ' + String(b.email || '').replace(/^(.).*(@.*)$/, '$1***$2'));
return json(res, 200, r);
}
// stop a member's campaign for good (2026-10-04, Marty: Shift AI closed, stop its ads): pause it on every rail, then archive it.
// Reserved budget is computed from active/paused campaigns, so archiving releases the unspent remainder to the member at
// once; flat up-front buys (visit packs) are refunded separately through /api/admin/member grantCredits.
if (p === '/api/admin/campaign/stop' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const c = await ads.campaignById(Number(b.id)); if (!c) return json(res, 404, { error: 'No such campaign.' });
const owner = c.owner || c.ownerEmail || c.owner_email;
if (c.status === 'active') { const r = await ads.setStatus(owner, c.id, 'paused'); if (r && r.error) return json(res, 400, r); }
const a = (c.status === 'archived') ? { ok: true, already: true, freed: 0 } : await ads.archive(owner, c.id);
console.log('admin stop campaign', c.id, owner, String(b.reason || '').slice(0, 80), JSON.stringify({ freed: a.freed }));
return json(res, a.error ? 400 : 200, Object.assign({ id: c.id, owner }, a));
}
if (p === '/api/admin/login-queue' && req.method === 'GET') { // the prepaid login-ad line, oldest paid first (2026-10-23)
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await ads.adminLoginQueue());
}
m = /^\/api\/admin\/login-queue\/(\d+)\/cancel$/.exec(p);
if (m && req.method === 'POST') { // admin cancel = the same full refund the owner would get
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await ads.cancelLoginReservation(null, m[1], { admin: true });
if (!r.error) console.log('admin cancelled login reservation', r.id, String(r.owner || '').replace(/^(.).*(@.*)$/, '$1***$2'), 'refunded', r.refunded);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/campaigns' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { campaigns: await ads.adminList(), rates: ads.rates(), bannerSizes: ads.bannerSizes(), houseOwner: ads.HOUSE_OWNER });
}
if (p === '/api/admin/campaigns' && req.method === 'POST') { // free house ad
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
// A house video was never checked: videoCheck guarded the member path only, so a bad
// source pasted here would hand every viewer a black player exactly as #146 did.
if (String(b.type) === 'video') { const vc = await videoCheck(b.videoUrl); if (!vc.ok) return json(res, 400, { error: vc.reason }); }
{ const sb = await sbcheck.check(b.targetUrl); if (!sb.ok) return json(res, 400, { error: sb.reason }); }
{ const rc = await reach.check(b.targetUrl); if (!rc.ok) return json(res, 400, { error: rc.reason }); }
if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) {
if (b.type === 'banner' || (b.type === 'login' && b.imageUrl)) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); }
const fc = await frameCheck(b.targetUrl);
if (!fc.ok) return json(res, 400, { error: fc.reason });
}
const r = await ads.createHouseCampaign(b);
return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/admin\/campaigns\/(\d+)\/(pause|resume)$/.exec(p);
if (m && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await ads.adminSetStatus(m[1], m[2] === 'pause' ? 'paused' : 'active');
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/audit' && req.method === 'GET') { // counters reconciled against delivery logs
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await audit.run());
}
if (p === '/api/admin/sponsor-resolve' && req.method === 'GET') { // support: where would a buy under ?ref= land right now?
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const ref = String(u.searchParams.get('ref') || '').trim();
const detailed = await resolveSponsorDetailed(ref);
const walk = detailed.reason === 'notActivated' ? await walkUpActivatedSponsor(ref) : null;
return json(res, 200, { ref, detailed, walk, catchId: Number(siteConfig().defaultSponsorId) || 1 });
}
if (p === '/api/admin/trace' && req.method === 'GET') { // payment trace for any member
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const who = String(u.searchParams.get('who') || '').trim().replace(/^[@#]/, '').toLowerCase();
let target = /^\d+$/.test(who) ? Number(who) : 0;
if (!target && who) { let a = await accounts.byUsername(who); if (!a) a = await accounts.byCode(who); if (!a && who.includes('@')) a = await accounts.byEmail(who); if (a && a.memberId) target = a.memberId; }
if (!target) return json(res, 400, { error: 'No activated member matches "' + who.slice(0, 40) + '".' });
return json(res, 200, await tracePurchases(target, 60));
}
if (p === '/api/admin/chain/rescan' && req.method === 'POST') { // rebuild the full event history from the deploy block
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await chain.rescan());
}
if (p === '/api/admin/chain/status' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { events: chain.eventCount(), historyComplete: chain.historyComplete(), totals: chain.totals() });
}
if (p === '/api/admin/reports' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { reports: await reports.list(200) });
}
m = /^\/api\/admin\/reports\/(\d+)\/resolve$/.exec(p);
if (m && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await reports.resolve(m[1]));
}
if (p === '/api/admin/upload' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return handleUpload(req, res, 'admin');
}
if (p === '/api/admin/rates' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { rates: ads.rates() });
}
if (p === '/api/admin/drip' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { sequence: drip.sequence(), defaults: drip.DEFAULT_SEQUENCE, stats: await drip.stats(), mailReady: mailer.hasKey() });
}
if (p === '/api/admin/drip' && req.method === 'PATCH') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = b.reset ? drip.resetSequence() : drip.setSequence(b.sequence);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/drip/test' && req.method === 'POST') { // send one step to the admin inbox
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
if (!ADMIN_EMAIL) return json(res, 400, { error: 'ADMIN_EMAIL is not set.' });
if (!mailer.hasKey()) return json(res, 400, { error: 'No mail key on the server.' });
try { const r = await drip.sendStep(ADMIN_EMAIL, Number(b.step) || 0, ADMIN_EMAIL); return json(res, r.error ? 400 : 200, r); }
catch (e) { return json(res, 502, { error: 'Send failed: ' + e.message }); }
}
// wall fallback ads: shown in wall positions a member has not earned or filled, when no upline banner exists
if (p === '/api/admin/wall-ads' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
let saved = null; try { saved = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); } catch (e) {}
return json(res, 200, { ads: Array.isArray(saved) ? saved : [], defaults: getAdminWallAds(), usingDefaults: !Array.isArray(saved) || !saved.length });
}
if (p === '/api/admin/wall-ads' && req.method === 'PATCH') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const src = Array.isArray(b.ads) ? b.ads.slice(0, 20) : [];
const out = [];
for (const o of src) {
const name = String((o && o.name) || '').trim().slice(0, 60);
const targetUrl = String((o && o.targetUrl) || '').trim();
const bannerUrl = String((o && o.bannerUrl) || '').trim();
if (!targetUrl) continue;
if (!/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Every wall ad needs an https:// link (' + (name || targetUrl) + ').' });
if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL (' + (name || targetUrl) + ').' });
out.push({ name: name || 'InstantAdPay', targetUrl, bannerUrl: bannerUrl || null });
}
const file = path.join(DATA_DIR, 'admin-wall-ads.json');
if (out.length) fs.writeFileSync(file, JSON.stringify(out, null, 2)); else { try { fs.unlinkSync(file); } catch (e) {} }
return json(res, 200, { ok: true, ads: out, usingDefaults: !out.length });
}
// -- growth snapshot: preview the post, or send it now
if (p === '/api/admin/snapshot' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { text: await snapshot.preview() });
}
if (p === '/api/admin/snapshot/send' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await snapshot.post(); return json(res, r.error ? 400 : 200, r);
}
// -- 1,000-member drop: view, mode (off|dry|armed via site config), snapshot now, pay now, resend the missed-it notices, reset (only before any payment)
if (p === '/api/admin/milestone') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
if (req.method === 'GET') return json(res, 200, await milestone.view());
const b = await readBody(req); const act = String(b.action || '');
if (act === 'mode') { const m = ['off', 'dry', 'armed'].includes(b.mode) ? b.mode : 'off'; const cur = siteConfig(); fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, { milestoneMode: m }, b.target ? { milestoneTarget: Number(b.target) } : {}, b.pol ? { milestonePol: Number(b.pol) } : {}), null, 2)); return json(res, 200, await milestone.view()); }
if (act === 'snapshot') { await milestone.snapshot(!!b.force); return json(res, 200, await milestone.view()); }
if (act === 'recheck') { await milestone.recheck(); return json(res, 200, await milestone.view()); }
if (act === 'pay') { const r = await milestone.pay(); return json(res, 200, Object.assign({ result: r }, await milestone.view())); }
if (act === 'settle') { await milestone.settle(); return json(res, 200, await milestone.view()); }
if (act === 'notify-missed') { const r = await milestone.notifyMissed(); return json(res, 200, Object.assign({ result: r }, await milestone.view())); }
if (act === 'reset') { const v = await milestone.view(); if (v.paid || v.sent) return json(res, 400, { error: 'Payments exist; the record stays.' }); milestone.reset(); return json(res, 200, await milestone.view()); }
return json(res, 400, { error: 'Unknown action.' });
}
if (p === '/api/admin/site' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { site: siteConfig() });
}
// -- profit and loss from the chain index: volume, platform fees, member payouts,
// pass-ups, per period (by block: ~43,200 Polygon blocks a day), plus the fee
// wallets' live balances and an admin-entered fixed monthly cost
if (p === '/api/admin/pnl' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const hunt = await huntLedger(); // marketing spend that never touches this contract
let gamesAll = null; try { gamesAll = await gamestats.allTime(); } catch (e) { gamesAll = { error: e.message }; } // every game wallet's payouts, all time, from Polygon
const days = Math.max(0, Number(u.searchParams.get('days') || 30));
let latest = 0; try { latest = parseInt(await chain.rpc('eth_blockNumber', []), 16); } catch (e) {}
const fromBlock = days ? latest - Math.round(days * 43200) : 0;
const evs = chain.recentEvents(1e9).filter(e => !days || e.block >= fromBlock);
const sum = (list, f) => list.reduce((n, e) => n + BigInt(f(e) || '0'), 0n);
const pol = wei => Number(BigInt(wei) / 10n ** 12n) / 1e6; // 6-decimal POL, no float drift
const purchases = evs.filter(e => e.type === 'Purchase');
const tier = evs.filter(e => e.type === 'TierPaid');
const admin = evs.filter(e => e.type === 'AdminPaid');
const passed = evs.filter(e => e.type === 'PassedUp');
const byTier = {};
for (const t of [1, 2, 3]) byTier[t] = sum(tier.filter(e => e.tier === t), e => e.amountWei).toString();
const byPkg = {};
for (const e of purchases) { const k = '$' + Math.round(e.priceCents / 100); byPkg[k] = (byPkg[k] || 0) + 1; }
let polUsd = 0; try { const cat = await chain.catalog(); const pk = (cat.products || cat).find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {}
const wallets = { feeA: '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', feeB: '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', engine: burner.status().address || null };
const balances = {};
for (const [k, a] of Object.entries(wallets)) { if (!a) continue; try { balances[k] = BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { balances[k] = null; } }
return json(res, 200, { days, fromBlock, latest, polUsd,
purchases: { count: purchases.length, volumeWei: sum(purchases, e => e.paidWei).toString(), usdCents: purchases.reduce((n, e) => n + (e.priceCents || 0), 0), byPackage: byPkg },
platformWei: sum(admin, e => e.amountWei).toString(), memberPayoutsWei: sum(tier, e => e.amountWei).toString(), byTier,
passedUp: { count: passed.length, unqualified: passed.filter(e => e.reason === 'unqualified').length, sendFailed: passed.filter(e => e.reason === 'send-failed').length },
wallets, balances, fixedMonthlyUsd: Number(siteConfig().pnlFixedMonthlyUsd) || 0, burner: burner.status(), polhunter: hunt, gamesAll,
// hand-entered movements in and out of the receivers: draws the chain cannot explain, and
// outside income (a ClickBaitPays withdrawal, say) that is not an AdminPaid event
ledger: { entries: ledger.entries(), totals: ledger.totals('feeA'),
reconcile: ledger.reconcile(pol(sum(admin, e => e.amountWei)), pol(BigInt(balances.feeA || '0')), 'feeA') } });
}
// tax summary (2026-10-04, Marty: "show what I spent in advertising versus income" at tax time). Income = the platform's cut
// of every package sale (AdminPaid), valued in dollars at that sale's own price (Purchase.priceCents / paidWei in the same
// transaction), minus sales to Marty's own positions (site config ownMemberIds, default "1": his own money moving around is
// not income), plus outside revenue lines. Costs = ledger 'cost' lines by category. Draws and transfers are listed apart:
// they are owner money, not expenses. Dates are the blocks' REAL timestamps (2026-10-04: a 2-second-per-block
// estimate drifted weeks and put September sales in August), read once from the chain and kept in DATA_DIR/blocktimes.json.
if (p === '/api/admin/tax' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const year = String(Number(u.searchParams.get('year')) || new Date().getFullYear());
const own = new Set(String(siteConfig().ownMemberIds || '1').split(',').map(x => Number(x.trim())).filter(Boolean));
const evs = chain.recentEvents(1e9);
const bt = blockTimes(); const need = Array.from(new Set(evs.filter(e => e.type === 'AdminPaid' && !bt[e.block]).map(e => e.block)));
for (let i = 0; i < need.length; i += 8) await Promise.all(need.slice(i, i + 8).map(async blk => { try { const b = await chain.rpc('eth_getBlockByNumber', ['0x' + blk.toString(16), false]); if (b && b.timestamp) bt[blk] = parseInt(b.timestamp, 16) * 1000; } catch (e) {} }));
if (need.length) saveBlockTimes(bt);
const missing = evs.filter(e => e.type === 'AdminPaid' && !bt[e.block]).length;
if (missing) return json(res, 503, { error: missing + ' sale dates could not be read from the chain right now. Try again in a minute.' });
const dayOf = blk => new Date(bt[blk]).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const buys = new Map(); for (const e of evs) if (e.type === 'Purchase') buys.set(e.tx, e);
const months = {}; let incomeUsd = 0, incomePol = 0, ownUsd = 0, sales = 0;
for (const e of evs) {
if (e.type !== 'AdminPaid') continue; const day = dayOf(e.block); if (!day.startsWith(year)) continue;
const b = buys.get(e.tx); const pol = Number(BigInt(e.amountWei) / 10n ** 12n) / 1e6;
const usd = b && Number(b.paidWei) > 0 ? (Number(BigInt(e.amountWei) * 1000000n / BigInt(b.paidWei)) / 1e6) * (b.priceCents / 100) : 0;
if (own.has(Number(e.buyerId))) { ownUsd += usd; continue; }
incomeUsd += usd; incomePol += pol; sales++; const m = day.slice(0, 7); months[m] = months[m] || { incomeUsd: 0, costUsd: {} }; months[m].incomeUsd += usd;
}
const lines = ledger.entriesFor(year); let outsideUsd = 0; const costs = {}; const draws = []; const transfers = [];
for (const l of lines) {
const m = l.date.slice(0, 7); months[m] = months[m] || { incomeUsd: 0, costUsd: {} };
if (l.kind === 'revenue') { outsideUsd += l.usd; months[m].incomeUsd += l.usd; }
else if (l.kind === 'cost') { const c = l.category || 'other', v = l.dir === 'out' ? l.usd : -l.usd; costs[c] = (costs[c] || 0) + v; months[m].costUsd[c] = (months[m].costUsd[c] || 0) + v; }
else if (l.kind === 'draw') draws.push(l); else transfers.push(l);
}
const r2 = n => Math.round(n * 100) / 100, adPromo = (costs.advertising || 0) + (costs.games || 0) + (costs.rewards || 0), allCosts = Object.values(costs).reduce((n, v) => n + v, 0);
const csv = [['Section', 'Date', 'Category', 'Description', 'POL', 'USD', 'Transaction'].join(',')];
const q = v => '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"';
for (const e of evs) { if (e.type !== 'AdminPaid' || own.has(Number(e.buyerId))) continue; const day = dayOf(e.block); if (!day.startsWith(year)) continue; const b = buys.get(e.tx);
const usd = b && Number(b.paidWei) > 0 ? (Number(BigInt(e.amountWei) * 1000000n / BigInt(b.paidWei)) / 1e6) * (b.priceCents / 100) : 0;
csv.push(['Income', day, 'Platform share of package sale', 'Member #' + e.buyerId + (b ? ' bought the $' + Math.round(b.priceCents / 100) + ' package' : ''), (Number(BigInt(e.amountWei) / 10n ** 12n) / 1e6).toFixed(6), usd.toFixed(2), e.tx].map(q).join(',')); }
for (const l of lines) { const sec = l.kind === 'revenue' ? 'Income' : l.kind === 'cost' ? 'Expense' : l.kind === 'draw' ? 'Owner draw (not an expense)' : 'Transfer (not income or expense)';
csv.push([sec, l.date, l.kind === 'cost' ? (ledger.CATS[l.category] || l.category) : l.kind, l.note, (l.dir === 'out' ? -1 : 1) * l.amount, (l.kind === 'cost' && l.dir === 'out' ? -1 : 1) * l.usd, l.tx].map(q).join(',')); }
csv.push(''); csv.push(q('Sale dates are the Polygon block timestamps, in US Central time. Sales to your own positions (' + Array.from(own).join(', ') + ') are left out. USD values are each sale\'s own package price.'));
return json(res, 200, { year, ownMemberIds: Array.from(own),
income: { platformUsd: r2(incomeUsd), platformPol: Math.round(incomePol * 1e4) / 1e4, sales, outsideUsd: r2(outsideUsd), totalUsd: r2(incomeUsd + outsideUsd), ownSalesExcludedUsd: r2(ownUsd) },
expenses: { byCategory: Object.fromEntries(Object.entries(costs).map(([k, v]) => [k, r2(v)])), labels: ledger.CATS, advertisingAndPromotionUsd: r2(adPromo), totalUsd: r2(allCosts) },
netUsd: r2(incomeUsd + outsideUsd - allCosts), draws: draws.length, transfers: transfers.length,
months: Object.fromEntries(Object.keys(months).sort().map(k => [k, { incomeUsd: r2(months[k].incomeUsd), costUsd: r2(Object.values(months[k].costUsd).reduce((n, v) => n + v, 0)) }])),
csv: csv.join('\n') });
}
if (p === '/api/admin/ledger' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = ledger.put(b);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/ledger/delete' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = ledger.remove(String(b.id || ''));
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/videosweep' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
return json(res, 200, await videosweep.run({ dry: !!b.dry }));
}
if (p === '/api/admin/sbcheck' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
return json(res, 200, await sbcheck.run({ dry: !!b.dry }));
}
if (p === '/api/admin/burner' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, burner.status());
}
if (p === '/api/admin/burner/run' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await burner.tick());
}
// -- admin (Bearer ADMIN_PASSWORD, or the /admin portal session)
if (p === '/api/admin/burns' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { pending: await ads.pendingBurns() });
}
if (p === '/api/admin/burns/mark' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = await ads.markBurned(b.id, b.tx);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/rates' && req.method === 'PATCH') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
return json(res, 200, { ok: true, rates: ads.setRates(b) });
}
if (p === '/api/admin/site' && req.method === 'PATCH') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const cur = siteConfig();
if (b.bixCompanyLink !== undefined && String(b.bixCompanyLink || '').trim()) { const v = bixpay.validate(b.bixCompanyLink); if (!v.ok) return json(res, 400, { error: 'bixCompanyLink: ' + v.error }); b.bixCompanyLink = v.link; }
if (String(b.bixpayLive) === '1' && String(cur.bixpayLive) !== '1' && !String(cur.bixpayLiveSince || '').trim()) b.bixpayLiveSince = new Date().toISOString(); // the Overview announcement runs a week from the flip
fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, b), null, 2));
return json(res, 200, { ok: true, site: siteConfig() });
}
if (p === '/api/admin/chain' && req.method === 'PATCH') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const file = path.join(DATA_DIR, 'config.json');
let cur = {}; try { cur = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) {}
fs.writeFileSync(file, JSON.stringify(Object.assign(cur, b), null, 2));
chain.reloadConfig();
return json(res, 200, { ok: true, config: chain.getConfig() });
}
// -- pages (HEAD answered like GET so link previewers and crawlers see 200; Node drops the body)
if (req.method === 'GET' || req.method === 'HEAD') {
if (p === '/') {
// arrived from PolHunter: remember it for 30 days so the dashboard can send them back once a wallet is linked
if (u.searchParams.get('from') === 'polhunter') { res.writeHead(302, { Location: '/', 'Set-Cookie': 'iap.return=polhunter; Path=/; SameSite=Lax; Max-Age=' + (30 * 24 * 3600) + (IS_PROD ? '; Secure' : ''), 'Cache-Control': 'no-store' }); return res.end(); }
return sendFile(res, path.join(PUBLIC_DIR, 'index.html'));
}
if (p === '/ledger') return sendFile(res, path.join(PUBLIC_DIR, 'ledger.html'));
if (p === '/contract') return sendFile(res, path.join(PUBLIC_DIR, 'contract.html'));
if (p === '/terms') return sendFile(res, path.join(PUBLIC_DIR, 'terms.html'));
if (p === '/privacy') return sendFile(res, path.join(PUBLIC_DIR, 'privacy.html'));
if (p === '/disclaimer') return sendFile(res, path.join(PUBLIC_DIR, 'disclaimer.html'));
if (p === '/facts') return sendFile(res, path.join(PUBLIC_DIR, 'facts.html')); // verified platform facts (2026-10-06), linked from every footer
if (p === '/llms.txt') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(fs.readFileSync(path.join(PUBLIC_DIR, 'llms.txt'))); }
if (p === '/my') return sendFile(res, path.join(PUBLIC_DIR, 'my.html'));
if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html'));
if (p === '/shorts') return sendFile(res, path.join(PUBLIC_DIR, 'shorts.html'));
if (p === '/plays') return sendFile(res, path.join(PUBLIC_DIR, 'plays.html'));
if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12)
if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html'));
if (p === '/games') return sendFile(res, path.join(PUBLIC_DIR, 'games.html'));
if (p === '/presentation') return sendFile(res, path.join(PUBLIC_DIR, 'presentation.html')); // narrated Build Wide presentation, captions in 6 languages (2026-10-15) // public games list (2026-10-10) // member guide: how earning works (2026-09-12)
// -- badge share page + image: /b/<username>/<key> (OG preview = the member's composed badge) (Marty, 2026-09-13)
m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)\.jpg$/.exec(p);
if (m) return sendFile(res, path.join(UPLOADS_DIR, 'badge-' + m[1] + '-' + m[2] + '.jpg'));
m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)$/i.exec(p);
if (m) {
const un = m[1].toLowerCase(), key = m[2];
const a = await accounts.byUsername(un);
const file = path.join(UPLOADS_DIR, 'badge-' + un + '-' + key + '.jpg');
if (!a || !fs.existsSync(file) || !(await ads.milestonesOf(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
const [label, sub] = BADGE_META[key];
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const url = 'https://instantadpay.com/b/' + un + '/' + key, img = 'https://instantadpay.com/badge-img/' + un + '/' + key + '.jpg';
const title = '@' + un + ' unlocked ' + label + ' on InstantAdPay';
const desc = label + ': ' + sub + '. InstantAdPay pays sponsors in the same transaction, on-chain. Join @' + un + '\u2019s line free.';
const html = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + esc(title) + '</title>'
+ '<meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="' + url + '"><meta name="robots" content="noindex">'
+ '<meta property="og:type" content="website"><meta property="og:site_name" content="InstantAdPay"><meta property="og:title" content="' + esc(title) + '"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:url" content="' + url + '"><meta property="og:image" content="' + img + '"><meta property="og:image:width" content="1024"><meta property="og:image:height" content="1024">'
+ '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' + esc(title) + '"><meta name="twitter:description" content="' + esc(desc) + '"><meta name="twitter:image" content="' + img + '">'
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap"><link rel="stylesheet" href="/assets/site.css?v=20260913a">'
+ '<style>.bp{max-width:560px;text-align:center;padding:40px 16px 60px}.bp img{width:100%;max-width:520px;border-radius:18px;border:1px solid var(--line);box-shadow:0 20px 60px rgba(0,0,0,.45)}.bp h1{font-size:clamp(24px,5vw,34px);margin:22px 0 8px}.bp p{color:var(--muted);max-width:44ch;margin:0 auto 20px}</style></head>'
+ '<body><div class="wrap bp"><img src="' + img + '" alt="' + esc(label) + ' badge for @' + esc(un) + '"><h1>@' + esc(un) + ' unlocked <em>' + label + '</em></h1><p>' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On InstantAdPay every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.</p>'
+ '<a class="btn" href="/join/' + esc(un) + '">Join @' + esc(un) + '\u2019s line free</a><p class="small" style="margin-top:26px">Advertising with a performance referral program. Not an investment; no income is guaranteed.</p></div>'
+ '<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }));
return res.end(html);
}
// -- blog: server-rendered so crawlers get real HTML + metadata (Marty, 2026-09-12)
if (p === '/blog' || p === '/blog/' || /^\/blog\/page\/\d+$/.test(p) || /^\/blog\/tag\/[^/]+$/.test(p)) {
const posts = await blog.listPublished();
const pg = (m = /^\/blog\/page\/(\d+)$/.exec(p)) ? Number(m[1]) : 1;
const tag = (m = /^\/blog\/tag\/([^/]+)$/.exec(p)) ? decodeURIComponent(m[1]).toLowerCase() : null;
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }));
return res.end(blog.renderIndex(posts, pg, tag));
}
m = /^\/handout\/([a-z0-9_]{3,20})$/i.exec(p);
if (m) { const h = await toolkit.handout(m[1].toLowerCase()); if (!h) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); return res.end(h); }
if (p === '/leaderboard') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=60' })); return res.end(await leaderboard.renderPage()); }
if (p === '/whats-new') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=120' })); return res.end(releases.renderPage()); }
if (p === '/blog/feed.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/rss+xml; charset=utf-8', 'Cache-Control': 'public, max-age=900' })); return res.end(blog.rss(await blog.listPublished())); }
if (p === '/sitemap.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.sitemap(await blog.listPublished())); }
if (p === '/robots.txt') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.robots()); }
m = /^\/blog\/([a-z0-9-]{1,80})$/.exec(p);
if (m) {
const post = await blog.get(m[1]);
const preview = !!(post && post.status !== 'published' && isAdmin(req)); // admins can open a draft at its real URL
if (!post || (post.status !== 'published' && !preview)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8' })); return res.end(blog.renderIndex(await blog.listPublished(), 1, null).replace('<title>', '<title>Not found | ')); }
if (!preview && req.method === 'GET') blog.bumpViews(post.slug);
const related = blog.relatedFor(post, await blog.listPublished());
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': preview ? 'no-store' : 'public, max-age=300' }));
return res.end(blog.renderPost(post, related));
}
if (p === '/wallets') return sendFile(res, path.join(PUBLIC_DIR, 'wallets.html'));
if (p === '/support' || /^\/support\/t\/[A-Za-z0-9_.-]{20,80}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'support.html')); // help desk (2026-10-16): the form, and the private ticket link
if (p === '/friday') return sendFile(res, path.join(PUBLIC_DIR, 'friday.html'));
if (p === '/wednesday') return sendFile(res, path.join(PUBLIC_DIR, 'wednesday.html'));
if (p === '/conversion-tracking') return sendFile(res, path.join(PUBLIC_DIR, 'conversion-tracking.html')); // how to set up the conversion pixel, the member guide (2026-10-24)
if (p === '/bixpay') { if (!bixpay.live()) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } return sendFile(res, path.join(PUBLIC_DIR, 'bixpay.html')); } // the BixPay card guide (2026-10-29), public once bixpayLive is on
// counted BixPay click: every surface links here; resolves the member's link (own > sponsor chain > network) and 302s to it
if (p === '/go/bixpay') {
if (!bixpay.live()) { res.writeHead(302, baseHeaders({ Location: '/' })); return res.end(); }
const surface = String(u.searchParams.get('s') || 'other').trim().toLowerCase().slice(0, 12);
const tok = String(u.searchParams.get('m') || '').trim().toLowerCase().slice(0, 40);
let acct = null; try { if (tok) acct = await refAccount(tok); if (!acct) { const s = await auth.fromRequest(req); if (s && s.email) acct = await accounts.byEmail(s.email); } if (!acct) { const ck = String(parseCookies(req)['iap.sponsor'] || '').trim().toLowerCase(); if (ck) acct = await refAccount(ck); } } catch (e) { acct = null; }
const r = await bixpay.resolve(acct);
if (!BOT_UA.test(String(req.headers['user-agent'] || ''))) bixpay.click(surface, acct ? acct.email : null);
res.writeHead(302, baseHeaders({ Location: r.link, 'Cache-Control': 'no-store' })); return res.end();
}
if (p === '/refuel') return sendFile(res, path.join(PUBLIC_DIR, u.searchParams.has('t') ? 'refuel.html' : 'refuel-guide.html')); // ?t=<token>: the games' refuel visit (2026-09-30); no token: the Fuel Your Offers member guide (2026-10-24)
if (p === '/door') return sendFile(res, path.join(PUBLIC_DIR, 'door.html')); // Spooky Doors door visit (2026-10-02)
// per-partner kit pages (Marty, 2026-09-29): /partners/<slug> serves public/kits/<slug>.html, one file per reviewer or site owner
{ const mk = p.match(/^\/partners\/([a-z0-9-]{2,40})$/); if (mk) { const f = path.join(PUBLIC_DIR, 'kits', mk[1] + '.html'); if (fs.existsSync(f)) return sendFile(res, f); } }
if (p === '/plan-lab') return sendFile(res, path.join(PUBLIC_DIR, 'plan-lab.html')); // Reach Ladder simulator for Marty's planning group: unlisted, shared by link (2026-09-27)
if (p === '/launch') return sendFile(res, path.join(PUBLIC_DIR, 'launch.html'));
if (/^\/view\/[a-f0-9]{32}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'view.html'));
m = /^\/uploads\/([a-z0-9]{24}\.(?:png|jpg|webp|gif|mp4|webm))$/.exec(p);
if (m) return sendFile(res, path.join(UPLOADS_DIR, m[1]));
if (/^\/tx\/0x[0-9a-fA-F]{64}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'tx.html'));
m = /^\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p);
if (m) { // server-inject per-member OG tags so shared bio links preview correctly (crawlers don't run JS)
try {
const tok = m[1].toLowerCase();
let a = await accounts.byUsername(tok); if (!a) a = await accounts.byCode(tok);
// a deleted or never-seen name is a real 404, never a bare "Banner wall" page at 200 (a soft 404 Google kept indexed, 2026-10-30)
if (!a) {
const nf = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>No wall under that name | InstantAdPay</title><meta name="robots" content="noindex"><link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="/assets/site.css?v=20260911w"></head><body><section><div class="wrap" style="max-width:720px;text-align:center;padding:60px 0"><h1>No wall under that name</h1><p class="muted">This member page does not exist or was removed.</p><p><a class="btn" href="/">Go to InstantAdPay</a></p></div></section></body></html>';
res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Robots-Tag': 'noindex' }));
return res.end(nf);
}
let html = fs.readFileSync(path.join(PUBLIC_DIR, 'wall.html'), 'utf8');
if (a) {
const nm = a.username ? '@' + a.username : 'member #' + (a.memberId || 0);
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const bought = await hasBought(a); // only a paying member's avatar becomes the share image
const title = nm + '\u2019s ad wall | InstantAdPay';
const desc = esc(wallDescription(nm)); // fixed site sentence, never the bio (indexed snippet stays ours)
const img = bought && a.avatarUrl && /^https:/.test(a.avatarUrl) ? a.avatarUrl : 'https://instantadpay.com/banners/iap-hero-1200x630.png';
const url = 'https://instantadpay.com/wall/' + (a.username || a.code);
const og = [
'<meta property="og:type" content="profile">',
'<meta property="og:site_name" content="InstantAdPay">',
'<meta property="og:url" content="' + url + '">',
'<meta property="og:title" content="' + esc(title) + '">',
'<meta property="og:description" content="' + desc + '">',
'<meta property="og:image" content="' + esc(img) + '">',
'<meta name="twitter:card" content="summary_large_image">',
'<meta name="twitter:title" content="' + esc(title) + '">',
'<meta name="twitter:description" content="' + desc + '">',
'<meta name="twitter:image" content="' + esc(img) + '">',
'<meta name="description" content="' + desc + '">',
'<link rel="canonical" href="' + url + '">'
].join('\n');
html = html.replace('<title>Banner wall | InstantAdPay</title>', '<title>' + esc(title) + '</title>').replace('<!--OG-->', og);
}
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' }));
return res.end(html);
} catch (e) { return sendFile(res, path.join(PUBLIC_DIR, 'wall.html')); }
}
const safe = path.normalize(p).replace(/^([.\\/])+/, '');
const file = path.join(PUBLIC_DIR, safe);
if (file.startsWith(PUBLIC_DIR) && fs.existsSync(file) && fs.statSync(file).isFile()) return sendFile(res, file);
}
res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' }));
res.end('Not found');
} catch (e) {
console.error('request error', req.url, e.message);
try { json(res, 500, { error: 'server error' }); } catch (_) {}
}
});
boot().then(() => {
server.listen(PORT, () => console.log(`InstantAdPay site on :${PORT} — chain: ${chain.getConfig().chainName} — store: ${db.enabled() ? 'MySQL' : 'volume JSON'}`));
}).catch(e => { console.error('boot failed:', e.message); process.exit(1); });