Code box survives a board reload: the board hands back the member's started mission, a second Start reuses the live token, and submit accepts the code of any live token of theirs for that mission (ticket IAP-1027, phones that open the site in the board's own window)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-24 08:51:00 -06:00
parent d915884409
commit 21b2f5e91b
5 changed files with 481 additions and 466 deletions
+14 -4
View File
@@ -49,6 +49,14 @@ function issue(memberId, missionId, extra) {
return rec; return rec;
} }
function token(t) { const rec = store.read('tokens', {})[String(t || '')]; return rec && rec.exp > Date.now() ? rec : null; } function token(t) { const rec = store.read('tokens', {})[String(t || '')]; return rec && rec.exp > Date.now() ? rec : null; }
// a member's live Code Hunt tokens (no kind), newest first; missionId narrows it to one mission. The board uses the
// newest to bring the code box back after a reload, and start reuses it so a code already on screen keeps matching
// (2026-11-24: on phones the site opened in the board's own window, the reload lost the box, and a second Start
// issued a new token whose code no longer matched the one on screen)
function live(memberId, missionId) {
const all = store.read('tokens', {}), now = Date.now();
return Object.keys(all).map(k => all[k]).filter(r => r && !r.kind && r.exp > now && r.memberId === Number(memberId) && (missionId === undefined || r.missionId === missionId)).sort((x, y) => y.iat - x.iat);
}
// the proof: six characters from HMAC(secret, token); shown by the embed, typed by the hunter // the proof: six characters from HMAC(secret, token); shown by the embed, typed by the hunter
function codeFor(rec) { return h('code:' + rec.t + ':' + rec.memberId + ':' + rec.missionId).toString('hex').slice(0, 6).toUpperCase(); } function codeFor(rec) { return h('code:' + rec.t + ':' + rec.memberId + ':' + rec.missionId).toString('hex').slice(0, 6).toUpperCase(); }
@@ -75,11 +83,13 @@ function check(t, memberId, typed) {
const rec = token(t); if (!rec) return { error: 'That mission timed out. Start it again from your board.' }; const rec = token(t); if (!rec) return { error: 'That mission timed out. Start it again from your board.' };
if (rec.memberId !== Number(memberId)) return { error: 'That mission belongs to a different account.' }; if (rec.memberId !== Number(memberId)) return { error: 'That mission belongs to a different account.' };
if (rec.kind) return { error: 'That is an Ad Detective case. Answer its question on your board.' }; if (rec.kind) return { error: 'That is an Ad Detective case. Answer its question on your board.' };
const want = codeFor(rec);
const got = String(typed || '').trim().toUpperCase(); const got = String(typed || '').trim().toUpperCase();
if (got.length !== 6) return { error: 'Codes are 6 characters and you typed ' + got.length + '. Look at the site again: the code sits in six boxes, and a tap on it copies all six.' }; if (got.length !== 6) return { error: 'Codes are 6 characters and you typed ' + got.length + '. Look at the site again: the code sits in six boxes, and a tap on it copies all six.' };
if (got !== want) return { error: 'That is not the code. It is on the site, and it is yours alone.' }; if (got === codeFor(rec)) return { ok: true, rec };
return { ok: true, rec }; // pressed Start more than once: the code on screen may belong to another live token of theirs for this same mission
const other = live(rec.memberId, rec.missionId).find(r => r.t !== rec.t && codeFor(r) === got);
if (other) return { ok: true, rec: other };
return { error: 'That is not the code. It is on the site, and it is yours alone.' };
} }
module.exports = { list, get, save, remove, forMember, issue, token, codeForEmbed, check, ctDay, onVisit: null }; module.exports = { list, get, save, remove, forMember, issue, token, live, codeForEmbed, check, ctDay, onVisit: null };
+1 -1
View File
@@ -58,7 +58,7 @@
<div class="modal" id="shareModal" hidden><div class="modal-card"><button class="modal-x" id="shareClose" type="button" aria-label="Close">×</button><div id="shareBody"></div></div></div> <div class="modal" id="shareModal" hidden><div class="modal-card"><button class="modal-x" id="shareClose" type="button" aria-label="Close">×</button><div id="shareBody"></div></div></div>
<script src="https://instantadpay.com/assets/game-strip.js?v=20261003a"></script> <script src="https://instantadpay.com/assets/game-strip.js?v=20261003a"></script>
<script>if (window.IAPGames) IAPGames.strip(document.getElementById('moreGames'), { current: 'polhunter', title: ' ' }).then(function (n) { var m = document.getElementById('moreGames'), h = m.querySelector('.gs-h'); if (h) h.remove(); document.getElementById('moreGamesSec').hidden = !n; });</script> <script>if (window.IAPGames) IAPGames.strip(document.getElementById('moreGames'), { current: 'polhunter', title: ' ' }).then(function (n) { var m = document.getElementById('moreGames'), h = m.querySelector('.gs-h'); if (h) h.remove(); document.getElementById('moreGamesSec').hidden = !n; });</script>
<script src="/app.js?v=23"></script> <script src="/app.js?v=24"></script>
<script src="/nas.js?v=20261024" defer></script> <script src="/nas.js?v=20261024" defer></script>
</body> </body>
</html> </html>
+3 -2
View File
@@ -257,11 +257,12 @@
} }
} }
let explorer = 'https://polygonscan.com'; let explorer = 'https://polygonscan.com';
async function load() { board = await api('/api/my/board'); render(); } // the server remembers a started mission, so its code box survives a reload (phones often open the site in this same window)
async function load() { board = await api('/api/my/board'); if (board && board.open && (!open || open.token !== board.open.token || open.missionId !== board.open.missionId)) open = board.open; render(); }
async function start(id) { async function start(id) {
const r = await api('/api/my/start', { missionId: id }); const r = await api('/api/my/start', { missionId: id });
if (r.error) { toast(esc(r.error), 'bad'); if (r.spent || r.dailyDone) await load(); return; } if (r.error) { toast(esc(r.error), 'bad'); if (r.spent || r.dailyDone) await load(); return; }
open = { missionId: id, token: r.token, url: r.url, dwell: r.dwell, started: Date.now(), expires: r.expires }; open = { missionId: id, token: r.token, url: r.url, dwell: r.dwell, started: r.started || Date.now(), expires: r.expires };
window.open(r.url, '_blank', 'noopener'); window.open(r.url, '_blank', 'noopener');
render(); render();
} }
+461 -459
View File
@@ -1,461 +1,463 @@
// PolHunter: gamified visits across the network, paid in POL. // PolHunter: gamified visits across the network, paid in POL.
// //
// Three gates, all default-deny, all from the environment. A missing variable means silence: // Three gates, all default-deny, all from the environment. A missing variable means silence:
// OUTBOUND=on required before anything leaves this server: Telegram posts included. // OUTBOUND=on required before anything leaves this server: Telegram posts included.
// There is no mailer in this app and there is not going to be one. // There is no mailer in this app and there is not going to be one.
// SIGNUPS=open there is no sign-up form at all; hunters arrive signed in from their // SIGNUPS=open there is no sign-up form at all; hunters arrive signed in from their
// InstantAdPay dashboard (lib/sso.js). This gate controls whether that // InstantAdPay dashboard (lib/sso.js). This gate controls whether that
// hand-off is accepted, so the whole thing can be shut with one variable. // hand-off is accepted, so the whole thing can be shut with one variable.
// CURTAIN=<secret> a contentless "Coming soon" page for everyone who has not opened ?k=<secret>. // CURTAIN=<secret> a contentless "Coming soon" page for everyone who has not opened ?k=<secret>.
// //
// Faucet: HUNT_WALLET_KEY + HUNT_RPC (+ HUNT_CHAIN_ID). Admin: ADMIN_KEY. Hand-off: HUNT_SSO_SECRET. // Faucet: HUNT_WALLET_KEY + HUNT_RPC (+ HUNT_CHAIN_ID). Admin: ADMIN_KEY. Hand-off: HUNT_SSO_SECRET.
'use strict'; 'use strict';
const http = require('http'); const http = require('http');
const discordRelay = require('./discord-relay.cjs'); // mirror group posts into the CTB Discord (2026-10-09) const discordRelay = require('./discord-relay.cjs'); // mirror group posts into the CTB Discord (2026-10-09)
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const crypto = require('crypto'); const crypto = require('crypto');
const store = require('./lib/store'); const store = require('./lib/store');
const sso = require('./lib/sso'); const sso = require('./lib/sso');
const missions = require('./lib/missions'); const missions = require('./lib/missions');
const rewards = require('./lib/rewards'); const rewards = require('./lib/rewards');
const fridaybank = require('./lib/fridaybank'); // Friday Bonus Hunts (2026-09-26) const fridaybank = require('./lib/fridaybank'); // Friday Bonus Hunts (2026-09-26)
const activeMissionCount = () => missions.list().filter(m => m.active && !m.paid).length; const activeMissionCount = () => missions.list().filter(m => m.active && !m.paid).length;
const fbFor = me => fridaybank.forHunter(me, activeMissionCount(), rewards.settings().missionsPerDay || 3); const fbFor = me => fridaybank.forHunter(me, activeMissionCount(), rewards.settings().missionsPerDay || 3);
const social = require('./lib/social'); const social = require('./lib/social');
const badge = require('./lib/badge'); const badge = require('./lib/badge');
const referrals = require('./lib/referrals'); // pays a hunter for bringing someone who turns up and hunts const referrals = require('./lib/referrals'); // pays a hunter for bringing someone who turns up and hunts
const faucet = require('./lib/faucet'); const faucet = require('./lib/faucet');
const detective = require('./lib/detective'); // Mystery Hunt Box + Ad Detective (2026-09-26) const detective = require('./lib/detective'); // Mystery Hunt Box + Ad Detective (2026-09-26)
const PORT = Number(process.env.PORT || 3000); const PORT = Number(process.env.PORT || 3000);
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data'); const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const PUBLIC_DIR = path.join(__dirname, 'public'); const PUBLIC_DIR = path.join(__dirname, 'public');
badge.init({ publicDir: PUBLIC_DIR, dataDir: process.env.DATA_DIR || path.join(__dirname, 'data') }); badge.init({ publicDir: PUBLIC_DIR, dataDir: process.env.DATA_DIR || path.join(__dirname, 'data') });
const CURTAIN = String(process.env.CURTAIN || '').trim(); const CURTAIN = String(process.env.CURTAIN || '').trim();
// HUNT_LIVE_AT (ISO 8601): until then the curtain stays up and nothing goes out, whatever OUTBOUND // HUNT_LIVE_AT (ISO 8601): until then the curtain stays up and nothing goes out, whatever OUTBOUND
// says; from then on the curtain lifts by itself and Telegram opens. Launch: 2026-09-21T09:00-05:00. // says; from then on the curtain lifts by itself and Telegram opens. Launch: 2026-09-21T09:00-05:00.
const LIVE_AT = process.env.HUNT_LIVE_AT ? Date.parse(process.env.HUNT_LIVE_AT) : 0; const LIVE_AT = process.env.HUNT_LIVE_AT ? Date.parse(process.env.HUNT_LIVE_AT) : 0;
function live() { return !LIVE_AT || Date.now() >= LIVE_AT; } function live() { return !LIVE_AT || Date.now() >= LIVE_AT; }
const ADMIN_KEY = String(process.env.ADMIN_KEY || '').trim(); const ADMIN_KEY = String(process.env.ADMIN_KEY || '').trim();
const SITE = String(process.env.SITE_URL || 'https://polhunter.com').replace(/\/+$/, ''); const SITE = String(process.env.SITE_URL || 'https://polhunter.com').replace(/\/+$/, '');
const outbound = () => process.env.OUTBOUND === 'on' && live(); // nothing leaves before the live moment const outbound = () => process.env.OUTBOUND === 'on' && live(); // nothing leaves before the live moment
const signupsOpen = () => process.env.SIGNUPS === 'open'; const signupsOpen = () => process.env.SIGNUPS === 'open';
store.init(DATA_DIR); store.init(DATA_DIR);
const faucetOn = faucet.init(); const faucetOn = faucet.init();
detective.init(); detective.init();
// ---- Game Pass (GAMEPASS=on, docs/GAME-PASS.md 3a): InstantAdPay's account-wide daily cap decides what a hunter is paid; the house // ---- Game Pass (GAMEPASS=on, docs/GAME-PASS.md 3a): InstantAdPay's account-wide daily cap decides what a hunter is paid; the house
// cap and the per-hunter daily limit stay as backstops. Finds and Ad Detective cases are repeatable ('daily'): what the cap does not // cap and the per-hunter daily limit stay as backstops. Finds and Ad Detective cases are repeatable ('daily'): what the cap does not
// allow is dropped and the hunter is told. Advertiser-funded missions are NOT gated: the advertiser already paid for that completion. // allow is dropped and the hunter is told. Advertiser-funded missions are NOT gated: the advertiser already paid for that completion.
const gp = require('./lib/polgrant'), tournament = require('./lib/tournament'); const gp = require('./lib/polgrant'), tournament = require('./lib/tournament');
const IAP_URL = String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''); const IAP_URL = String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
gp.use({ game: 'polhunter', secret: String(process.env.HUNT_SSO_SECRET || '').trim(), iap: IAP_URL, store, notify: (kind, p) => notify(kind, p) }); gp.use({ game: 'polhunter', secret: String(process.env.HUNT_SSO_SECRET || '').trim(), iap: IAP_URL, store, notify: (kind, p) => notify(kind, p) });
const passActive = me => !!(gp.on() && me && gp.passOf(me.memberId, me.email).active); const passActive = me => !!(gp.on() && me && gp.passOf(me.memberId, me.email).active);
const passExtra = me => passActive(me) ? 2 : 0; // the perk: 5 missions a day instead of 3 const passExtra = me => passActive(me) ? 2 : 0; // the perk: 5 missions a day instead of 3
// the full tier (Marty 2026-11-02): Game Pass holders get the full allotment, the full draw, the weekly prizes and the Mystery Box; // the full tier (Marty 2026-11-02): Game Pass holders get the full allotment, the full draw, the weekly prizes and the Mystery Box;
// a free account gets the free tier (lib/rewards.js freeMissionsPerDay / freeMinPol / freeMaxPol). With GAMEPASS off there is no // a free account gets the free tier (lib/rewards.js freeMissionsPerDay / freeMinPol / freeMaxPol). With GAMEPASS off there is no
// pass to buy, so everyone stays on the full tier as before. // pass to buy, so everyone stays on the full tier as before.
const fullTier = me => !gp.on() || passActive(me); const fullTier = me => !gp.on() || passActive(me);
// the Network Tour (Marty 2026-11-17, lib/rotation.js): rounds per hunter; a free member's repeat find is a tour stop (ad credits, no POL) // the Network Tour (Marty 2026-11-17, lib/rotation.js): rounds per hunter; a free member's repeat find is a tour stop (ad credits, no POL)
const rotation = require('./lib/rotation'); const rotation = require('./lib/rotation');
const isTourStop = (me, m) => !fullTier(me) && !m.paid && rotation.everFound(me.memberId, me.wallet, m.id); const isTourStop = (me, m) => !fullTier(me) && !m.paid && rotation.everFound(me.memberId, me.wallet, m.id);
// one reward through IAP: ask(pol, ref) -> IAP's answer (+ the player-facing note), wait(rowId, pol, ref) -> queue the ref (fail closed) // one reward through IAP: ask(pol, ref) -> IAP's answer (+ the player-facing note), wait(rowId, pol, ref) -> queue the ref (fail closed)
const gpGate = me => ({ const gpGate = me => ({
ask: async (pol, ref) => { const r = await gp.grant({ memberId: me.memberId, email: me.email, kind: 'daily', pol, ref }); r.note = gp.note(r, 'daily', pol); return r; }, ask: async (pol, ref) => { const r = await gp.grant({ memberId: me.memberId, email: me.email, kind: 'daily', pol, ref }); r.note = gp.note(r, 'daily', pol); return r; },
wait: (rowId, pol, ref) => gp.enqueue({ memberId: me.memberId, email: me.email, ref, kind: 'daily', pol, rowId }), wait: (rowId, pol, ref) => gp.enqueue({ memberId: me.memberId, email: me.email, ref, kind: 'daily', pol, rowId }),
}); });
const payQueued = async (item, r) => { rewards.settleQueued(item.rowId, r.allowed, { pass: !!r.pass, capHit: r.capHit || null }); }; // a queued ref finally answered const payQueued = async (item, r) => { rewards.settleQueued(item.rowId, r.allowed, { pass: !!r.pass, capHit: r.capHit || null }); }; // a queued ref finally answered
tournament.init({ faucet, notify: (kind, p) => notify(kind, p), dry: faucet.dry }); tournament.init({ faucet, notify: (kind, p) => notify(kind, p), dry: faucet.dry });
// Badges added after launch count work already done, so on the day they ship many hunters hold them at once. // Badges added after launch count work already done, so on the day they ship many hunters hold them at once.
// Those are marked as announced without posting, or the badge sweep would flood Telegram with old news. // Those are marked as announced without posting, or the badge sweep would flood Telegram with old news.
// Badges earned from here on are announced as usual. Runs once per new badge id. // Badges earned from here on are announced as usual. Runs once per new badge id.
(function seedNewBadges() { (function seedNewBadges() {
const ORIGINAL = ['first', 'hunter', 'tracker', 'sweep', 'lucky', 'streak', 'top', 'recruiter']; const ORIGINAL = ['first', 'hunter', 'tracker', 'sweep', 'lucky', 'streak', 'top', 'recruiter'];
const known = new Set(store.read('badges-known', ORIGINAL)); const known = new Set(store.read('badges-known', ORIGINAL));
const fresh = social.BADGES.map(b => b.id).filter(id => !known.has(id)); if (!fresh.length) return; const fresh = social.BADGES.map(b => b.id).filter(id => !known.has(id)); if (!fresh.length) return;
const members = new Set(store.read('payouts', []).map(p => p.memberId)); let n = 0; const members = new Set(store.read('payouts', []).map(p => p.memberId)); let n = 0;
store.update('badges-posted', {}, all => { for (const id of members) { const have = new Set(all[String(id)] || []); for (const b of social.badgesFor(id)) if (fresh.includes(b.id) && !have.has(b.id)) { have.add(b.id); n++; } all[String(id)] = [...have]; } return all; }); store.update('badges-posted', {}, all => { for (const id of members) { const have = new Set(all[String(id)] || []); for (const b of social.badgesFor(id)) if (fresh.includes(b.id) && !have.has(b.id)) { have.add(b.id); n++; } all[String(id)] = [...have]; } return all; });
store.write('badges-known', [...known, ...fresh]); store.write('badges-known', [...known, ...fresh]);
console.log('new badges', fresh.join(','), '- marked', n, 'already-earned as announced (no posts)'); console.log('new badges', fresh.join(','), '- marked', n, 'already-earned as announced (no posts)');
})(); })();
// ---- Telegram (outward: gated) ------------------------------------------------------------ // ---- Telegram (outward: gated) ------------------------------------------------------------
async function telegram(text, topicOverride) { async function telegram(text, topicOverride) {
if (!outbound()) return false; // the gate if (!outbound()) return false; // the gate
const tok = process.env.HUNT_TG_TOKEN, chat = process.env.HUNT_TG_CHAT, topic = topicOverride || process.env.HUNT_TG_TOPIC; const tok = process.env.HUNT_TG_TOKEN, chat = process.env.HUNT_TG_CHAT, topic = topicOverride || process.env.HUNT_TG_TOPIC;
if (!tok || !chat) return false; if (!tok || !chat) return false;
discordRelay.mirror({ chatId: chat, threadId: topic ? Number(topic) : undefined, text }); discordRelay.mirror({ chatId: chat, threadId: topic ? Number(topic) : undefined, text });
const body = JSON.stringify(Object.assign({ chat_id: chat, text, parse_mode: 'HTML', disable_web_page_preview: true }, topic ? { message_thread_id: Number(topic) } : {})); const body = JSON.stringify(Object.assign({ chat_id: chat, text, parse_mode: 'HTML', disable_web_page_preview: true }, topic ? { message_thread_id: Number(topic) } : {}));
try { const r = await fetch('https://api.telegram.org/bot' + tok + '/sendMessage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body }); return r.ok; } catch (e) { return false; } try { const r = await fetch('https://api.telegram.org/bot' + tok + '/sendMessage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body }); return r.ok; } catch (e) { return false; }
} }
async function telegramPhoto(file, caption, general, topicOverride) { async function telegramPhoto(file, caption, general, topicOverride) {
if (!outbound()) return false; // the gate if (!outbound()) return false; // the gate
const tok = process.env.HUNT_TG_TOKEN, chat = process.env.HUNT_TG_CHAT, topic = topicOverride || process.env.HUNT_TG_TOPIC; const tok = process.env.HUNT_TG_TOKEN, chat = process.env.HUNT_TG_CHAT, topic = topicOverride || process.env.HUNT_TG_TOPIC;
if (!tok || !chat || !file) return false; if (!tok || !chat || !file) return false;
discordRelay.mirror({ chatId: chat, threadId: topic && !general ? Number(topic) : undefined, text: caption, photo: fs.readFileSync(file) }); discordRelay.mirror({ chatId: chat, threadId: topic && !general ? Number(topic) : undefined, text: caption, photo: fs.readFileSync(file) });
try { try {
const fd = new FormData(); fd.append('chat_id', chat); fd.append('caption', caption); fd.append('parse_mode', 'HTML'); if (topic && !general) fd.append('message_thread_id', String(topic)); const fd = new FormData(); fd.append('chat_id', chat); fd.append('caption', caption); fd.append('parse_mode', 'HTML'); if (topic && !general) fd.append('message_thread_id', String(topic));
fd.append('photo', new Blob([fs.readFileSync(file)], { type: 'image/jpeg' }), 'badge.jpg'); fd.append('photo', new Blob([fs.readFileSync(file)], { type: 'image/jpeg' }), 'badge.jpg');
const r = await fetch('https://api.telegram.org/bot' + tok + '/sendPhoto', { method: 'POST', body: fd }); return r.ok; const r = await fetch('https://api.telegram.org/bot' + tok + '/sendPhoto', { method: 'POST', body: fd }); return r.ok;
} catch (e) { return false; } } catch (e) { return false; }
} }
const fmt = n => Number(n).toLocaleString('en-US', { maximumFractionDigits: 4 }); const fmt = n => Number(n).toLocaleString('en-US', { maximumFractionDigits: 4 });
// keys being posted right now, so the claim path and the sweep never post the same thing twice // keys being posted right now, so the claim path and the sweep never post the same thing twice
const postingNow = new Set(); const postingNow = new Set();
async function notify(kind, p) { async function notify(kind, p) {
if (kind === 'paid' && p && p.id) { const k = 'find:' + p.id; if (postingNow.has(k)) return false; postingNow.add(k); try { return await notifyPaid(p); } finally { postingNow.delete(k); } } if (kind === 'paid' && p && p.id) { const k = 'find:' + p.id; if (postingNow.has(k)) return false; postingNow.add(k); try { return await notifyPaid(p); } finally { postingNow.delete(k); } }
if (kind === 'badge' && p && p.me) { const k = 'badge:' + p.me.memberId + ':' + p.id; if (postingNow.has(k)) return false; postingNow.add(k); try { return await notifyBadge(p); } finally { postingNow.delete(k); } } if (kind === 'badge' && p && p.me) { const k = 'badge:' + p.me.memberId + ':' + p.id; if (postingNow.has(k)) return false; postingNow.add(k); try { return await notifyBadge(p); } finally { postingNow.delete(k); } }
return notifyOther(kind, p); return notifyOther(kind, p);
} }
async function notifyPaid(p) { async function notifyPaid(p) {
if (p.detective) { const ok = await telegram('\u{1F50E} <b>PolHunter</b> · ' + (p.username ? '@' + p.username : '#' + p.memberId) + ' cracked an <b>Ad Detective</b> case on ' + p.site + ' and got <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>\n<a href="' + SITE + '">Hunt yours</a>'); if (ok && p.id) rewards.mark(p.id, { posted: Date.now() }); return ok; } if (p.detective) { const ok = await telegram('\u{1F50E} <b>PolHunter</b> · ' + (p.username ? '@' + p.username : '#' + p.memberId) + ' cracked an <b>Ad Detective</b> case on ' + p.site + ' and got <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>\n<a href="' + SITE + '">Hunt yours</a>'); if (ok && p.id) rewards.mark(p.id, { posted: Date.now() }); return ok; }
{ const ok = await telegram('\u{1F3AF} <b>PolHunter</b> · ' + (p.username ? '@' + p.username : '#' + p.memberId) + ' found it on ' + p.site + ' and got <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>\n<a href="' + SITE + '">Hunt yours</a>'); if (ok && p.id) rewards.mark(p.id, { posted: Date.now() }); return ok; } { const ok = await telegram('\u{1F3AF} <b>PolHunter</b> · ' + (p.username ? '@' + p.username : '#' + p.memberId) + ' found it on ' + p.site + ' and got <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>\n<a href="' + SITE + '">Hunt yours</a>'); if (ok && p.id) rewards.mark(p.id, { posted: Date.now() }); return ok; }
} }
async function notifyOther(kind, p) { async function notifyOther(kind, p) {
if (kind === 'low') return telegram('⚠️ <b>PolHunter faucet is low</b>: ' + fmt(p.balance) + ' POL left in ' + p.address + ' (alert threshold ' + fmt(p.threshold) + ').' + (p.tournament ? ' A Pass Tournament prize is waiting on it.' : '') + ' Top up from Receiver B.'); if (kind === 'low') return telegram('⚠️ <b>PolHunter faucet is low</b>: ' + fmt(p.balance) + ' POL left in ' + p.address + ' (alert threshold ' + fmt(p.threshold) + ').' + (p.tournament ? ' A Pass Tournament prize is waiting on it.' : '') + ' Top up from Receiver B.');
if (kind === 'gpstuck') return telegram('⚠️ <b>PolHunter</b> Game Pass grant stuck 48 h: member #' + p.memberId + ' ' + (p.email || '') + ' ref ' + p.ref + ' (' + fmt(p.pol) + ' POL, ' + p.kind + '). InstantAdPay /api/partner/polgrant unreachable: ' + (p.error || '?')); if (kind === 'gpstuck') return telegram('⚠️ <b>PolHunter</b> Game Pass grant stuck 48 h: member #' + p.memberId + ' ' + (p.email || '') + ' ref ' + p.ref + ' (' + fmt(p.pol) + ' POL, ' + p.kind + '). InstantAdPay /api/partner/polgrant unreachable: ' + (p.error || '?'));
if (kind === 'tourneypaid') return telegram('\u{1F3C6} <b>Pass Tournament</b> prize paid from the PolHunter faucet: week ' + p.week + ' place ' + p.place + ' · ' + (p.email || '#' + p.memberId) + ' · <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>'); if (kind === 'tourneypaid') return telegram('\u{1F3C6} <b>Pass Tournament</b> prize paid from the PolHunter faucet: week ' + p.week + ' place ' + p.place + ' · ' + (p.email || '#' + p.memberId) + ' · <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>');
if (kind === 'tourneyfail') return telegram('❌ <b>Pass Tournament</b> prize NOT paid (row stays pending on InstantAdPay): week ' + p.week + ' place ' + p.place + ' · ' + (p.email || '#' + p.memberId) + ' · ' + fmt(p.pol) + ' POL · ' + p.error); if (kind === 'tourneyfail') return telegram('❌ <b>Pass Tournament</b> prize NOT paid (row stays pending on InstantAdPay): week ' + p.week + ' place ' + p.place + ' · ' + (p.email || '#' + p.memberId) + ' · ' + fmt(p.pol) + ' POL · ' + p.error);
if (kind === 'failed') return telegram('❌ <b>PolHunter</b> · drip to #' + p.memberId + ' failed: ' + p.error); if (kind === 'failed') return telegram('❌ <b>PolHunter</b> · drip to #' + p.memberId + ' failed: ' + p.error);
// a bounty is the one payout that advertises the mission itself, so it goes to the room // a bounty is the one payout that advertises the mission itself, so it goes to the room
if (kind === 'referral') { const d = p.drip; return telegram('\u{1F91D} <b>PolHunter</b> · ' + (d.username ? '@' + d.username : '#' + d.memberId) + ' brought ' + d.ref.forName + ' in and they are hunting · <b>' + fmt(d.pol) + ' POL</b> bounty on the way\n<a href="' + SITE + '">Bring yours</a>'); } if (kind === 'referral') { const d = p.drip; return telegram('\u{1F91D} <b>PolHunter</b> · ' + (d.username ? '@' + d.username : '#' + d.memberId) + ' brought ' + d.ref.forName + ' in and they are hunting · <b>' + fmt(d.pol) + ' POL</b> bounty on the way\n<a href="' + SITE + '">Bring yours</a>'); }
// Marty's launch bonus, paid once to whoever gets a referral all the way through first // Marty's launch bonus, paid once to whoever gets a referral all the way through first
if (kind === 'firstbonus') { const d = p.drip; return telegram('\u{1F947} <b>First referral home!</b> ' + (d.username ? '@' + d.username : '#' + d.memberId) + ' is the first to bring a hunter all the way through, so Marty’s <b>' + fmt(d.pol) + ' POL</b> bonus is theirs on top of the bounty.\nThat one is claimed. The mission is not — <a href="' + SITE + '">bring yours</a>.'); } if (kind === 'firstbonus') { const d = p.drip; return telegram('\u{1F947} <b>First referral home!</b> ' + (d.username ? '@' + d.username : '#' + d.memberId) + ' is the first to bring a hunter all the way through, so Marty’s <b>' + fmt(d.pol) + ' POL</b> bonus is theirs on top of the bounty.\nThat one is claimed. The mission is not — <a href="' + SITE + '">bring yours</a>.'); }
if (kind === 'prize') { const medal = ['\u{1F947}', '\u{1F948}', '\u{1F949}']; return telegram('\u{1F3C6} <b>PolHunter weekly prizes</b> for the week of ' + p.week + '\n' + p.winners.map(w => (medal[w.rank - 1] || '#' + w.rank) + ' ' + w.who + ' \u00b7 ' + w.finds + ' finds \u00b7 <b>' + fmt(w.prizePol) + ' POL</b>').join('\n') + '\n<a href="' + SITE + '/leaders">Leaderboard</a>'); } if (kind === 'prize') { const medal = ['\u{1F947}', '\u{1F948}', '\u{1F949}']; return telegram('\u{1F3C6} <b>PolHunter weekly prizes</b> for the week of ' + p.week + '\n' + p.winners.map(w => (medal[w.rank - 1] || '#' + w.rank) + ' ' + w.who + ' \u00b7 ' + w.finds + ' finds \u00b7 <b>' + fmt(w.prizePol) + ' POL</b>').join('\n') + '\n<a href="' + SITE + '/leaders">Leaderboard</a>'); }
return false; return false;
} }
async function notifyBadge(p) { const ok = await postBadge(p); if (ok) store.update('badges-posted', {}, all => { const k = String(p.me.memberId); all[k] = Array.from(new Set([...(all[k] || []), p.id])); return all; }); return ok; } async function notifyBadge(p) { const ok = await postBadge(p); if (ok) store.update('badges-posted', {}, all => { const k = String(p.me.memberId); all[k] = Array.from(new Set([...(all[k] || []), p.id])); return all; }); return ok; }
async function postBadge(p) { async function postBadge(p) {
{ const b = social.BADGES.find(x => x.id === p.id); if (!b) return false; const who = social.nameOf(p.me); const file = await badge.render(p.id, p.me.username || '#' + p.me.memberId); const cap = '\u{1F3C6} <b>PolHunter</b> \u00b7 <b>' + (p.me.username ? '@' + p.me.username : '#' + p.me.memberId) + '</b> unlocked <b>' + b.name + '</b>: ' + b.why + '\n' + SITE + '/b/' + who + '/' + p.id; const ach = process.env.HUNT_TG_ACH_TOPIC || ''; /* badges = achievements topic (Marty, 2026-10-01); payouts stay in HUNT_TG_TOPIC */ if (!file) return telegram(cap, ach); const ok = await telegramPhoto(file, cap, false, ach); if (String(process.env.HUNT_TG_BADGE_GENERAL || 'on') === 'on') await telegramPhoto(file, cap, true); return ok; } { const b = social.BADGES.find(x => x.id === p.id); if (!b) return false; const who = social.nameOf(p.me); const file = await badge.render(p.id, p.me.username || '#' + p.me.memberId); const cap = '\u{1F3C6} <b>PolHunter</b> \u00b7 <b>' + (p.me.username ? '@' + p.me.username : '#' + p.me.memberId) + '</b> unlocked <b>' + b.name + '</b>: ' + b.why + '\n' + SITE + '/b/' + who + '/' + p.id; const ach = process.env.HUNT_TG_ACH_TOPIC || ''; /* badges = achievements topic (Marty, 2026-10-01); payouts stay in HUNT_TG_TOPIC */ if (!file) return telegram(cap, ach); const ok = await telegramPhoto(file, cap, false, ach); if (String(process.env.HUNT_TG_BADGE_GENERAL || 'on') === 'on') await telegramPhoto(file, cap, true); return ok; }
return false; return false;
} }
// Marty's rule (2026-09-19): when the day's pool is spent, say so; claims reopen at midnight Central // Marty's rule (2026-09-19): when the day's pool is spent, say so; claims reopen at midnight Central
const dailyMsg = d => 'That is your ' + (['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'][d.limit] || d.limit) + ' for today. Fresh missions at midnight Central.' + (d.pass ? '' : ' Game Pass holders hunt five a day at the full reward.'); // free tier since 2026-11-02 const dailyMsg = d => 'That is your ' + (['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'][d.limit] || d.limit) + ' for today. Fresh missions at midnight Central.' + (d.pass ? '' : ' Game Pass holders hunt five a day at the full reward.'); // free tier since 2026-11-02
const SPENT_MSG = 'Today\u2019s POL pool is spent. No more claims today. Claims reopen at midnight Central.'; const SPENT_MSG = 'Today\u2019s POL pool is spent. No more claims today. Claims reopen at midnight Central.';
function refOf(req) { const m = /(?:^|;\s*)ph\.ref=([^;]+)/.exec(req.headers.cookie || ''); const r = m ? decodeURIComponent(m[1]) : ''; return /^[A-Za-z0-9_.-]{1,40}$/.test(r) ? r : null; } function refOf(req) { const m = /(?:^|;\s*)ph\.ref=([^;]+)/.exec(req.headers.cookie || ''); const r = m ? decodeURIComponent(m[1]) : ''; return /^[A-Za-z0-9_.-]{1,40}$/.test(r) ? r : null; }
function explorer() { return Number(process.env.HUNT_CHAIN_ID) === 80002 ? 'https://amoy.polygonscan.com' : 'https://polygonscan.com'; } function explorer() { return Number(process.env.HUNT_CHAIN_ID) === 80002 ? 'https://amoy.polygonscan.com' : 'https://polygonscan.com'; }
// ---- helpers ------------------------------------------------------------------------------- // ---- helpers -------------------------------------------------------------------------------
const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.webp': 'image/webp', '.mp4': 'video/mp4' }; const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'application/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.webp': 'image/webp', '.mp4': 'video/mp4' };
// framing (2026-10-03, diannt's traffic-exchange 'refused to connect'): public pages may be shown in other sites' frames (surf // framing (2026-10-03, diannt's traffic-exchange 'refused to connect'): public pages may be shown in other sites' frames (surf
// and rotator sites); the signed-in board, sign-in, admin and member APIs never are (clickjacking guard set per request below) // and rotator sites); the signed-in board, sign-in, admin and member APIs never are (clickjacking guard set per request below)
const SEC = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }; const SEC = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' };
const NO_FRAME = p => /^\/(app|admin|auth|logout)(\/|$)/.test(p) || /^\/api\/(my|admin)(\/|$)/.test(p); const NO_FRAME = p => /^\/(app|admin|auth|logout)(\/|$)/.test(p) || /^\/api\/(my|admin)(\/|$)/.test(p);
function json(res, code, body, extra) { res.writeHead(code, Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, SEC, extra || {})); res.end(JSON.stringify(body)); } function json(res, code, body, extra) { res.writeHead(code, Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, SEC, extra || {})); res.end(JSON.stringify(body)); }
function sendFile(res, file, extra) { function sendFile(res, file, extra) {
// video streams with byte ranges (iOS Safari refuses to play without 206 support) // video streams with byte ranges (iOS Safari refuses to play without 206 support)
if (path.extname(file) === '.mp4') return sendRange(res, file, extra); if (path.extname(file) === '.mp4') return sendRange(res, file, extra);
fs.readFile(file, (err, buf) => { fs.readFile(file, (err, buf) => {
if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
res.writeHead(200, Object.assign({ 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store' }, SEC, extra || {})); res.writeHead(200, Object.assign({ 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store' }, SEC, extra || {}));
res.end(buf); res.end(buf);
}); });
} }
function sendRange(res, file, extra) { function sendRange(res, file, extra) {
fs.stat(file, (err, st) => { fs.stat(file, (err, st) => {
if (err || !st.isFile()) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } if (err || !st.isFile()) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
const size = st.size; const range = res.req && res.req.headers.range; const size = st.size; const range = res.req && res.req.headers.range;
const head = Object.assign({ 'Content-Type': TYPES['.mp4'], 'Accept-Ranges': 'bytes', 'Cache-Control': 'public, max-age=3600' }, SEC, extra || {}); const head = Object.assign({ 'Content-Type': TYPES['.mp4'], 'Accept-Ranges': 'bytes', 'Cache-Control': 'public, max-age=3600' }, SEC, extra || {});
let start = 0, end = size - 1, code = 200; let start = 0, end = size - 1, code = 200;
const m = range && /^bytes=(\d*)-(\d*)$/.exec(range); const m = range && /^bytes=(\d*)-(\d*)$/.exec(range);
if (m) { if (m) {
start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2] || 0)); end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : (m[1] ? size - 1 : size - 1); start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2] || 0)); end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : (m[1] ? size - 1 : size - 1);
if (start > end || start >= size) { res.writeHead(416, { 'Content-Range': 'bytes */' + size }); return res.end(); } if (start > end || start >= size) { res.writeHead(416, { 'Content-Range': 'bytes */' + size }); return res.end(); }
code = 206; head['Content-Range'] = 'bytes ' + start + '-' + end + '/' + size; code = 206; head['Content-Range'] = 'bytes ' + start + '-' + end + '/' + size;
} }
head['Content-Length'] = end - start + 1; head['Content-Length'] = end - start + 1;
res.writeHead(code, head); res.writeHead(code, head);
if (res.req && res.req.method === 'HEAD') return res.end(); if (res.req && res.req.method === 'HEAD') return res.end();
fs.createReadStream(file, { start, end }).pipe(res); fs.createReadStream(file, { start, end }).pipe(res);
}); });
} }
function readBody(req) { return new Promise((resolve) => { let d = ''; req.on('data', c => { d += c; if (d.length > 65536) req.destroy(); }); req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { resolve({}); } }); }); } function readBody(req) { return new Promise((resolve) => { let d = ''; req.on('data', c => { d += c; if (d.length > 65536) req.destroy(); }); req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { resolve({}); } }); }); }
const hits = new Map(); const hits = new Map();
function limited(key, max, windowMs) { const now = Date.now(); const r = hits.get(key); if (!r || now > r.reset) { hits.set(key, { n: 1, reset: now + windowMs }); return false; } r.n++; return r.n > max; } function limited(key, max, windowMs) { const now = Date.now(); const r = hits.get(key); if (!r || now > r.reset) { hits.set(key, { n: 1, reset: now + windowMs }); return false; } r.n++; return r.n > max; }
const ip = req => String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim(); const ip = req => String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
const CURTAIN_PAGE = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>Coming soon</title><style>*{margin:0;padding:0;box-sizing:border-box}html,body{height:100%}body{display:flex;align-items:center;justify-content:center;padding:24px;background:#0d1117;color:#e6edf3;font:16px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif}.card{max-width:420px;text-align:center}h1{font-size:clamp(28px,7vw,44px);font-weight:700;letter-spacing:-.5px;margin-bottom:14px}p{color:#8b949e}</style></head><body><div class="card"><h1>Coming soon</h1><p>This site is still being built.</p></div></body></html>`; const CURTAIN_PAGE = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>Coming soon</title><style>*{margin:0;padding:0;box-sizing:border-box}html,body{height:100%}body{display:flex;align-items:center;justify-content:center;padding:24px;background:#0d1117;color:#e6edf3;font:16px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif}.card{max-width:420px;text-align:center}h1{font-size:clamp(28px,7vw,44px);font-weight:700;letter-spacing:-.5px;margin-bottom:14px}p{color:#8b949e}</style></head><body><div class="card"><h1>Coming soon</h1><p>This site is still being built.</p></div></body></html>`;
function curtained(req, res, u) { function curtained(req, res, u) {
if (!CURTAIN || (LIVE_AT && live())) return false; // the launch moment lifts the curtain if (!CURTAIN || (LIVE_AT && live())) return false; // the launch moment lifts the curtain
if (u.searchParams.get('k') === CURTAIN) { u.searchParams.delete('k'); res.writeHead(302, { 'Set-Cookie': 'ph.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax; Secure', Location: u.pathname + (u.searchParams.toString() ? '?' + u.searchParams : ''), 'Cache-Control': 'no-store' }); res.end(); return true; } if (u.searchParams.get('k') === CURTAIN) { u.searchParams.delete('k'); res.writeHead(302, { 'Set-Cookie': 'ph.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax; Secure', Location: u.pathname + (u.searchParams.toString() ? '?' + u.searchParams : ''), 'Cache-Control': 'no-store' }); res.end(); return true; }
const m = /(?:^|;\s*)ph\.pass=([^;]*)/.exec(req.headers.cookie || ''); const m = /(?:^|;\s*)ph\.pass=([^;]*)/.exec(req.headers.cookie || '');
if (m && decodeURIComponent(m[1]) === CURTAIN) return false; if (m && decodeURIComponent(m[1]) === CURTAIN) return false;
res.writeHead(503, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' }); res.end(req.method === 'HEAD' ? '' : CURTAIN_PAGE); return true; res.writeHead(503, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' }); res.end(req.method === 'HEAD' ? '' : CURTAIN_PAGE); return true;
} }
function admin(req) { const k = req.headers['x-admin-key'] || new URL(req.url, 'http://x').searchParams.get('key'); return !!(ADMIN_KEY && k && k.length === ADMIN_KEY.length && crypto.timingSafeEqual(Buffer.from(k), Buffer.from(ADMIN_KEY))); } function admin(req) { const k = req.headers['x-admin-key'] || new URL(req.url, 'http://x').searchParams.get('key'); return !!(ADMIN_KEY && k && k.length === ADMIN_KEY.length && crypto.timingSafeEqual(Buffer.from(k), Buffer.from(ADMIN_KEY))); }
const pubMission = m => ({ id: m.id, site: m.site, name: m.name, brief: m.brief, dwell: m.dwell || 30, reward: rewards.settings() }); // a mission URL may place the token itself with {token} (a Telegram Mini App takes it in ?startapp=, not as our own
// query string); otherwise the token rides in the hash: a server never sees it, so no redirect or canonical rewrite can lose it
// ---- the server ------------------------------------------------------------------------------ const missionUrl = (m, t) => m.url.includes('{token}') ? m.url.replace('{token}', t) : m.url + '#ph=' + t;
const server = http.createServer(async (req, res) => { const pubMission = m => ({ id: m.id, site: m.site, name: m.name, brief: m.brief, dwell: m.dwell || 30, reward: rewards.settings() });
try {
const u = new URL(req.url, 'http://x'); const p = u.pathname; // ---- the server ------------------------------------------------------------------------------
if (NO_FRAME(p)) { res.setHeader('X-Frame-Options', 'DENY'); res.setHeader('Content-Security-Policy', "frame-ancestors 'none'"); } const server = http.createServer(async (req, res) => {
if (p === '/health') return json(res, 200, { ok: true, outbound: outbound(), signups: signupsOpen(), curtain: !!CURTAIN && !(LIVE_AT && live()), live: live(), liveAt: LIVE_AT ? new Date(LIVE_AT).toISOString() : null, faucet: faucetOn, sso: sso.enabled(), chain: Number(process.env.HUNT_CHAIN_ID) || null }); try {
const u = new URL(req.url, 'http://x'); const p = u.pathname;
// the embed talks to us from the mission sites: it must work through the curtain, and it must if (NO_FRAME(p)) { res.setHeader('X-Frame-Options', 'DENY'); res.setHeader('Content-Security-Policy', "frame-ancestors 'none'"); }
// answer only to the mission's own origin (CORS is the second lock, missions.codeForEmbed the first) if (p === '/health') return json(res, 200, { ok: true, outbound: outbound(), signups: signupsOpen(), curtain: !!CURTAIN && !(LIVE_AT && live()), live: live(), liveAt: LIVE_AT ? new Date(LIVE_AT).toISOString() : null, faucet: faucetOn, sso: sso.enabled(), chain: Number(process.env.HUNT_CHAIN_ID) || null });
if (p === '/api/embed/code') {
const origin = String(req.headers.origin || ''); // the embed talks to us from the mission sites: it must work through the curtain, and it must
const r = missions.codeForEmbed(u.searchParams.get('t'), origin); // answer only to the mission's own origin (CORS is the second lock, missions.codeForEmbed the first)
const cors = r.error === 'origin' ? {} : { 'Access-Control-Allow-Origin': origin, 'Vary': 'Origin' }; if (p === '/api/embed/code') {
if (req.method === 'OPTIONS') { res.writeHead(204, Object.assign({ 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Max-Age': '600' }, cors)); return res.end(); } const origin = String(req.headers.origin || '');
if (limited('embed:' + ip(req), 120, 60000)) return json(res, 429, { error: 'slow down' }, cors); const r = missions.codeForEmbed(u.searchParams.get('t'), origin);
return json(res, r.error ? 403 : 200, r, cors); const cors = r.error === 'origin' ? {} : { 'Access-Control-Allow-Origin': origin, 'Vary': 'Origin' };
} if (req.method === 'OPTIONS') { res.writeHead(204, Object.assign({ 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Max-Age': '600' }, cors)); return res.end(); }
if (p === '/embed.js') return sendFile(res, path.join(PUBLIC_DIR, 'embed.js'), { 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); if (limited('embed:' + ip(req), 120, 60000)) return json(res, 429, { error: 'slow down' }, cors);
// badge cards and their share pages are posted around the web: they pass the curtain return json(res, r.error ? 403 : 200, r, cors);
if (p === '/style.css') return sendFile(res, path.join(PUBLIC_DIR, 'style.css'), { 'Cache-Control': 'public, max-age=3600' }); // the share pages are styled for outsiders }
if (/^\/badges\/badge-[a-z]+\.jpg$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, p.slice(1)), { 'Cache-Control': 'public, max-age=86400' }); if (p === '/embed.js') return sendFile(res, path.join(PUBLIC_DIR, 'embed.js'), { 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' });
{ const bm = /^\/badge-img\/([a-z0-9_.-]{1,40})\/([a-z]+)\.jpg$/.exec(p) || /^\/b\/([a-z0-9_.-]{1,40})\/([a-z]+)$/.exec(p); // badge cards and their share pages are posted around the web: they pass the curtain
if (bm) { if (p === '/style.css') return sendFile(res, path.join(PUBLIC_DIR, 'style.css'), { 'Cache-Control': 'public, max-age=3600' }); // the share pages are styled for outsiders
const who = bm[1], id = bm[2]; const m = social.memberByName(who); const b = social.BADGES.find(x => x.id === id); if (/^\/badges\/badge-[a-z]+\.jpg$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, p.slice(1)), { 'Cache-Control': 'public, max-age=86400' });
if (!m || !b || !social.badgesFor(m.memberId).some(x => x.id === id)) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } { const bm = /^\/badge-img\/([a-z0-9_.-]{1,40})\/([a-z]+)\.jpg$/.exec(p) || /^\/b\/([a-z0-9_.-]{1,40})\/([a-z]+)$/.exec(p);
if (p.startsWith('/badge-img/')) { const file = await badge.render(id, m.username || '#' + m.memberId); return sendFile(res, file || path.join(PUBLIC_DIR, 'badges', 'badge-' + id + '.jpg'), { 'Cache-Control': 'public, max-age=3600' }); } if (bm) {
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])); const who = bm[1], id = bm[2]; const m = social.memberByName(who); const b = social.BADGES.find(x => x.id === id);
const url = SITE + '/b/' + who + '/' + id, img = SITE + '/badge-img/' + who + '/' + id + '.jpg', ref = SITE + '/?r=' + encodeURIComponent(m.username || m.memberId); if (!m || !b || !social.badgesFor(m.memberId).some(x => x.id === id)) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
const title = m.who + ' unlocked ' + b.name + ' on PolHunter', desc = b.name + ': ' + b.why + '. PolHunter pays random drips of POL for finding your code on our sites, on chain, with a link to prove it.'; if (p.startsWith('/badge-img/')) { const file = await badge.render(id, m.username || '#' + m.memberId); return sendFile(res, file || path.join(PUBLIC_DIR, 'badges', 'badge-' + id + '.jpg'), { 'Cache-Control': 'public, max-age=3600' }); }
const share = encodeURIComponent(title + ' ' + url); const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
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">' const url = SITE + '/b/' + who + '/' + id, img = SITE + '/badge-img/' + who + '/' + id + '.jpg', ref = SITE + '/?r=' + encodeURIComponent(m.username || m.memberId);
+ '<meta property="og:type" content="website"><meta property="og:site_name" content="PolHunter"><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="1080"><meta property="og:image:height" content="1080">' const title = m.who + ' unlocked ' + b.name + ' on PolHunter', desc = b.name + ': ' + b.why + '. PolHunter pays random drips of POL for finding your code on our sites, on chain, with a link to prove it.';
+ '<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="stylesheet" href="/style.css?v=12"></head>' const share = encodeURIComponent(title + ' ' + url);
+ '<body><div class="wrap"><header class="top"><a class="mark" href="/"><span class="coin"></span>PolHunter</a><nav class="nav"><a class="btn ghost sm" href="/leaders">Leaderboard</a><a class="btn sm" href="' + ref + '">Hunt yours</a></nav></header>' 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">'
+ '<div class="bp"><img src="' + img + '" alt="' + esc(b.name) + ' badge for ' + esc(m.who) + '"><h1>' + esc(m.who) + ' unlocked <em>' + esc(b.name) + '</em></h1><p>' + esc(b.why.charAt(0).toUpperCase() + b.why.slice(1)) + '. PolHunter pays random drips of POL for finding your code on our sites, straight to your wallet, on chain.</p>' + '<meta property="og:type" content="website"><meta property="og:site_name" content="PolHunter"><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="1080"><meta property="og:image:height" content="1080">'
+ '<a class="btn" href="' + ref + '">Hunt yours</a><div class="sharebtns" style="justify-content:center;margin-top:16px"><a class="btn ghost sm" target="_blank" rel="noopener" href="https://twitter.com/intent/tweet?text=' + share + '">X</a><a class="btn ghost sm" target="_blank" rel="noopener" href="https://t.me/share/url?url=' + encodeURIComponent(url) + '&text=' + encodeURIComponent(title) + '">Telegram</a><a class="btn ghost sm" target="_blank" rel="noopener" href="https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url) + '">Facebook</a><a class="btn ghost sm" target="_blank" rel="noopener" href="https://wa.me/?text=' + share + '">WhatsApp</a></div>' + '<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="stylesheet" href="/style.css?v=12"></head>'
+ '<p class="small" style="margin-top:26px">Rewards are for completed missions, not income. Cryptocurrency involves risk of loss.</p></div></div></body></html>'; + '<body><div class="wrap"><header class="top"><a class="mark" href="/"><span class="coin"></span>PolHunter</a><nav class="nav"><a class="btn ghost sm" href="/leaders">Leaderboard</a><a class="btn sm" href="' + ref + '">Hunt yours</a></nav></header>'
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(html); + '<div class="bp"><img src="' + img + '" alt="' + esc(b.name) + ' badge for ' + esc(m.who) + '"><h1>' + esc(m.who) + ' unlocked <em>' + esc(b.name) + '</em></h1><p>' + esc(b.why.charAt(0).toUpperCase() + b.why.slice(1)) + '. PolHunter pays random drips of POL for finding your code on our sites, straight to your wallet, on chain.</p>'
} + '<a class="btn" href="' + ref + '">Hunt yours</a><div class="sharebtns" style="justify-content:center;margin-top:16px"><a class="btn ghost sm" target="_blank" rel="noopener" href="https://twitter.com/intent/tweet?text=' + share + '">X</a><a class="btn ghost sm" target="_blank" rel="noopener" href="https://t.me/share/url?url=' + encodeURIComponent(url) + '&text=' + encodeURIComponent(title) + '">Telegram</a><a class="btn ghost sm" target="_blank" rel="noopener" href="https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url) + '">Facebook</a><a class="btn ghost sm" target="_blank" rel="noopener" href="https://wa.me/?text=' + share + '">WhatsApp</a></div>'
} + '<p class="small" style="margin-top:26px">Rewards are for completed missions, not income. Cryptocurrency involves risk of loss.</p></div></div></body></html>';
// the coin on the code pill, fetched by mission-site visitors who hold no curtain pass res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(html);
if (p === '/img/coin-sm.png' || p === '/img/coin.png' || p === '/img/og.jpg' || /^\/promo\/polhunter-[a-z-]*\d+x\d+\.(jpg|png)$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, p.slice(1)), { 'Cache-Control': 'public, max-age=86400' }); }
}
if (curtained(req, res, u)) return; // the coin on the code pill, fetched by mission-site visitors who hold no curtain pass
// a member's share link: /?r=<their IAP username or id> becomes a 30-day cookie; the landing then if (p === '/img/coin-sm.png' || p === '/img/coin.png' || p === '/img/og.jpg' || /^\/promo\/polhunter-[a-z-]*\d+x\d+\.(jpg|png)$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, p.slice(1)), { 'Cache-Control': 'public, max-age=86400' });
// sends sign-ups to instantadpay.com/join/<ref>, so IAP's own last-touch sponsor rule applies
// Served in place, not redirected (Marty, 2026-09-21): Facebook's crawler follows redirects and canonicalizes a if (curtained(req, res, u)) return;
// share to og:url, so a redirect to the bare home page lost the member's name on every share. og:url carries // a member's share link: /?r=<their IAP username or id> becomes a 30-day cookie; the landing then
// the ref; the cookie rides on the same response. // sends sign-ups to instantadpay.com/join/<ref>, so IAP's own last-touch sponsor rule applies
if (p === '/' && u.searchParams.get('r')) { // Served in place, not redirected (Marty, 2026-09-21): Facebook's crawler follows redirects and canonicalizes a
const r = String(u.searchParams.get('r')).trim().slice(0, 40); // share to og:url, so a redirect to the bare home page lost the member's name on every share. og:url carries
const ok = /^[A-Za-z0-9_.-]{1,40}$/.test(r); // the ref; the cookie rides on the same response.
let html = fs.readFileSync(path.join(PUBLIC_DIR, 'index.html'), 'utf8'); if (p === '/' && u.searchParams.get('r')) {
if (ok) html = html.replace('<meta property="og:url" content="https://polhunter.com/">', '<meta property="og:url" content="https://polhunter.com/?r=' + encodeURIComponent(r) + '">'); const r = String(u.searchParams.get('r')).trim().slice(0, 40);
const h = Object.assign({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }, SEC); const ok = /^[A-Za-z0-9_.-]{1,40}$/.test(r);
if (ok) h['Set-Cookie'] = 'ph.ref=' + encodeURIComponent(r) + '; Path=/; Max-Age=2592000; SameSite=Lax; Secure'; let html = fs.readFileSync(path.join(PUBLIC_DIR, 'index.html'), 'utf8');
res.writeHead(200, h); return res.end(html); if (ok) html = html.replace('<meta property="og:url" content="https://polhunter.com/">', '<meta property="og:url" content="https://polhunter.com/?r=' + encodeURIComponent(r) + '">');
} const h = Object.assign({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }, SEC);
if (ok) h['Set-Cookie'] = 'ph.ref=' + encodeURIComponent(r) + '; Path=/; Max-Age=2592000; SameSite=Lax; Secure';
// ---- sign-in by hand-off from InstantAdPay res.writeHead(200, h); return res.end(html);
if (p === '/auth') { }
if (!signupsOpen()) { res.writeHead(503, { 'Content-Type': 'text/plain' }); return res.end('PolHunter is not accepting hunters yet.'); }
const v = sso.verify(u.searchParams.get('t')); // ---- sign-in by hand-off from InstantAdPay
if (v.error) { res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('<p style="font:16px system-ui;padding:40px">' + v.error + '</p>'); } if (p === '/auth') {
const cur = sso.fromRequest(req); if (!signupsOpen()) { res.writeHead(503, { 'Content-Type': 'text/plain' }); return res.end('PolHunter is not accepting hunters yet.'); }
let sid = cur && cur.memberId === Number(v.claims.memberId) ? cur.sid : null; const v = sso.verify(u.searchParams.get('t'));
if (sid) sso.refresh(sid, v.claims); else sid = sso.startSession(v.claims); if (v.error) { res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('<p style="font:16px system-ui;padding:40px">' + v.error + '</p>'); }
referrals.seen(v.claims); // keep the hunter directory (and the sponsor behind it) current on every sign-in const cur = sso.fromRequest(req);
if (v.claims.gamePass != null) gp.rememberPass(v.claims.memberId, v.claims.email, v.claims.gamePass); // the Game Pass flag rides on the hand-off as gamePass:{active,until} (GAME-PASS.md 3a item 7) let sid = cur && cur.memberId === Number(v.claims.memberId) ? cur.sid : null;
res.writeHead(302, { Location: '/app', 'Set-Cookie': sso.cookie(sid), 'Cache-Control': 'no-store' }); return res.end(); if (sid) sso.refresh(sid, v.claims); else sid = sso.startSession(v.claims);
} referrals.seen(v.claims); // keep the hunter directory (and the sponsor behind it) current on every sign-in
if (p === '/logout') { const s = sso.fromRequest(req); if (s) sso.endSession(s.sid); res.writeHead(302, { Location: '/', 'Set-Cookie': sso.clearCookie() }); return res.end(); } if (v.claims.gamePass != null) gp.rememberPass(v.claims.memberId, v.claims.email, v.claims.gamePass); // the Game Pass flag rides on the hand-off as gamePass:{active,until} (GAME-PASS.md 3a item 7)
res.writeHead(302, { Location: '/app', 'Set-Cookie': sso.cookie(sid), 'Cache-Control': 'no-store' }); return res.end();
// ---- public }
// the last 24 hours for the shared 6 PM games summary in the achievements topic (counts only, no POL amounts) if (p === '/logout') { const s = sso.fromRequest(req); if (s) sso.endSession(s.sid); res.writeHead(302, { Location: '/', 'Set-Cookie': sso.clearCookie() }); return res.end(); }
if (p === '/api/public/today' && req.method === 'GET') {
const since = Date.now() - 24 * 3600000, t = v => typeof v === 'number' ? v : Date.parse(v) || 0; // ---- public
const pay = store.read('payouts', []).filter(x => x.status !== 'failed' && t(x.at) >= since && !x.prize && !(x.ref && x.ref.forName)); // the last 24 hours for the shared 6 PM games summary in the achievements topic (counts only, no POL amounts)
const hunters = Object.values(store.read('hunters', {})); if (p === '/api/public/today' && req.method === 'GET') {
return json(res, 200, { finds: pay.filter(x => !x.detective).length, cases: pay.filter(x => x.detective).length, hunters: new Set(pay.map(x => x.memberId)).size, newHunters: hunters.filter(h => t(h.firstSeen || h.joinedAt) >= since).length }); const since = Date.now() - 24 * 3600000, t = v => typeof v === 'number' ? v : Date.parse(v) || 0;
} const pay = store.read('payouts', []).filter(x => x.status !== 'failed' && t(x.at) >= since && !x.prize && !(x.ref && x.ref.forName));
if (p === '/api/config') { const ref = refOf(req); return json(res, 200, { name: 'PolHunter', signupsOpen: signupsOpen(), reward: rewards.settings(), iapUrl: 'https://instantadpay.com/my', explorer: explorer(), ref, joinUrl: ref ? 'https://instantadpay.com/join/' + encodeURIComponent(ref) + '?from=polhunter' : 'https://instantadpay.com/?from=polhunter' }); } const hunters = Object.values(store.read('hunters', {}));
if (p === '/api/leaders') { const per = ['week', 'month', 'all'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week'; return json(res, 200, { period: per, rows: social.leaderboard(per, 25) }, { 'Cache-Control': 'public, max-age=60' }); } return json(res, 200, { finds: pay.filter(x => !x.detective).length, cases: pay.filter(x => x.detective).length, hunters: new Set(pay.map(x => x.memberId)).size, newHunters: hunters.filter(h => t(h.firstSeen || h.joinedAt) >= since).length });
if (p === '/api/badges') return json(res, 200, { badges: social.BADGES.map(b => Object.assign({ art: '/badges/badge-' + b.id + '.jpg' }, b)) }); }
if (p === '/api/prizes') return json(res, 200, social.prizes(), { 'Cache-Control': 'public, max-age=60' }); if (p === '/api/config') { const ref = refOf(req); return json(res, 200, { name: 'PolHunter', signupsOpen: signupsOpen(), reward: rewards.settings(), iapUrl: 'https://instantadpay.com/my', explorer: explorer(), ref, joinUrl: ref ? 'https://instantadpay.com/join/' + encodeURIComponent(ref) + '?from=polhunter' : 'https://instantadpay.com/?from=polhunter' }); }
if (p === '/leaders') return sendFile(res, path.join(PUBLIC_DIR, 'leaders.html')); if (p === '/api/leaders') { const per = ['week', 'month', 'all'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week'; return json(res, 200, { period: per, rows: social.leaderboard(per, 25) }, { 'Cache-Control': 'public, max-age=60' }); }
if (p === '/promo') return sendFile(res, path.join(PUBLIC_DIR, 'promo.html')); if (p === '/api/badges') return json(res, 200, { badges: social.BADGES.map(b => Object.assign({ art: '/badges/badge-' + b.id + '.jpg' }, b)) });
if (p === '/terms' || p === '/privacy' || p === '/disclaimer') return sendFile(res, path.join(PUBLIC_DIR, p.slice(1) + '.html')); // legal pages (2026-11-17) if (p === '/api/prizes') return json(res, 200, social.prizes(), { 'Cache-Control': 'public, max-age=60' });
// evergreen Guides (Marty 2026-11-17): /guides and four pages, static files in public/guides if (p === '/leaders') return sendFile(res, path.join(PUBLIC_DIR, 'leaders.html'));
const GUIDES = ['how-a-hunt-works', 'is-polhunter-legit', 'free-account', 'faq']; if (p === '/promo') return sendFile(res, path.join(PUBLIC_DIR, 'promo.html'));
if (p === '/guides' || p === '/guides/') return sendFile(res, path.join(PUBLIC_DIR, 'guides', 'index.html')); if (p === '/terms' || p === '/privacy' || p === '/disclaimer') return sendFile(res, path.join(PUBLIC_DIR, p.slice(1) + '.html')); // legal pages (2026-11-17)
{ const gm = /^\/guides\/([a-z-]+)\/?$/.exec(p); if (gm && GUIDES.includes(gm[1])) return sendFile(res, path.join(PUBLIC_DIR, 'guides', gm[1] + '.html')); } // evergreen Guides (Marty 2026-11-17): /guides and four pages, static files in public/guides
if (p === '/sitemap.xml') { // the public pages (2026-11-17) const GUIDES = ['how-a-hunt-works', 'is-polhunter-legit', 'free-account', 'faq'];
const day = new Date().toISOString().slice(0, 10); if (p === '/guides' || p === '/guides/') return sendFile(res, path.join(PUBLIC_DIR, 'guides', 'index.html'));
const urls = ['/', '/leaders', '/promo', '/guides', ...GUIDES.map(g => '/guides/' + g), '/terms', '/disclaimer', '/privacy'].map(x => '<url><loc>' + SITE + x + '</loc><lastmod>' + day + '</lastmod></url>').join(''); { const gm = /^\/guides\/([a-z-]+)\/?$/.exec(p); if (gm && GUIDES.includes(gm[1])) return sendFile(res, path.join(PUBLIC_DIR, 'guides', gm[1] + '.html')); }
res.writeHead(200, Object.assign({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }, SEC)); if (p === '/sitemap.xml') { // the public pages (2026-11-17)
return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>'); const day = new Date().toISOString().slice(0, 10);
} const urls = ['/', '/leaders', '/promo', '/guides', ...GUIDES.map(g => '/guides/' + g), '/terms', '/disclaimer', '/privacy'].map(x => '<url><loc>' + SITE + x + '</loc><lastmod>' + day + '</lastmod></url>').join('');
if (p === '/robots.txt') { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }); return res.end('User-agent: *\nDisallow: /app\nDisallow: /admin\nSitemap: ' + SITE + '/sitemap.xml\n'); } res.writeHead(200, Object.assign({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }, SEC));
if (p === '/api/ledger') { const t = rewards.totals(); return json(res, 200, { totals: t, referrals: referrals.totals(), pools: { finds: rewards.pool(), referral: referrals.refPool() }, recent: rewards.ledger(30).map(x => ({ who: x.username ? '@' + x.username : '#' + x.memberId, site: x.site, pol: x.pol, tx: x.tx, at: x.paidAt })) }); } return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>');
}
// ---- hunter (session required) if (p === '/robots.txt') { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }); return res.end('User-agent: *\nDisallow: /app\nDisallow: /admin\nSitemap: ' + SITE + '/sitemap.xml\n'); }
if (p.startsWith('/api/my/')) { if (p === '/api/ledger') { const t = rewards.totals(); return json(res, 200, { totals: t, referrals: referrals.totals(), pools: { finds: rewards.pool(), referral: referrals.refPool() }, recent: rewards.ledger(30).map(x => ({ who: x.username ? '@' + x.username : '#' + x.memberId, site: x.site, pol: x.pol, tx: x.tx, at: x.paidAt })) }); }
const me = sso.fromRequest(req); if (!me) return json(res, 401, { error: 'Open PolHunter from your InstantAdPay dashboard to sign in.' });
if (p === '/api/my/board') { // ---- hunter (session required)
const fbank = await fbFor(me); if (p.startsWith('/api/my/')) {
if (gp.on()) gp.fetchPass(me.memberId, me.email).catch(() => {}); // keep the Game Pass flag fresh (display + perks; grant answers carry the truth) const me = sso.fromRequest(req); if (!me) return json(res, 401, { error: 'Open PolHunter from your InstantAdPay dashboard to sign in.' });
referrals.seen(me); // hunters already signed in never pass through /auth again, so keep the directory fresh here too if (p === '/api/my/board') {
const done = rewards.doneToday(me.memberId, me.wallet); // today's finds, by member id or wallet const fbank = await fbFor(me);
// the Network Tour: open this round first (never visited, then least recently found), then today's finds marked done if (gp.on()) gp.fetchPass(me.memberId, me.email).catch(() => {}); // keep the Game Pass flag fresh (display + perks; grant answers carry the truth)
const rot = rotation.state(me), free = !fullTier(me), rc = rotation.cfg(); referrals.seen(me); // hunters already signed in never pass through /auth again, so keep the directory fresh here too
const offered = rotation.order(me, rot).filter(m => !done.has(m.id)), doneList = missions.forMember(me.memberId).filter(m => done.has(m.id)); const done = rewards.doneToday(me.memberId, me.wallet); // today's finds, by member id or wallet
const boardMissions = offered.concat(doneList).map(m => Object.assign(pubMission(m), { done: done.has(m.id), fresh: !m.paid && !rot.last.has(m.id), tourStop: free && !m.paid && rot.last.has(m.id) ? { credits: rc.credits } : undefined })); // the Network Tour: open this round first (never visited, then least recently found), then today's finds marked done
const tour = { on: rot.on, round: rot.round, rounds: rot.rounds, done: rot.done, total: rot.total, left: [...new Set(rot.left.map(m => m.site))], toured: rot.toured, free, tourStopCredits: rc.credits }; const rot = rotation.state(me), free = !fullTier(me), rc = rotation.cfg();
return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet }, missions: boardMissions, tour, drips: rewards.mine(me.memberId).slice(0, 20), faucet: { on: faucetOn }, pool: rewards.pool(), daily: rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fbank.bonus, passExtra(me), fullTier(me)), /* the tier, as start/submit pass it (the board showed a Pass holder 3, not 5) */ fridayBank: fbank, gamepass: gp.view(me.memberId, me.email), const offered = rotation.order(me, rot).filter(m => !done.has(m.id)), doneList = missions.forMember(me.memberId).filter(m => done.has(m.id));
badges: social.badgesFor(me.memberId), badgeCards: (() => { const got = new Set(social.badgesFor(me.memberId).map(b => b.id)); const who = social.nameOf(me); return social.BADGES.map(b => ({ id: b.id, name: b.name, icon: b.icon, why: b.why, count: b.id === 'sweep' && rot.rounds > 1 ? rot.rounds : undefined, art: '/badges/badge-' + b.id + '.jpg', earned: got.has(b.id), page: got.has(b.id) ? SITE + '/b/' + who + '/' + b.id : null, image: got.has(b.id) ? SITE + '/badge-img/' + who + '/' + b.id + '.jpg' : null })); })(), rank: { week: social.rankOf(me.memberId, 'week'), month: social.rankOf(me.memberId, 'month'), all: social.rankOf(me.memberId, 'all') }, const boardMissions = offered.concat(doneList).map(m => Object.assign(pubMission(m), { done: done.has(m.id), fresh: !m.paid && !rot.last.has(m.id), tourStop: free && !m.paid && rot.last.has(m.id) ? { credits: rc.credits } : undefined }));
share: { link: social.shareLink(SITE, me), joinUrl: 'https://instantadpay.com/join/' + encodeURIComponent(String(me.username || me.memberId)) + '?from=polhunter' }, const tour = { on: rot.on, round: rot.round, rounds: rot.rounds, done: rot.done, total: rot.total, left: [...new Set(rot.left.map(m => m.site))], toured: rot.toured, free, tourStopCredits: rc.credits };
referral: referrals.state(me), box: detective.view(me, fullTier(me)) }); return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet }, missions: boardMissions, tour, drips: rewards.mine(me.memberId).slice(0, 20), faucet: { on: faucetOn }, pool: rewards.pool(), daily: rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fbank.bonus, passExtra(me), fullTier(me)), /* the tier, as start/submit pass it (the board showed a Pass holder 3, not 5) */ fridayBank: fbank, gamepass: gp.view(me.memberId, me.email),
} badges: social.badgesFor(me.memberId), badgeCards: (() => { const got = new Set(social.badgesFor(me.memberId).map(b => b.id)); const who = social.nameOf(me); return social.BADGES.map(b => ({ id: b.id, name: b.name, icon: b.icon, why: b.why, count: b.id === 'sweep' && rot.rounds > 1 ? rot.rounds : undefined, art: '/badges/badge-' + b.id + '.jpg', earned: got.has(b.id), page: got.has(b.id) ? SITE + '/b/' + who + '/' + b.id : null, image: got.has(b.id) ? SITE + '/badge-img/' + who + '/' + b.id + '.jpg' : null })); })(), rank: { week: social.rankOf(me.memberId, 'week'), month: social.rankOf(me.memberId, 'month'), all: social.rankOf(me.memberId, 'all') },
if (p === '/api/my/start' && req.method === 'POST') { share: { link: social.shareLink(SITE, me), joinUrl: 'https://instantadpay.com/join/' + encodeURIComponent(String(me.username || me.memberId)) + '?from=polhunter' },
const b = await readBody(req); const m = missions.get(String(b.missionId || '')); if (!m || !m.active) return json(res, 404, { error: 'That mission is not open.' }); referral: referrals.state(me), box: detective.view(me, fullTier(me)),
if (!me.wallet) return json(res, 400, { error: 'Link a wallet on InstantAdPay first so the drip has somewhere to land, then open PolHunter again.' }); // the mission they started and have not claimed yet: the board brings its code box back after a reload
if (rewards.completed(me.memberId, m.id, me.wallet)) return json(res, 400, { error: 'You already completed this one.' }); open: (() => { for (const r of missions.live(me.memberId)) { const m = missions.get(r.missionId); if (m && m.active && !done.has(m.id)) return { missionId: m.id, token: r.t, url: missionUrl(m, r.t), dwell: m.dwell || 30, started: r.iat, expires: r.exp }; } return null; })() });
if (rotation.blocked(me, m)) return json(res, 400, { error: 'You found this one already this round. The rest of the network tour comes first.', tour: true }); }
{ const pool = rewards.pool(); if (pool.spent) return json(res, 400, { error: SPENT_MSG, spent: true, resetsAt: pool.resetsAt }); } if (p === '/api/my/start' && req.method === 'POST') {
{ const fb = await fbFor(me); const d = rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fb.bonus, passExtra(me), fullTier(me)); if (!d.left) return json(res, 400, { error: dailyMsg(d), dailyDone: true, resetsAt: rewards.pool().resetsAt }); } const b = await readBody(req); const m = missions.get(String(b.missionId || '')); if (!m || !m.active) return json(res, 404, { error: 'That mission is not open.' });
if (limited('start:' + me.memberId, 20, 3600000)) return json(res, 429, { error: 'Easy. Twenty starts an hour is plenty.' }); if (!me.wallet) return json(res, 400, { error: 'Link a wallet on InstantAdPay first so the drip has somewhere to land, then open PolHunter again.' });
const t = missions.issue(me.memberId, m.id); if (rewards.completed(me.memberId, m.id, me.wallet)) return json(res, 400, { error: 'You already completed this one.' });
// a mission URL may place the token itself with {token} (a Telegram Mini App takes it in if (rotation.blocked(me, m)) return json(res, 400, { error: 'You found this one already this round. The rest of the network tour comes first.', tour: true });
// ?startapp=, not as our own query string); otherwise it is appended as ?ph= { const pool = rewards.pool(); if (pool.spent) return json(res, 400, { error: SPENT_MSG, spent: true, resetsAt: pool.resetsAt }); }
// the token rides in the hash: a server never sees it, so no redirect or canonical rewrite can lose it { const fb = await fbFor(me); const d = rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fb.bonus, passExtra(me), fullTier(me)); if (!d.left) return json(res, 400, { error: dailyMsg(d), dailyDone: true, resetsAt: rewards.pool().resetsAt }); }
const url = m.url.includes('{token}') ? m.url.replace('{token}', t.t) : m.url + '#ph=' + t.t; if (limited('start:' + me.memberId, 20, 3600000)) return json(res, 429, { error: 'Easy. Twenty starts an hour is plenty.' });
return json(res, 200, { ok: true, token: t.t, url, dwell: m.dwell || 30, expires: t.exp }); // a second Start on the same mission hands back the live token (3+ minutes left), so a code already on screen keeps matching
} const t = missions.live(me.memberId, m.id).find(r => r.exp - Date.now() > 180000) || missions.issue(me.memberId, m.id);
if (p === '/api/my/submit' && req.method === 'POST') { return json(res, 200, { ok: true, token: t.t, url: missionUrl(m, t.t), dwell: m.dwell || 30, started: t.iat, expires: t.exp });
const b = await readBody(req); }
if (limited('submit:' + me.memberId, 30, 3600000)) return json(res, 429, { error: 'Too many tries. Take a breath.' }); if (p === '/api/my/submit' && req.method === 'POST') {
const c = missions.check(String(b.token || ''), me.memberId, b.code); if (c.error) return json(res, 400, { error: c.error }); const b = await readBody(req);
const m = missions.get(c.rec.missionId); if (!m) return json(res, 404, { error: 'That mission is gone.' }); if (limited('submit:' + me.memberId, 30, 3600000)) return json(res, 429, { error: 'Too many tries. Take a breath.' });
if (rewards.completed(me.memberId, m.id, me.wallet)) return json(res, 400, { error: 'You already completed this one.' }); const c = missions.check(String(b.token || ''), me.memberId, b.code); if (c.error) return json(res, 400, { error: c.error });
{ const pool = rewards.pool(); if (pool.spent) return json(res, 400, { error: SPENT_MSG, spent: true, resetsAt: pool.resetsAt }); } const m = missions.get(c.rec.missionId); if (!m) return json(res, 404, { error: 'That mission is gone.' });
{ const fb = await fbFor(me); const d = rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fb.bonus, passExtra(me), fullTier(me)); if (!d.left) return json(res, 400, { error: dailyMsg(d), dailyDone: true, resetsAt: rewards.pool().resetsAt }); } if (rewards.completed(me.memberId, m.id, me.wallet)) return json(res, 400, { error: 'You already completed this one.' });
const before = new Set(social.badgesFor(me.memberId).map(b => b.id)); const roundsBefore = rotation.state(me).rounds; { const pool = rewards.pool(); if (pool.spent) return json(res, 400, { error: SPENT_MSG, spent: true, resetsAt: pool.resetsAt }); }
// a free member's repeat find (Marty 2026-11-17): a tour stop, ad credits instead of POL; counts as the day's hunt and for the tour { const fb = await fbFor(me); const d = rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fb.bonus, passExtra(me), fullTier(me)); if (!d.left) return json(res, 400, { error: dailyMsg(d), dailyDone: true, resetsAt: rewards.pool().resetsAt }); }
if (isTourStop(me, m)) { const before = new Set(social.badgesFor(me.memberId).map(b => b.id)); const roundsBefore = rotation.state(me).rounds;
const row = rotation.tourStop(me, m); const roundsNow = rotation.state(me).rounds; // a free member's repeat find (Marty 2026-11-17): a tour stop, ad credits instead of POL; counts as the day's hunt and for the tour
const unlocked = social.badgesFor(me.memberId).filter(b => !before.has(b.id)); if (isTourStop(me, m)) {
for (const b of unlocked) notify('badge', { me, id: b.id }).catch(() => {}); const row = rotation.tourStop(me, m); const roundsNow = rotation.state(me).rounds;
const show = unlocked.map(b => b.id); if (roundsNow > roundsBefore && !show.includes('sweep')) show.push('sweep'); // a new round closed: celebrate again const unlocked = social.badgesFor(me.memberId).filter(b => !before.has(b.id));
rotation.deliver(row, gp).catch(e => console.error('tour stop', e.message)); // signed call to InstantAdPay; owed and retried if it fails for (const b of unlocked) notify('badge', { me, id: b.id }).catch(() => {});
const cr = row.tourStop.credits; const show = unlocked.map(b => b.id); if (roundsNow > roundsBefore && !show.includes('sweep')) show.push('sweep'); // a new round closed: celebrate again
return json(res, 200, { ok: true, pol: 0, tourStop: { credits: cr }, unlocked: show, round: roundsNow > roundsBefore ? roundsNow : null, gamepass: gp.view(me.memberId, me.email), rotation.deliver(row, gp).catch(e => console.error('tour stop', e.message)); // signed call to InstantAdPay; owed and retried if it fails
message: 'Tour stop logged. ' + (cr > 0 ? '+' + cr + ' ad credits are on their way to your InstantAdPay account.' : 'Today\u2019s tour-stop ad credits are already yours.') + ' New sites pay POL on your first find, and the Game Pass pays POL on every hunt.' }); const cr = row.tourStop.credits;
} return json(res, 200, { ok: true, pol: 0, tourStop: { credits: cr }, unlocked: show, round: roundsNow > roundsBefore ? roundsNow : null, gamepass: gp.view(me.memberId, me.email),
let g, note = null; message: 'Tour stop logged. ' + (cr > 0 ? '+' + cr + ' ad credits are on their way to your InstantAdPay account.' : 'Today\u2019s tour-stop ad credits are already yours.') + ' New sites pay POL on your first find, and the Game Pass pays POL on every hunt.' });
if (gp.on() && !m.paid) { // the Game Pass: IAP's account-wide daily cap first (a paid mission is the advertiser's money, not gated) }
const quote = rewards.quote(m, fullTier(me)), ref = 'find:' + m.id + ':' + missions.ctDay(), r = await gpGate(me).ask(quote, ref); note = r.note; let g, note = null;
if (r.retry) { g = rewards.grant(me, m, { pol: quote, status: 'gp-wait', nominal: quote, gp: { ref, kind: 'daily', nominal: quote, pending: true } }); if (!g.error) gpGate(me).wait(g.rec.id, quote, ref); } if (gp.on() && !m.paid) { // the Game Pass: IAP's account-wide daily cap first (a paid mission is the advertiser's money, not gated)
else g = rewards.grant(me, m, { pol: r.allowed, nominal: quote, gp: { ref, kind: 'daily', nominal: quote, pass: !!r.pass, capHit: r.capHit || null } }); const quote = rewards.quote(m, fullTier(me)), ref = 'find:' + m.id + ':' + missions.ctDay(), r = await gpGate(me).ask(quote, ref); note = r.note;
} else g = rewards.grant(me, m, { pass: fullTier(me) }); if (r.retry) { g = rewards.grant(me, m, { pol: quote, status: 'gp-wait', nominal: quote, gp: { ref, kind: 'daily', nominal: quote, pending: true } }); if (!g.error) gpGate(me).wait(g.rec.id, quote, ref); }
if (g.error) return json(res, 400, g); else g = rewards.grant(me, m, { pol: r.allowed, nominal: quote, gp: { ref, kind: 'daily', nominal: quote, pass: !!r.pass, capHit: r.capHit || null } });
// whoever brought this hunter gets paid for it: the bounty on their first find, a match while they are new } else g = rewards.grant(me, m, { pass: fullTier(me) });
let refDrips = []; if (g.error) return json(res, 400, g);
try { refDrips = referrals.onFind(me, g.rec); } catch (e) { console.error('referral', e.message); } // whoever brought this hunter gets paid for it: the bounty on their first find, a match while they are new
for (const d of refDrips) if (d.ref.kind === 'bounty' || d.ref.kind === 'first-bonus') notify(d.ref.kind === 'bounty' ? 'referral' : 'firstbonus', { drip: d }).catch(() => {}); let refDrips = [];
// achievements unlocked by this find: told to the board, posted to Telegram (gated) try { refDrips = referrals.onFind(me, g.rec); } catch (e) { console.error('referral', e.message); }
const roundsNow = rotation.state(me).rounds; for (const d of refDrips) if (d.ref.kind === 'bounty' || d.ref.kind === 'first-bonus') notify(d.ref.kind === 'bounty' ? 'referral' : 'firstbonus', { drip: d }).catch(() => {});
const unlocked = social.badgesFor(me.memberId).filter(b => !before.has(b.id)); // achievements unlocked by this find: told to the board, posted to Telegram (gated)
for (const b of unlocked) notify('badge', { me, id: b.id }).catch(() => {}); const roundsNow = rotation.state(me).rounds;
const show = unlocked.map(b => b.id); if (roundsNow > roundsBefore && !show.includes('sweep')) show.push('sweep'); // Full Network Tour again: board only, Telegram posts a badge once const unlocked = social.badgesFor(me.memberId).filter(b => !before.has(b.id));
return json(res, 200, { ok: true, pol: g.waiting ? 0 : g.rec.pol, nominal: g.rec.nominal, queued: g.queued, capped: g.capped, waiting: g.waiting, note, unlocked: show, round: roundsNow > roundsBefore ? roundsNow : null, gamepass: gp.view(me.memberId, me.email), for (const b of unlocked) notify('badge', { me, id: b.id }).catch(() => {});
message: g.waiting ? 'Found it. ' + note : g.capped ? 'Found it. ' + note : g.queued ? 'Found it. Today’s POL is spoken for, so yours is queued and pays out next.' : 'Found it. ' + fmt(g.rec.pol) + ' POL is on its way to your wallet.' + (note ? ' ' + note : '') }); const show = unlocked.map(b => b.id); if (roundsNow > roundsBefore && !show.includes('sweep')) show.push('sweep'); // Full Network Tour again: board only, Telegram posts a badge once
} return json(res, 200, { ok: true, pol: g.waiting ? 0 : g.rec.pol, nominal: g.rec.nominal, queued: g.queued, capped: g.capped, waiting: g.waiting, note, unlocked: show, round: roundsNow > roundsBefore ? roundsNow : null, gamepass: gp.view(me.memberId, me.email),
// ---- Mystery Hunt Box + Ad Detective message: g.waiting ? 'Found it. ' + note : g.capped ? 'Found it. ' + note : g.queued ? 'Found it. Today’s POL is spoken for, so yours is queued and pays out next.' : 'Found it. ' + fmt(g.rec.pol) + ' POL is on its way to your wallet.' + (note ? ' ' + note : '') });
if (p === '/api/my/box/open' && req.method === 'POST') { const r = detective.open(me, passActive(me), fullTier(me)); return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, box: detective.view(me, fullTier(me)) }); } // pass: a second case a day }
if (p === '/api/my/box/start' && req.method === 'POST') { // ---- Mystery Hunt Box + Ad Detective
if (!me.wallet) return json(res, 400, { error: 'Link a wallet on InstantAdPay first so the reward has somewhere to land.' }); if (p === '/api/my/box/open' && req.method === 'POST') { const r = detective.open(me, passActive(me), fullTier(me)); return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, box: detective.view(me, fullTier(me)) }); } // pass: a second case a day
if (limited('boxstart:' + me.memberId, 20, 3600000)) return json(res, 429, { error: 'Easy. Try again in a little while.' }); if (p === '/api/my/box/start' && req.method === 'POST') {
const r = detective.start(me); return json(res, r.error ? 400 : 200, r); if (!me.wallet) return json(res, 400, { error: 'Link a wallet on InstantAdPay first so the reward has somewhere to land.' });
} if (limited('boxstart:' + me.memberId, 20, 3600000)) return json(res, 429, { error: 'Easy. Try again in a little while.' });
if (p === '/api/my/box/answer' && req.method === 'POST') { const r = detective.start(me); return json(res, r.error ? 400 : 200, r);
const b = await readBody(req); }
if (limited('boxans:' + me.memberId, 10, 3600000)) return json(res, 429, { error: 'Easy. Try again in a little while.' }); if (p === '/api/my/box/answer' && req.method === 'POST') {
const before = new Set(social.badgesFor(me.memberId).map(x => x.id)); const b = await readBody(req);
const r = await detective.answer(me, b.choice, gp.on() ? gpGate(me) : null); if (r.error) return json(res, 400, r); if (limited('boxans:' + me.memberId, 10, 3600000)) return json(res, 429, { error: 'Easy. Try again in a little while.' });
const unlocked = r.correct ? social.badgesFor(me.memberId).filter(x => !before.has(x.id)) : []; const before = new Set(social.badgesFor(me.memberId).map(x => x.id));
for (const x of unlocked) notify('badge', { me, id: x.id }).catch(() => {}); const r = await detective.answer(me, b.choice, gp.on() ? gpGate(me) : null); if (r.error) return json(res, 400, r);
const msg = r.correct ? (r.queued ? 'Case solved. Today\u2019s POL is spoken for, so your ' + fmt(r.pol) + ' POL is queued and pays out next.' : 'Case solved. ' + fmt(r.pol) + ' POL is on its way to your wallet.') : 'Not this time. The answer was: ' + r.answer + '. A new box unlocks tomorrow.'; const unlocked = r.correct ? social.badgesFor(me.memberId).filter(x => !before.has(x.id)) : [];
return json(res, 200, { ok: true, correct: r.correct, pol: r.pol, nominal: r.nominal, queued: r.queued, capped: r.capped, waiting: r.waiting, note: r.note || null, unlocked: unlocked.map(x => x.id), message: msg + (r.note ? ' ' + r.note : ''), box: detective.view(me, fullTier(me)), gamepass: gp.view(me.memberId, me.email) }); for (const x of unlocked) notify('badge', { me, id: x.id }).catch(() => {});
} const msg = r.correct ? (r.queued ? 'Case solved. Today\u2019s POL is spoken for, so your ' + fmt(r.pol) + ' POL is queued and pays out next.' : 'Case solved. ' + fmt(r.pol) + ' POL is on its way to your wallet.') : 'Not this time. The answer was: ' + r.answer + '. A new box unlocks tomorrow.';
return json(res, 404, { error: 'No such call.' }); return json(res, 200, { ok: true, correct: r.correct, pol: r.pol, nominal: r.nominal, queued: r.queued, capped: r.capped, waiting: r.waiting, note: r.note || null, unlocked: unlocked.map(x => x.id), message: msg + (r.note ? ' ' + r.note : ''), box: detective.view(me, fullTier(me)), gamepass: gp.view(me.memberId, me.email) });
} }
return json(res, 404, { error: 'No such call.' });
// ---- admin (key) }
if (p.startsWith('/api/admin/')) {
if (!admin(req)) return json(res, 401, { error: 'Admin key required.' }); // ---- admin (key)
if (p === '/api/admin/state') return json(res, 200, { missions: missions.list(), settings: rewards.settings(), totals: rewards.totals(), referrals: referrals.totals(), referralPool: referrals.refPool(), faucet: { on: faucetOn, address: faucet.address(), state: store.read('faucet-state', {}) }, payouts: store.read('payouts', []).slice(-100).reverse(), gates: { outbound: outbound(), signups: signupsOpen(), curtain: !!CURTAIN, sso: sso.enabled() }, gamepass: { on: gp.on(), iap: IAP_URL, queue: gp.queue().length, stuck: gp.queue().filter(x => x.stuck).length }, tournament: tournament.state() }); if (p.startsWith('/api/admin/')) {
if (p === '/api/admin/mission' && req.method === 'POST') { if (!admin(req)) return json(res, 401, { error: 'Admin key required.' });
const b = await readBody(req); if (p === '/api/admin/state') return json(res, 200, { missions: missions.list(), settings: rewards.settings(), totals: rewards.totals(), referrals: referrals.totals(), referralPool: referrals.refPool(), faucet: { on: faucetOn, address: faucet.address(), state: store.read('faucet-state', {}) }, payouts: store.read('payouts', []).slice(-100).reverse(), gates: { outbound: outbound(), signups: signupsOpen(), curtain: !!CURTAIN, sso: sso.enabled() }, gamepass: { on: gp.on(), iap: IAP_URL, queue: gp.queue().length, stuck: gp.queue().filter(x => x.stuck).length }, tournament: tournament.state() });
const id = String(b.id || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 40); if (!id) return json(res, 400, { error: 'id required' }); if (p === '/api/admin/mission' && req.method === 'POST') {
let host = ''; try { host = new URL(String(b.url)).hostname.replace(/^www\./, ''); } catch (e) { return json(res, 400, { error: 'url must be a full https URL' }); } const b = await readBody(req);
// the origin the embed calls from can differ from the link (a t.me launch link opens a Mini App on its own host) const id = String(b.id || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 40); if (!id) return json(res, 400, { error: 'id required' });
if (b.host) host = String(b.host).trim().toLowerCase().replace(/^https?:\/\//, '').replace(/^www\./, '').replace(/\/.*$/, ''); let host = ''; try { host = new URL(String(b.url)).hostname.replace(/^www\./, ''); } catch (e) { return json(res, 400, { error: 'url must be a full https URL' }); }
missions.save({ id, site: String(b.site || host).slice(0, 60), host, name: String(b.name || '').slice(0, 80), brief: String(b.brief || '').slice(0, 400), url: String(b.url), dwell: Math.max(5, Number(b.dwell) || 45), slots: Math.max(1, Number(b.slots) || 1), budget: Math.max(0, Number(b.budget) || 0), active: b.active !== false }); // the origin the embed calls from can differ from the link (a t.me launch link opens a Mini App on its own host)
return json(res, 200, { ok: true, missions: missions.list() }); if (b.host) host = String(b.host).trim().toLowerCase().replace(/^https?:\/\//, '').replace(/^www\./, '').replace(/\/.*$/, '');
} missions.save({ id, site: String(b.site || host).slice(0, 60), host, name: String(b.name || '').slice(0, 80), brief: String(b.brief || '').slice(0, 400), url: String(b.url), dwell: Math.max(5, Number(b.dwell) || 45), slots: Math.max(1, Number(b.slots) || 1), budget: Math.max(0, Number(b.budget) || 0), active: b.active !== false });
if (p === '/api/admin/mission' && req.method === 'DELETE') { const b = await readBody(req); missions.remove(String(b.id || '')); return json(res, 200, { ok: true, missions: missions.list() }); } return json(res, 200, { ok: true, missions: missions.list() });
if (p === '/api/admin/settings' && req.method === 'POST') { const b = await readBody(req); const patch = {}; for (const k of ['minPol', 'maxPol', 'dailyCapPol', 'lowBalancePol', 'weeklyMinFinds', 'drawSkew', 'missionsPerDay', 'freeMissionsPerDay', 'freeMinPol', 'freeMaxPol', 'detectiveOn', 'detectivePol', 'refEnabled', 'refBountyPol', 'refMatchPct', 'refMatchDays', 'refNewDays', 'refCapPol', 'refMatchMinPol', 'rotationOn', 'tourStopCredits', 'tourStopCreditsDailyMax']) if (b[k] != null && Number(b[k]) >= 0) patch[k] = Number(b[k]); for (const k of ['weeklyPrizes', 'leaderboardExclude']) if (Array.isArray(b[k])) patch[k] = b[k].map(Number).filter(n => n >= 0); return json(res, 200, { ok: true, settings: rewards.setSettings(patch) }); } }
// award a week by hand (its Monday key); already-awarded weeks are skipped if (p === '/api/admin/mission' && req.method === 'DELETE') { const b = await readBody(req); missions.remove(String(b.id || '')); return json(res, 200, { ok: true, missions: missions.list() }); }
if (p === '/api/admin/prizes/award' && req.method === 'POST') { const b = await readBody(req); const r = social.awardWeek(String(b.week || '')); if (r && r.winners && r.winners.length) notify('prize', r).catch(() => {}); return json(res, r && r.error ? 400 : 200, r); } if (p === '/api/admin/settings' && req.method === 'POST') { const b = await readBody(req); const patch = {}; for (const k of ['minPol', 'maxPol', 'dailyCapPol', 'lowBalancePol', 'weeklyMinFinds', 'drawSkew', 'missionsPerDay', 'freeMissionsPerDay', 'freeMinPol', 'freeMaxPol', 'detectiveOn', 'detectivePol', 'refEnabled', 'refBountyPol', 'refMatchPct', 'refMatchDays', 'refNewDays', 'refCapPol', 'refMatchMinPol', 'rotationOn', 'tourStopCredits', 'tourStopCreditsDailyMax']) if (b[k] != null && Number(b[k]) >= 0) patch[k] = Number(b[k]); for (const k of ['weeklyPrizes', 'leaderboardExclude']) if (Array.isArray(b[k])) patch[k] = b[k].map(Number).filter(n => n >= 0); return json(res, 200, { ok: true, settings: rewards.setSettings(patch) }); }
// award a week by hand (its Monday key); already-awarded weeks are skipped
if (p === '/api/admin/prizes/award' && req.method === 'POST') { const b = await readBody(req); const r = social.awardWeek(String(b.week || '')); if (r && r.winners && r.winners.length) notify('prize', r).catch(() => {}); return json(res, r && r.error ? 400 : 200, r); }
// one-time catch-up for an already-awarded week (2026-11-23), ignoring the Pass: pays the places that went unpaid, never anyone twice // one-time catch-up for an already-awarded week (2026-11-23), ignoring the Pass: pays the places that went unpaid, never anyone twice
if (p === '/api/admin/prizes/fill' && req.method === 'POST') { const b = await readBody(req); const r = social.awardFill(String(b.week || '')); if (r && r.winners && r.winners.length) notify('prize', r).catch(() => {}); return json(res, r && r.error ? 400 : 200, r); } if (p === '/api/admin/prizes/fill' && req.method === 'POST') { const b = await readBody(req); const r = social.awardFill(String(b.week || '')); if (r && r.winners && r.winners.length) notify('prize', r).catch(() => {}); return json(res, r && r.error ? 400 : 200, r); }
// Ad Detective question bank: stats per question, add or edit one, retire or restore one // Ad Detective question bank: stats per question, add or edit one, retire or restore one
if (p === '/api/admin/rotation') return json(res, 200, rotation.adminView()); // the Network Tour: rounds per hunter, tour-stop credits sent / owed if (p === '/api/admin/rotation') return json(res, 200, rotation.adminView()); // the Network Tour: rounds per hunter, tour-stop credits sent / owed
if (p === '/api/admin/detective') return json(res, 200, detective.stats()); if (p === '/api/admin/detective') return json(res, 200, detective.stats());
if (p === '/api/admin/detective/question' && req.method === 'POST') { const b = await readBody(req); if (b.id && b.active != null && !b.q) return json(res, detective.setActive(String(b.id), !!b.active) ? 200 : 404, { ok: true }); const r = detective.saveQuestion(b); return json(res, r.error ? 400 : 200, r); } if (p === '/api/admin/detective/question' && req.method === 'POST') { const b = await readBody(req); if (b.id && b.active != null && !b.q) return json(res, detective.setActive(String(b.id), !!b.active) ? 200 : 404, { ok: true }); const r = detective.saveQuestion(b); return json(res, r.error ? 400 : 200, r); }
if (p === '/api/admin/drip/retry' && req.method === 'POST') { const b = await readBody(req); rewards.mark(String(b.id || ''), { status: 'due', error: null }); return json(res, 200, { ok: true }); } if (p === '/api/admin/drip/retry' && req.method === 'POST') { const b = await readBody(req); rewards.mark(String(b.id || ''), { status: 'due', error: null }); return json(res, 200, { ok: true }); }
if (p === '/api/admin/faucet/tick' && req.method === 'POST') { const r = await faucet.tick(notify); return json(res, 200, Object.assign(r, { balance: await faucet.balance() })); } if (p === '/api/admin/faucet/tick' && req.method === 'POST') { const r = await faucet.tick(notify); return json(res, 200, Object.assign(r, { balance: await faucet.balance() })); }
if (p === '/api/admin/embed-test') { // mint a token for any mission so the embed can be tried without a hunter if (p === '/api/admin/embed-test') { // mint a token for any mission so the embed can be tried without a hunter
const m = missions.get(String(u.searchParams.get('id') || '')); if (!m) return json(res, 404, { error: 'no such mission' }); const m = missions.get(String(u.searchParams.get('id') || '')); if (!m) return json(res, 404, { error: 'no such mission' });
const t = missions.issue(0, m.id); return json(res, 200, { url: m.url.includes('{token}') ? m.url.replace('{token}', t.t) : m.url + '#ph=' + t.t, token: t.t, dwell: m.dwell }); const t = missions.issue(0, m.id); return json(res, 200, { url: m.url.includes('{token}') ? m.url.replace('{token}', t.t) : m.url + '#ph=' + t.t, token: t.t, dwell: m.dwell });
} }
return json(res, 404, { error: 'No such admin call.' }); return json(res, 404, { error: 'No such admin call.' });
} }
if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html')); if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html'));
if (p === '/app') { if (!sso.fromRequest(req)) { res.writeHead(302, { Location: '/?signin=1' }); return res.end(); } return sendFile(res, path.join(PUBLIC_DIR, 'app.html')); } if (p === '/app') { if (!sso.fromRequest(req)) { res.writeHead(302, { Location: '/?signin=1' }); return res.end(); } return sendFile(res, path.join(PUBLIC_DIR, 'app.html')); }
if (p.startsWith('/api/')) return json(res, 404, { error: 'No such call.' }); if (p.startsWith('/api/')) return json(res, 404, { error: 'No such call.' });
const safe = path.normalize(p).replace(/^(\.\.[/\\])+/, ''); const safe = path.normalize(p).replace(/^(\.\.[/\\])+/, '');
const file = path.join(PUBLIC_DIR, safe === '/' || safe === '\\' ? 'index.html' : safe); const file = path.join(PUBLIC_DIR, safe === '/' || safe === '\\' ? 'index.html' : safe);
if (!file.startsWith(PUBLIC_DIR)) { res.writeHead(400); return res.end(); } if (!file.startsWith(PUBLIC_DIR)) { res.writeHead(400); return res.end(); }
return sendFile(res, file); return sendFile(res, file);
} catch (e) { console.error(req.method, req.url, e.message); try { json(res, 500, { error: 'Internal server error' }); } catch (x) {} } } catch (e) { console.error(req.method, req.url, e.message); try { json(res, 500, { error: 'Internal server error' }); } catch (x) {} }
}); });
// the faucet pays every two minutes; nothing outward leaves unless OUTBOUND=on (telegram checks) // the faucet pays every two minutes; nothing outward leaves unless OUTBOUND=on (telegram checks)
if (faucetOn) setInterval(() => faucet.tick(notify).catch(e => console.error('faucet', e.message)), 2 * 60000); if (faucetOn) setInterval(() => faucet.tick(notify).catch(e => console.error('faucet', e.message)), 2 * 60000);
// Game Pass: refs that could not reach InstantAdPay retry every 5 minutes (lib/polgrant.js); the weekly Pass Tournament prizes are // Game Pass: refs that could not reach InstantAdPay retry every 5 minutes (lib/polgrant.js); the weekly Pass Tournament prizes are
// paid from this faucet every 10 minutes (lib/tournament.js). Both are inert unless GAMEPASS=on; prizes need the faucet wallet too. // paid from this faucet every 10 minutes (lib/tournament.js). Both are inert unless GAMEPASS=on; prizes need the faucet wallet too.
gp.startRetry(payQueued); if (faucetOn) tournament.start(); gp.startRetry(payQueued); if (faucetOn) tournament.start();
// tour-stop ad credits InstantAdPay has not confirmed yet are retried every two minutes (owed until then) // tour-stop ad credits InstantAdPay has not confirmed yet are retried every two minutes (owed until then)
setInterval(() => { if (gp.on()) rotation.retryDue(gp).catch(e => console.error('tour stops', e.message)); }, 2 * 60000); setInterval(() => { if (gp.on()) rotation.retryDue(gp).catch(e => console.error('tour stops', e.message)); }, 2 * 60000);
// Every completed mission reaches Telegram (Marty, 2026-09-21): a find is posted when its drip is paid, and // Every completed mission reaches Telegram (Marty, 2026-09-21): a find is posted when its drip is paid, and
// this sweep posts any paid find that is not marked posted yet (the pre-live gate, Telegram down, a restart). // this sweep posts any paid find that is not marked posted yet (the pre-live gate, Telegram down, a restart).
// Only finds made after HUNT_POST_SINCE count, so rehearsal drips from before the doors opened stay quiet. // Only finds made after HUNT_POST_SINCE count, so rehearsal drips from before the doors opened stay quiet.
const POST_SINCE = process.env.HUNT_POST_SINCE ? Date.parse(process.env.HUNT_POST_SINCE) : 0; const POST_SINCE = process.env.HUNT_POST_SINCE ? Date.parse(process.env.HUNT_POST_SINCE) : 0;
let sweeping = false; let sweeping = false;
async function postMissedFinds() { async function postMissedFinds() {
if (sweeping || !outbound()) return 0; sweeping = true; let n = 0; if (sweeping || !outbound()) return 0; sweeping = true; let n = 0;
try { for (const p of rewards.unposted(POST_SINCE, 15)) { if (postingNow.has('find:' + p.id)) continue; if (await notify('paid', p)) n++; else break; } } try { for (const p of rewards.unposted(POST_SINCE, 15)) { if (postingNow.has('find:' + p.id)) continue; if (await notify('paid', p)) n++; else break; } }
catch (e) { console.error('find sweep', e.message); } finally { sweeping = false; } catch (e) { console.error('find sweep', e.message); } finally { sweeping = false; }
if (n) console.log('posted', n, 'missed find(s) to Telegram'); if (n) console.log('posted', n, 'missed find(s) to Telegram');
await postMissedBadges().catch(e => console.error('badge sweep', e.message)); await postMissedBadges().catch(e => console.error('badge sweep', e.message));
return n; return n;
} }
// badges of every hunter active since the cutoff that were never posted (gated, Telegram down, restart) // badges of every hunter active since the cutoff that were never posted (gated, Telegram down, restart)
async function postMissedBadges() { async function postMissedBadges() {
if (!outbound()) return 0; if (!outbound()) return 0;
const since = POST_SINCE; const recs = store.read('payouts', []).filter(x => (x.at || 0) >= since && x.status !== 'failed'); const since = POST_SINCE; const recs = store.read('payouts', []).filter(x => (x.at || 0) >= since && x.status !== 'failed');
const seen = new Map(); for (const r of recs) seen.set(r.memberId, { memberId: r.memberId, username: r.username || null }); const seen = new Map(); for (const r of recs) seen.set(r.memberId, { memberId: r.memberId, username: r.username || null });
const posted = store.read('badges-posted', {}); let n = 0; const posted = store.read('badges-posted', {}); let n = 0;
for (const me of seen.values()) { for (const me of seen.values()) {
const have = new Set(posted[String(me.memberId)] || []); const have = new Set(posted[String(me.memberId)] || []);
for (const b of social.badgesFor(me.memberId)) { if (have.has(b.id) || postingNow.has('badge:' + me.memberId + ':' + b.id)) continue; if (n >= 10) return n; if (await notify('badge', { me, id: b.id })) n++; else return n; } for (const b of social.badgesFor(me.memberId)) { if (have.has(b.id) || postingNow.has('badge:' + me.memberId + ':' + b.id)) continue; if (n >= 10) return n; if (await notify('badge', { me, id: b.id })) n++; else return n; }
} }
if (n) console.log('posted', n, 'missed badge(s) to Telegram'); if (n) console.log('posted', n, 'missed badge(s) to Telegram');
return n; return n;
} }
setInterval(() => postMissedFinds().catch(() => {}), 2 * 60000); setTimeout(() => postMissedFinds().catch(() => {}), 20000); setInterval(() => postMissedFinds().catch(() => {}), 2 * 60000); setTimeout(() => postMissedFinds().catch(() => {}), 20000);
// weekly prizes: the week that just ended is awarded on the first tick after Sunday, Central // weekly prizes: the week that just ended is awarded on the first tick after Sunday, Central
setInterval(() => { Promise.resolve().then(() => social.awardDue(notify)).catch(e => console.error('prizes', e.message)); }, 2 * 60000); setInterval(() => { Promise.resolve().then(() => social.awardDue(notify)).catch(e => console.error('prizes', e.message)); }, 2 * 60000);
server.listen(PORT, () => console.log(`PolHunter on :${PORT} — outbound: ${outbound() ? 'ON' : 'OFF'} — sign-ups: ${signupsOpen() ? 'open' : 'CLOSED'} — curtain: ${CURTAIN ? 'up' : 'down'} — sso: ${sso.enabled() ? 'on' : 'off'} — faucet: ${faucetOn ? faucet.address() + ' chain ' + (process.env.HUNT_CHAIN_ID || '?') : 'off'}`)); server.listen(PORT, () => console.log(`PolHunter on :${PORT} — outbound: ${outbound() ? 'ON' : 'OFF'} — sign-ups: ${signupsOpen() ? 'open' : 'CLOSED'} — curtain: ${CURTAIN ? 'up' : 'down'} — sso: ${sso.enabled() ? 'on' : 'off'} — faucet: ${faucetOn ? faucet.address() + ' chain ' + (process.env.HUNT_CHAIN_ID || '?') : 'off'}`));
+2
View File
@@ -47,6 +47,8 @@ const sleep = ms => new Promise(r => setTimeout(r, ms));
const st = await call('/api/my/start', { method: 'POST', body: JSON.stringify({ missionId: 'test-1' }) }); const st = await call('/api/my/start', { method: 'POST', body: JSON.stringify({ missionId: 'test-1' }) });
eq([st.status, /#ph=[a-f0-9]{32}$/.test(st.body.url)], [200, true], 'start issues a token on the mission link'); eq([st.status, /#ph=[a-f0-9]{32}$/.test(st.body.url)], [200, true], 'start issues a token on the mission link');
const t = st.body.token; const t = st.body.token;
{ const b2 = await call('/api/my/board'); eq([b2.body.open && b2.body.open.token, b2.body.open && b2.body.open.missionId], [t, 'test-1'], 'board hands back the started mission, so the code box survives a reload');
const st2 = await call('/api/my/start', { method: 'POST', body: JSON.stringify({ missionId: 'test-1' }) }); eq([st2.status, st2.body.token === t, st2.body.started <= Date.now()], [200, true, true], 'a second Start reuses the live token (the code on screen keeps matching)'); }
// the embed's locks // the embed's locks
const wrongOrigin = await fetch(B + '/api/embed/code?t=' + t, { headers: { Origin: 'https://evil.example' } }); const wrongOrigin = await fetch(B + '/api/embed/code?t=' + t, { headers: { Origin: 'https://evil.example' } });