Files
5xyourteam/store.js
T
martbost b2d5eb4625 Network hub hook (Marty 2026-11-16): sign out everywhere, hub blocks and erases end sessions here; "Sign out everywhere" button
hubevents.js (new, byte-identical in VBB, DLB, ViralAdBlitz, DownlineHydra, 5xYourTeam): POST /api/hub/events, signed by the hub
with HUB_SECRET (same hook InstantAdPay and LinkSpin take). member.signedout and member.blocked: the person is looked up by hub id
(/v1/resolve, signed as fivex) and their sessions here end (by the main wallet or any contract wallet). member.erased: matched by the wallet SHA-256s
(and email SHA-256) the hub now sends with the event. Only sessions made before the event end (a replay never signs anyone out
twice); a failed hub lookup answers 503 so the hub resends. Off with HUB_HOOK=0. Admin status: hubEvents (counts only).
/team: "Sign out everywhere" next to Sign out (POST /api/auth/logout-everywhere -> networksso.signOutEverywhere, then every
session of this member here ends).
Smoke: section 14b (same cases as the other wallet sites): 172 pass, 2 fail with UI; the same 2 (pool size, this week's pot: test-clock dated) fail on a clean HEAD. team.js?v=4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 05:05:40 -06:00

125 lines
8.4 KiB
JavaScript

// 5xYourTeam data. One document (fivex.json) holds members (coaches and anyone signed in), sessions, position purchases (the
// chain's Purchase events), the watcher position, the weekly drafts, instant-pick credits, Best Coach pot payouts and daily counters.
// Three growing collections are row tables on MySQL (docstore splits): picks (each pick = one adoption), messages (coach <-> pick,
// through the site only) and builder referral IDs. Without DOCSTORE_URL (local prototype + tests only) everything stays in the one
// file, written atomically. Marty's rule (2026-11-13): MySQL is the standard; never launch on files.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const cfgMod = require('./config');
const docstore = require('./docstore');
const DOC = 'fivex.json';
const SPLITS = [
{ doc: DOC, field: 'picks', table: 'fx_picks', key: 'id', ts: 'at' },
{ doc: DOC, field: 'msgs', table: 'fx_msgs', key: 'id', ts: 'at' },
{ doc: DOC, field: 'refids', table: 'fx_refids', key: 'id', ts: 'at' }
];
const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s]));
let S = null, saveT = null, rowMode = false;
const FILE = () => path.join(cfgMod.get().dataDir, DOC);
function load() {
try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; }
S = Object.assign({ v: 1, seq: { pick: 0, msg: 0, refid: 0 }, daily: {}, members: {}, sessions: {}, purchases: {}, shop: {}, drafts: {}, credits: {},
payouts: {}, programs: null, picks: [], msgs: [], refids: [] }, S || {});
rowMode = docstore.isOn();
if (rowMode) for (const sp of SPLITS) S[sp.field] = (docstore.rows(sp.table) || []).slice();
const now = Date.now();
for (const [k, s] of Object.entries(S.sessions)) if (s.expires < now) delete S.sessions[k];
}
function save(now) {
if (saveT && !now) return;
const run = () => {
saveT = null;
try {
const out = rowMode ? Object.assign({}, S, Object.fromEntries(SPLITS.map(sp => [sp.field, []]))) : S;
const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 }); fs.renameSync(tmp, FILE());
} catch (e) { console.error('store save failed', e.message); }
};
if (now) { clearTimeout(saveT); run(); } else saveT = setTimeout(run, 500);
}
function flush() { save(true); }
const state = () => S;
function putRow(field, item) { if (rowMode) { const sp = TABLE[field]; docstore.rowPut(sp.table, item[sp.key], item[sp.ts], item); } save(); }
function nextId(kind) { S.seq[kind] = (S.seq[kind] || 0) + 1; return S.seq[kind]; }
// ---- Central time (Marty: everything on US Central) ----
const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short', hour: '2-digit', minute: '2-digit', hour12: false });
const parts = ts => Object.fromEntries(fmt.formatToParts(new Date(ts)).map(x => [x.type, x.value]));
function ctDay(ts) { const p = parts(ts == null ? Date.now() : ts); return p.year + '-' + p.month + '-' + p.day; }
function ctWeek(ts) { // the Central-time date of that week's Monday
const p = parts(ts == null ? Date.now() : ts);
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0;
return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)).toISOString().slice(0, 10);
}
// a Central wall-clock time (YYYY-MM-DD, hour) -> epoch ms (handles CST / CDT)
function ctToMs(day, hour) {
const [y, m, d] = day.split('-').map(Number);
for (const off of [6, 5]) { const t = Date.UTC(y, m - 1, d, hour + off); const p = parts(t); if (Number(p.hour) % 24 === hour && p.day === String(d).padStart(2, '0')) return t; }
return Date.UTC(y, m - 1, d, hour + 6);
}
const addDays = (day, n) => new Date(Date.parse(day + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10);
function bump(k, n) { const day = ctDay(); const d = S.daily[day] || (S.daily[day] = {}); d[k] = (d[k] || 0) + (n || 1); save(); }
function today() { return S.daily[ctDay()] || {}; }
// ---- members (keyed by wallet) ----
function member(addr) { return S.members[String(addr || '').toLowerCase()] || null; }
function upsertMember(addr, patch) {
const a = String(addr).toLowerCase();
const m = S.members[a] || (S.members[a] = { address: a, username: null, hubId: null, joinedAt: Date.now(), via: null, netOk: false, queue: [] });
Object.assign(m, patch || {}); m.lastSeen = Date.now(); save(); return m;
}
function memberByName(name) { const n = String(name || '').toLowerCase(); if (!n) return null; for (const m of Object.values(S.members)) if (m.username && m.username.toLowerCase() === n) return m; return null; }
function memberByHub(id) { if (!id) return null; for (const m of Object.values(S.members)) if (m.hubId === id) return m; return null; }
function members() { return Object.values(S.members); }
// ---- sessions ----
const SESSION_TTL = 7 * 24 * 3600000;
function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: address.toLowerCase(), expires: Date.now() + SESSION_TTL }; save(); return token; }
function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; }
function dropSession(token) { delete S.sessions[token]; save(); }
// network hub events (hubevents.js, 2026-11-16): end every session `match` names that was made before `before` -> how many
function endSessions(match, before) { let n = 0; for (const [k, x] of Object.entries(S.sessions)) if (x.expires - SESSION_TTL <= before && match(x)) { delete S.sessions[k]; n++; } if (n) save(); return n; }
// ---- positions (from the chain) ----
const purchases = () => Object.entries(S.purchases || {}).map(([key, x]) => Object.assign({ key }, x));
function positionsOf(addr) { const a = String(addr || '').toLowerCase(); return purchases().filter(x => x.buyer === a).reduce((t, x) => t + (Number(x.qty) || 1), 0); }
function firstPositionAt(addr) { const a = String(addr || '').toLowerCase(); const l = purchases().filter(x => x.buyer === a).map(x => (x.blockAt ? x.blockAt * 1000 : x.at) || 0); return l.length ? Math.min(...l) : 0; }
function coaches() { const seen = new Set(purchases().map(x => x.buyer)); return [...seen].map(a => member(a) || upsertMember(a, { via: 'wallet' })); }
// ---- instant-pick credits (5 per position, used from the current pool) ----
const credits = addr => Number(S.credits[String(addr).toLowerCase()] || 0);
function addCredits(addr, n) { const a = String(addr).toLowerCase(); S.credits[a] = Math.max(0, credits(a) + n); save(); return S.credits[a]; }
// ---- picks ----
const picks = () => S.picks;
function pick(id) { return S.picks.find(p => p.id === Number(id)) || null; }
function addPick(p) { p.id = nextId('pick'); p.at = p.at || Date.now(); S.picks.push(p); putRow('picks', p); return p; }
function savePick(p) { p.updatedAt = Date.now(); putRow('picks', p); }
const picksOf = addr => S.picks.filter(p => p.coach === String(addr).toLowerCase());
const picksOfPerson = id => S.picks.filter(p => p.person === id);
// ---- messages (coach <-> pick, through the site) ----
function addMsg(m) { m.id = nextId('msg'); m.at = m.at || Date.now(); S.msgs.push(m); putRow('msgs', m); return m; }
const msgsOfPick = id => S.msgs.filter(m => m.pick === Number(id));
function saveMsg(m) { putRow('msgs', m); }
// ---- builder referral IDs (the CryptoTeamBuild downline builder, the DownlineHydra wild heads) ----
function setRefid(addr, program, refId) {
const a = String(addr).toLowerCase(); let r = S.refids.find(x => x.member === a && x.program === program);
if (!r) { r = { id: nextId('refid'), member: a, program, refId, at: Date.now() }; S.refids.push(r); } else { r.refId = refId; r.at = Date.now(); }
putRow('refids', r); return r;
}
const refidOf = (addr, program) => { const r = S.refids.find(x => x.member === String(addr || '').toLowerCase() && x.program === program); return r && r.refId ? r.refId : ''; };
// ---- drafts ----
const draft = week => S.drafts[week] || null;
function putDraft(d) { S.drafts[d.week] = d; save(); return d; }
module.exports = { SPLITS, load, flush, save, state, ctDay, ctWeek, ctToMs, addDays, bump, today, member, upsertMember, memberByName, memberByHub, members,
mintSession, session, dropSession, endSessions, SESSION_TTL, purchases, positionsOf, firstPositionAt, coaches, credits, addCredits,
picks, pick, addPick, savePick, picksOf, picksOfPerson, addMsg, msgsOfPick, saveMsg, setRefid, refidOf, draft, putDraft };