// 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 forumsso = require('./forumsso'); // Earners Corner forum sign-in (DiscourseConnect, 2026-11-10) const networksso = require('./networksso'); // network sign-in with LinkSpin (2026-11-12, Marty approved): see networksso.js const themehead = require('./themehead'); // 2026-11-01 light/dark theme head script for server-rendered pages + its CSP hash 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 lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07) const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15) const hubsync = require('./hubsync'); // network hub: members from other doors arrive as waiting accounts, ours are reported (2026-11-12, only with HUB_ENABLED) 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(/\/+$/, ''); const BL_BASE = () => String(process.env.BL_URL || 'https://downlinebanners.com').replace(/\/+$/, ''); // Downline Banners (network sign-in by wallet, 2026-11-13) const VBB_BASE = () => String(process.env.VBB_URL || 'https://viralbannerblitz.com').replace(/\/+$/, ''); // Viral Banner Blitz (network sign-in by wallet, 2026-11-14) // Refuel spots (Marty 2026-11-13: paid from the company fee share, $50+): refuel.js calls this once per counted $50+ refuel tx // (either site). Downline Banners buys the spot for the member's main wallet from the engine wallet (its refuelspots.js), with // their network sponsor's wallet as sponsor. Signed with NETWORK_SSO_SECRET ('net.v1.' + ts + newline + raw body). async function refuelSpotToBL({ email, site, tx, cents }) { const a = await accounts.byEmail(email).catch(() => null); const mask = String(email).replace(/^(.).*(@.*)$/, '$1***$2'); if (!a || !a.address) { console.log('refuel spot: no wallet linked, not sent', mask); return; } const sp = await accounts.sponsorOf(email).catch(() => null); const raw = JSON.stringify({ tx, site, cents, wallet: a.address, sponsorWallet: sp && sp.address ? sp.address : null }); const sec = String(process.env.NETWORK_SSO_SECRET || '').trim(); if (sec.length < 32) return; for (let i = 0; i < 4; i++) { const ts = String(Date.now()); const sig = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex'); try { const r = await fetch(BL_BASE() + '/api/partner/refuel-spot', { method: 'POST', body: raw, signal: AbortSignal.timeout(10000), headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } }); const j = await r.json().catch(() => ({})); if (r.ok) { console.log('refuel spot queued on Downline Banners', mask, String(tx).slice(0, 12), j.repeat ? '(repeat)' : ''); if (!j.repeat) await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], 'Your refuel earned a Downline Banners spot', '
Your $' + (cents / 100).toFixed(0) + ' refuel earned you a free spot on Downline Banners, the network banner board. It is being placed in the line for your wallet now.
Open My Spots to add your banner and link (or use one of your LinkSpin Banner Spins). Your InstantAdPay sign-in carries you in.
', 'notice').catch(() => {}); return; } if (r.status === 400 || r.status === 401) { console.error('refuel spot refused', r.status, j.error || '', mask); return; } } catch (e) {} await new Promise(ok => setTimeout(ok, 30000 * (i + 1))); } console.error('refuel spot: Downline Banners did not answer', mask, String(tx).slice(0, 12)); } 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(['/chasing-unicorns', '/', '/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'); require('./safefs').install(DATA_DIR); // every .json data file is written atomically (2026-11-13 rotator.json loss) const docstore = require('./docstore'); docstore.install(DATA_DIR); // data documents live in MySQL when DOCSTORE_URL is set (2026-11-13, database is the standard) const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme'; const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); // Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept // in the volume so a restart doesn't log the admin out. Separate cookie and // store from member sessions; the Bearer ADMIN_PASSWORD API path still works. const ADMIN_SESS_FILE = path.join(DATA_DIR, 'admin-sessions.json'); const ADMIN_TTL = 12 * 60 * 60 * 1000; let adminSessions = {}; if (!process.env.DOCSTORE_URL) { try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } } // with MySQL: loaded right after docstore.init function saveAdminSessions() { const now = Date.now(); for (const k of Object.keys(adminSessions)) if (!adminSessions[k] || adminSessions[k].expires < now) delete adminSessions[k]; try { fs.writeFileSync(ADMIN_SESS_FILE, JSON.stringify(adminSessions), { mode: 0o600 }); } catch (e) {} } function mintAdminSession(email) { const t = crypto.randomBytes(32).toString('hex'); adminSessions[t] = { email, expires: Date.now() + ADMIN_TTL }; saveAdminSessions(); return t; } function adminTokenOf(req) { const m = /(?:^|;\s*)iap\.adm=([^;]+)/.exec(req.headers.cookie || ''); return m ? decodeURIComponent(m[1]) : null; } function adminFromRequest(req) { const t = adminTokenOf(req); const s = t && adminSessions[t]; return (s && s.expires > Date.now()) ? s : null; } function dropAdminSession(req) { const t = adminTokenOf(req); if (t && adminSessions[t]) { delete adminSessions[t]; saveAdminSessions(); } } function adminCookie(t) { return 'iap.adm=' + encodeURIComponent(t) + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (ADMIN_TTL / 1000) + (IS_PROD ? '; Secure' : ''); } function clearAdminCookie() { return 'iap.adm=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; } const IS_PROD = process.env.NODE_ENV === 'production'; 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', 'stackpro']); 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' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('
').replace(/\n/g, '
') + '
Your place in line came up. Your reserved login-ad slot has started, so ' + esc(name) + ' now shows full screen to members as they sign in, for ' + days + ' days, until ' + esc(until) + '.
' + 'You paid for it when you reserved, so nothing more is charged. See it in Members > Campaigns.
'; 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'), refuelSpot: refuelSpotToBL, // $50+ counted refuel -> one Downline Banners spot (2026-11-13) feed: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay \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} InstantAdPay Β· ' + text, sc.telegramEchoTopicId); }, notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; const html = '' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('
').replace(/\n/g, '
') + '
' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s)]+)/g, '$1').split('\n\n').join('
').replace(/\n/g, '
') + '
' + l.replace(/&/g, '&').replace(/$1') + '
').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:' + l.replace(/&/g, '&').replace(/$1') + '
').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 = '' + String(text).replace(/&/g, '&').replace(//g, '>') .replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('
').replace(/\n/g, '
') + '
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 the games.
', '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 => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[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('' + escH(par).replace(/\n/g, '
') + '
' + escH(hello.trim()) + '
' + html + 'You can reply from your member inbox: instantadpay.com/my
Marty Bostick, InstantAdPay
Share this link. Anyone who joins the forum through it, or through a thread you share while signed in, signs up with you as their sponsor, exactly like your InstantAdPay referral link.
' + 'Tap the box, select all and copy. To share one thread, use the share button under any post while you are signed in to the forum: those links carry your name too.
' : 'Pick a username in your InstantAdPay profile first, then come back here for your invite link.
') + '' + gkEsc(r.error) + '
Back to Gem Kingdom'); const c = r.claims; if (c.kind !== 'gk-buy' || !c.order || !(c.credits > 0) || !(c.crowns > 0)) return gkPage(res, 400, 'Order problem', '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.
Back to Gem Kingdom'); 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 = 'Gem Kingdom · Crown Shop
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.
'); } const need = c.credits - usable; return gkPage(res, 200, 'More credits needed', head + '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)' : '') + '.
' + 'Buy a credit packagePick a smaller pack' + 'A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.
'); } // ---- 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', '' + gkEsc(r.error) + '
Back to PolyWarriors'); const c = r.claims; if (c.kind !== 'pw-mint' || !c.order || !(c.serial > 0)) return gkPage(res, 400, 'Mint problem', 'PolyWarriors · Mint to your wallet
Your warrior is on its way to the wallet on your InstantAdPay account. Taking you back to the game.
' + 'Back to PolyWarriors' + 'If this page stays, tap the button. The game shows the warrior as On Polygon once the transaction confirms, usually within a minute.
', ''); } 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', '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.
'); // 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', 'PolyWarriors · Mint to your wallet
You earned these passes with your package purchases: one mint for every $5. The game pays the network fee.
'); } return gkPage(res, 200, 'Mint your warrior', 'PolyWarriors · Mint to your wallet
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.
' + 'Buy a $5 packageBack to PolyWarriors' + '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.
'); } 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', '' + gkEsc(r.error) + '
'); 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', '' + gkEsc(r.error) + '
'); 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', '' + gkEsc(out.error) + '
'); } 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', 'Gem Kingdom Β· Crown Shop
Taking you back to your kingdom...
Back to Gem Kingdom'); } // -- 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=' + gkEsc(r.error) + '
Back to Spooky Doors'); 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', '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.
Back to Spooky Doors'); 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 = 'Spooky Doors · Costume shop
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.
'); } const need = c.credits - usable; return sdPage(res, 200, 'More credits needed', head + '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)' : '') + '.
' + 'Buy a credit packageBack to the costume shop' + 'A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.
'); } 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', '' + gkEsc(r.error) + '
'); const c = r.claims; if (c.kind !== 'sd-buy' || !c.order || !c.item || !(Number(c.credits) > 0)) return sdPage(res, 400, 'Order problem', '' + gkEsc(out.error) + '
'); } 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', 'Spooky Doors · Costume shop
Taking you back to the street...
Back to Spooky Doors'); } // -- 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) { const g = tdOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'turkeydrop') { r = g; game = 'turkeydrop'; } } 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.' }); if (game === 'turkeydrop' && !tdIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a Turkey Drop 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 === 'turkeydrop' ? { game: 'Turkey Drop', label: 'back on the air' } : 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 === 'turkeydrop' ? 'Turkey Drop back on the air' : 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 === 'turkeydrop') { // Turkey Drop "back on the air" (an extra life after the station pulls you off the air): signed receipt to the game's callback and on the ret page; gameplay only, never POL const receipt = tdMint({ kind: 'td-life', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000); const posted = await tdCallback(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: 'Turkey Drop', label: 'back on the air' }); } 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/' + 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.
' + 'Join @' + esc(un) + '\u2019s line freeAdvertising with a performance referral program. Not an investment; no income is guaranteed.