Files
polhunter/lib/detective.js
T
martbost 469cbf69a5 Mystery Hunt Box + Ad Detective, badge tiers
Finish the day's Code Hunts to unlock one box a day. It opens to an Ad
Detective case on one site with a fixed 0.15 POL reward shown up front:
visit (the embed records the visit after the dwell, no code), then answer
one question, one attempt. Paid inside the house cap, never counted as a
find. 34-question bank seeded from lib/detective-bank.json; a hunter never
repeats a question until they have seen every one for that site. Admin
panel with per-question stats and retire/restore.

New badges (all ledger-derived): Detective, Sleuth, Investigator, Master
Detective; Scout, Guide, Trail Boss; Week Sweep; 7-Day Streak. Badges
already earned on deploy are marked announced without posting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 16:10:17 -05:00

177 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Mystery Hunt Box + Ad Detective (Phase 1, Marty 2026-09-26).
//
// The box: finish the day's Code Hunts (missionsPerDay, normally 3) and one Mystery Hunt Box
// unlocks, once per member per Central day. Opening it reveals a mission, never an amount: an Ad
// Detective case on one of the network's sites, with its FIXED reward shown before the hunter
// starts (settings.detectivePol, default 0.15 POL). The only chance element is which site you get;
// every case pays the same disclosed rate, so this is a task, not a prize draw.
//
// The case: Begin issues a normal mission token (kind 'detective'). The hunter visits the site; the
// embed's origin-locked call after the dwell records the visit on the box (no code is shown). Only
// then does the board show the question. One answer. Correct pays the fixed reward through the
// same faucet, inside the same daily house cap (over the cap it queues, like a find). Wrong pays
// nothing today. Every answer is logged (answers.json) for per-question stats.
//
// Detective payouts are NOT finds: they never count toward the daily limit, the leaderboard, the
// weekly prizes, referral matches or the find badges. They have their own badge family.
//
// Variety (Marty's ask, 2026-09-26): a hunter is never asked the same question twice until they
// have answered every active question for that site, and the box leans toward the site with the
// most questions they have not seen yet. The options are shuffled per hunter per case. The bank
// grows from the admin (POST /api/admin/detective/question); per-question stats show which are
// worn and should be retired or replaced.
'use strict';
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const store = require('./store');
const missions = require('./missions');
const rewards = require('./rewards');
const SECRET = String(process.env.HUNT_CODE_SECRET || process.env.HUNT_SSO_SECRET || 'dev').trim();
const h = s => crypto.createHmac('sha256', SECRET).update('det:' + s).digest().readUInt32BE(0);
const ctDay = missions.ctDay;
const settings = () => { const s = rewards.settings(); return { on: s.detectiveOn == null ? true : !!Number(s.detectiveOn), pol: Number(s.detectivePol) > 0 ? Number(s.detectivePol) : 0.15, base: Math.max(1, Number(s.missionsPerDay) || 3) }; };
// ---- the bank -------------------------------------------------------------------------------
// seed from the repo, merged by id: questions already on the volume (edited or retired) win
function init() {
let seed = [];
try { seed = JSON.parse(fs.readFileSync(path.join(__dirname, 'detective-bank.json'), 'utf8')).questions || []; } catch (e) { console.error('detective seed', e.message); }
store.update('detective-bank', [], all => { const have = new Set(all.map(q => q.id)); for (const q of seed) if (!have.has(q.id)) all.push(q); return all; });
missions.onVisit = visited; // the embed tells us when a detective token has done its dwell on the right origin
}
function bank() { return store.read('detective-bank', []); }
function saveQuestion(q) {
const opts = (Array.isArray(q.options) ? q.options : []).map(o => String(o || '').trim().slice(0, 140)).filter(Boolean);
if (!q.missionId || !missions.get(String(q.missionId))) return { error: 'missionId must be an existing mission' };
if (!String(q.q || '').trim()) return { error: 'question text required' };
if (opts.length < 3 || opts.length > 5 || new Set(opts.map(o => o.toLowerCase())).size !== opts.length) return { error: 'three to five distinct options, the correct one first' };
let saved;
store.update('detective-bank', [], all => {
const id = q.id ? String(q.id).replace(/[^a-z0-9-]/gi, '').slice(0, 60) : String(q.missionId) + '-' + Date.now().toString(36);
const i = all.findIndex(x => x.id === id);
saved = Object.assign(i >= 0 ? all[i] : { id, added: ctDay() }, { missionId: String(q.missionId), q: String(q.q).trim().slice(0, 240), options: opts, fact: String(q.fact || '').slice(0, 300), active: q.active !== false });
if (i < 0) all.push(saved);
return all;
});
return { ok: true, question: saved };
}
function setActive(id, active) { let hit = false; store.update('detective-bank', [], all => { const q = all.find(x => x.id === id); if (q) { q.active = !!active; hit = true; } return all; }); return hit; }
const answers = () => store.read('answers', []);
function seenBy(memberId) { const m = new Map(); for (const a of answers()) if (a.memberId === Number(memberId)) m.set(a.qid, (m.get(a.qid) || 0) + 1); return m; }
// sites a case can be on: active house missions (not advertiser-paid) with at least one active question
function caseSites() {
const live = new Set(missions.list().filter(m => m.active && !m.paid).map(m => m.id));
const by = new Map(); for (const q of bank()) if (q.active !== false && live.has(q.missionId)) { if (!by.has(q.missionId)) by.set(q.missionId, []); by.get(q.missionId).push(q); }
return by;
}
// the site with the most questions this hunter has not answered; ties broken per hunter per day
function pickCase(memberId, day) {
const by = caseSites(); if (!by.size) return null;
const seen = seenBy(memberId);
const rows = [...by.entries()].map(([mid, qs]) => ({ mid, qs, fresh: qs.filter(q => !seen.get(q.id)).length, k: h(day + ':' + memberId + ':' + mid) }));
rows.sort((a, b) => b.fresh - a.fresh || a.k - b.k);
const pick = rows[0];
// within the site: the least-asked question for this hunter, ties broken the same way
const qs = pick.qs.map(q => ({ q, n: seen.get(q.id) || 0, k: h(day + ':' + memberId + ':' + q.id) })).sort((a, b) => a.n - b.n || a.k - b.k);
return { missionId: pick.mid, qid: qs[0].q.id };
}
// the options in this case's own order; the server alone knows which one is right (index 0 in the bank)
function order(box, q) { return q.options.map((o, i) => ({ i, k: h(box.id + ':' + q.id + ':' + i) })).sort((a, b) => a.k - b.k).map(x => x.i); }
// ---- the box ----------------------------------------------------------------------------------
const boxId = (memberId, day) => Number(memberId) + ':' + day;
function getBox(memberId, day) { return store.read('boxes', {})[boxId(memberId, day || ctDay())] || null; }
function putBox(b) { store.update('boxes', {}, all => { all[b.id] = b; return all; }); return b; }
function patchBox(id, patch) { let out = null; store.update('boxes', {}, all => { if (all[id]) { Object.assign(all[id], patch); out = all[id]; } return all; }); return out; }
function earned(me) { const s = settings(); return s.on && rewards.findsToday(me.memberId, ctDay()) >= s.base; }
// what the board shows
function view(me) {
const s = settings(); if (!s.on) return { on: false };
const day = ctDay(); const b = getBox(me.memberId, day);
const done = rewards.findsToday(me.memberId, day);
if (!b) return { on: true, status: done >= s.base ? 'ready' : 'locked', need: s.base, done: Math.min(done, s.base), pol: s.pol };
const m = missions.get(b.missionId) || {}; const q = bank().find(x => x.id === b.qid);
const out = { on: true, status: b.status, pol: b.pol, site: m.site || b.missionId, name: m.name || '', dwell: m.dwell || 30, url: b.url || null, expires: b.exp || null };
if (b.status === 'visited' && q) {
if (!b.shownAt) patchBox(b.id, { shownAt: Date.now() });
out.question = q.q; out.options = order(b, q).map(i => q.options[i]);
}
if (b.status === 'won' || b.status === 'missed') { out.question = q ? q.q : null; out.correct = b.status === 'won'; out.answer = q ? q.options[0] : null; }
return out;
}
function open(me) {
if (!earned(me)) return { error: 'Finish today’s Code Hunts first. The box unlocks when your last one is found.' };
const day = ctDay(); const cur = getBox(me.memberId, day); if (cur) return { ok: true, box: cur };
const c = pickCase(me.memberId, day); if (!c) return { error: 'No cases are open right now. Check back tomorrow.' };
let made = null;
// idempotent per member per day: a double tap or two tabs can never mint a second box
store.update('boxes', {}, all => { const id = boxId(me.memberId, day); if (!all[id]) all[id] = { id, memberId: Number(me.memberId), day, missionId: c.missionId, qid: c.qid, pol: settings().pol, status: 'open', openedAt: Date.now() }; made = all[id]; return all; });
return { ok: true, box: made };
}
function start(me) {
const b = getBox(me.memberId, ctDay()); if (!b) return { error: 'Open your Mystery Hunt Box first.' };
if (b.status === 'visited') return { error: 'You have been to the site. Your question is waiting on your board.' };
if (b.status === 'won' || b.status === 'missed') return { error: 'Today’s case is closed. A new box unlocks tomorrow.' };
const m = missions.get(b.missionId); if (!m || !m.active) return { error: 'That site is not open right now. Try again later.' };
// a live token is reused, so a second tap does not restart the dwell
const live = b.token && missions.token(b.token);
const t = live || missions.issue(me.memberId, m.id, { kind: 'detective', boxId: b.id });
const url = m.url.includes('{token}') ? m.url.replace('{token}', t.t) : m.url + '#ph=' + t.t;
patchBox(b.id, { status: 'started', token: t.t, url, exp: t.exp, startedAt: b.startedAt || Date.now() });
return { ok: true, url, dwell: m.dwell || 30, expires: t.exp };
}
// called by missions.codeForEmbed once a detective token has passed the origin and dwell locks
function visited(rec) {
if (!rec || rec.kind !== 'detective' || !rec.boxId) return;
store.update('boxes', {}, all => { const b = all[rec.boxId]; if (b && b.status === 'started' && b.token === rec.t) { b.status = 'visited'; b.visitedAt = Date.now(); } return all; });
}
function answer(me, choice) {
const b = getBox(me.memberId, ctDay()); if (!b) return { error: 'No case open today.' };
if (b.status === 'won' || b.status === 'missed') return { error: 'You already answered today’s case.' };
if (b.status !== 'visited') return { error: 'Visit the site first. The question unlocks once your visit is recorded.' };
const q = bank().find(x => x.id === b.qid); if (!q) return { error: 'That question was withdrawn. Tell support and we will make it right.' };
const ord = order(b, q); const n = Number(choice);
if (!Number.isInteger(n) || n < 0 || n >= ord.length) return { error: 'Pick one of the answers.' };
// claim the answer before anything else, so two taps or two tabs can only ever answer once
let claimed = false;
store.update('boxes', {}, all => { const x = all[b.id]; if (x && x.status === 'visited') { x.status = 'answering'; claimed = true; } return all; });
if (!claimed) return { error: 'You already answered today’s case.' };
const correct = ord[n] === 0; const at = Date.now();
store.update('answers', [], all => { all.push({ memberId: Number(me.memberId), boxId: b.id, missionId: b.missionId, qid: q.id, correct, picked: q.options[ord[n]], at, ms: b.shownAt ? at - b.shownAt : null }); return all; });
let g = null;
try {
if (correct) {
const m = missions.get(b.missionId) || { id: b.missionId, site: b.missionId };
g = rewards.grantFixed(me, { missionId: 'detective:' + m.id, site: m.site, pol: b.pol, detective: { boxId: b.id, qid: q.id } });
}
} finally {
// the answer is final either way; a grant that failed shows in the admin as a won box with no payout
patchBox(b.id, { status: correct ? 'won' : 'missed', answeredAt: at, payoutId: g && g.rec ? g.rec.id : null });
}
return { ok: true, correct, pol: correct ? b.pol : 0, queued: !!(g && g.queued), rec: g && g.rec, answer: q.options[0] };
}
// ---- stats for the admin -------------------------------------------------------------------------
function stats() {
const all = answers(); const by = new Map();
for (const a of all) { const r = by.get(a.qid) || { asked: 0, correct: 0 }; r.asked++; if (a.correct) r.correct++; by.set(a.qid, r); }
const boxes = Object.values(store.read('boxes', {})); const today = ctDay();
return {
settings: settings(),
questions: bank().map(q => Object.assign({}, q, by.get(q.id) || { asked: 0, correct: 0 })),
today: { boxes: boxes.filter(b => b.day === today).length, won: boxes.filter(b => b.day === today && b.status === 'won').length, missed: boxes.filter(b => b.day === today && b.status === 'missed').length },
recent: all.slice(-50).reverse(),
};
}
module.exports = { init, bank, saveQuestion, setActive, view, open, start, answer, visited, stats, pickCase, earned };