Files

198 lines
15 KiB
JavaScript
Raw Permalink 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;
// the day's current box: the second one (the Game Pass perk, id '<member>:<day>:2') once it exists, else the first
function getBox(memberId, day) { const all = store.read('boxes', {}), id = boxId(memberId, day || ctDay()); return all[id + ':2'] || all[id] || null; }
const closed = b => !!b && (b.status === 'won' || b.status === 'missed');
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; }
// The box is a Game Pass perk since 2026-11-02 (Marty: the Pass is the purchase that funds the game): a free account hunts
// once a day and never reaches the box; pass = false answers 'pass' on the board and refuses to open.
function earned(me, pass) { const s = settings(); return s.on && pass !== false && rewards.findsToday(me.memberId, ctDay()) >= s.base; }
// what the board shows
function view(me, pass) {
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 && pass === false) return { on: true, status: 'pass', need: s.base, done: Math.min(done, s.base), pol: s.pol };
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;
}
// pass = the Game Pass perk (GAME-PASS.md 4): a second case a day once the first is closed; the first case stays the rule for everyone else
// pass = the second-case perk; allowed = may a box open at all (the full tier: Game Pass holders, or everyone while GAMEPASS is off)
function open(me, pass, allowed) {
const day = ctDay(); const cur = getBox(me.memberId, day);
const second = !!(pass && cur && closed(cur) && !/:2$/.test(cur.id));
if (cur && !second) return { ok: true, box: cur }; // a box already open today stays reachable (a pass that lapsed mid-day)
if (allowed === false) return { error: 'The Mystery Hunt Box opens for Game Pass holders.' };
if (!earned(me, true)) return { error: 'Finish today’s Code Hunts first. The box unlocks when your last one is found.' };
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) + (second ? ':2' : ''); 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(), second: second || undefined }; 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; });
}
// gate (the Game Pass, GAME-PASS.md 3a): { ask(pol, ref) -> IAP's answer, wait(rowId, pol, ref) } set by server.js when GAMEPASS=on;
// the case is scored first (the answer is final either way), then InstantAdPay decides what the account-wide cap allows
async function answer(me, choice, gate) {
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, note = null;
try {
if (correct) {
const m = missions.get(b.missionId) || { id: b.missionId, site: b.missionId };
const t = { missionId: 'detective:' + m.id, site: m.site, pol: b.pol, detective: { boxId: b.id, qid: q.id } };
if (gate) { // the Game Pass: a case is a repeatable ('daily') reward; what the account-wide cap does not allow is dropped, not deferred
const ref = 'detective:' + b.id, r = await gate.ask(b.pol, ref);
if (r.retry) { t.status = 'gp-wait'; t.gp = { ref, kind: 'daily', nominal: b.pol, pending: true }; t.nominal = b.pol; }
else { t.pol = r.allowed; t.nominal = b.pol; t.gp = { ref, kind: 'daily', nominal: b.pol, pass: !!r.pass, capHit: r.capHit || null }; }
note = r.note || null;
g = rewards.grantFixed(me, t);
if (r.retry && g && g.rec) gate.wait(g.rec.id, b.pol, ref);
} else g = rewards.grantFixed(me, t);
}
} 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 });
}
const paid = correct && g && g.rec && g.rec.status !== 'gp-wait' ? g.rec.pol : 0; // a gp-wait row holds the nominal amount until IAP answers: nothing is paid yet
return { ok: true, correct, pol: paid, nominal: b.pol, note, queued: !!(g && g.queued), waiting: !!(g && g.waiting), capped: !!(g && g.capped), 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, getBox };