0e031f477e
networksso.js (the same file on every network site): with HUB_SSO=on /sso/start asks the network hub, /sso/in takes the hub's h1. token (this site's HUB_SECRET, iss hub, aud iap, 60 s, single use, state cookie), and when the hub has nobody the old pairwise provider is tried once (the fallback until every site is switched). networksso.page() on every GET: a signed-in member's real page load tells the hub once (nsso.hp, hub /sso/set and straight back) and pings the hub's /v1/activity once a day (fire and forget), only while the hub answers /health. Sessions: SESSION_TTL_HOURS (168 = 7 days in production), renewed on use at most hourly; the cookie lives 30 days and the server's sliding expiry decides. auth.endSessions(email, wallet). Sign out everywhere: POST /api/auth/logout-everywhere (hub /v1/sso/signout, every session of the member here ends) and a "Sign out everywhere" link beside Log out; my.js?v=20261115hub. hubsync: member.blocked and member.signedout end every session of that member here. Login ad: /api/ads/slot?type=login refuses signed-out callers (no ad drawn, no view counted; bots and probes cannot run up an advertiser's numbers). The games' kit keeps its own route. Chatbot: a sign-in lasts 7 days and renews; the login ad shows every few hours on its own clock; the silent check is every 2 minutes. Tests: qa/networksso-hub.e2e.mjs (new, run.sh member; real hub + IAP + LinkSpin + a wallet partner on four cookie hosts): page load pushes to the hub once, LinkSpin signs in through the hub, partner gets the wallet from the hub, sign out everywhere, blocked, replay, forged key, no email code. Partner e2e: signed-out slot on both sites, LinkSpin clock. qa member: ALL PASSED (2 known admin warnings). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
383 lines
27 KiB
JavaScript
383 lines
27 KiB
JavaScript
// Network hub sync (2026-11-12, Marty 2026-11-06: one membership from any door; the hub is the single identity).
|
|
// Everything here sleeps unless HUB_ENABLED is on: server.js does not even init this module without it, so no file is
|
|
// written, no route answers and no hook is wired. The InstantAdPay <-> LinkSpin direct sync (lssync.js / lsinbound.js)
|
|
// keeps running exactly as before either way.
|
|
//
|
|
// Inbound (POST /api/hub/events, signed by the hub with HUB_SECRET: X-Hub-Ts + X-Hub-Sig = hex HMAC-SHA256(ts + newline +
|
|
// raw body), 5-minute window). The hub only moves its cursor after a 2xx and may send an event twice:
|
|
// member.joined someone joined at another door: /v1/resolve the person (and, climbing, any sponsor not here yet) and
|
|
// hand the rows to lsinbound.receive, the same waiting-account path LinkSpin-first members take, with
|
|
// joinedVia 'hub' and joinedRef 'hub:<door>'. First-platform rule as there: an account that already
|
|
// exists here keeps its sponsor and only gets empty fields filled. Joins from this site are skipped.
|
|
// wallet.connected filled only on a waiting account that still has no wallet (lsinbound fill rules). A claimed account
|
|
// links its own wallet here; the hub's wallet is not proof of ownership on InstantAdPay.
|
|
// sponsor.changed ignored on purpose (2026-11-14): lsinbound's follow rule needs sponsorSetAt / By / PrevEmail, which the
|
|
// hub view does not expose, and someone the InstantAdPay contract holds never moves anyway.
|
|
// Rule 2 (2026-11-14): the sponsor written for an arrival is person.locks.iap's sponsor when that lock exists, never the
|
|
// plain network sponsor. QUIET: nothing on this path sends mail, a notice or a post, and lssync.js never
|
|
// pushes a hub waiting account to LinkSpin (qa/hubsync.test.cjs, mail audit).
|
|
// member.erased (2026-11-15) the hub erased someone: erase.js finds them by the SHA-256 of the email and takes them out
|
|
// here too; refused (wallet, member number, team) = a log note, never retried.
|
|
// anything else ignored.
|
|
// Each seq is applied once (done map). A failing event answers 503 so the hub retries it; after 5 tries it is set aside
|
|
// in the log so one bad row cannot hold every later event back.
|
|
//
|
|
// Outbound (/v1/join, /v1/wallet, signed as HUB_SITE): new accounts made here since the flag first went on and every main
|
|
// wallet linked here go into a persisted outbox (DATA_DIR/hubsync.json) and are sent in order, never in the way of a
|
|
// sign-up. Retried with backoff on 5xx / network / 404-before-join; a 400/409 refusal is final and logged.
|
|
// Gaps closed 2026-11-13 (Marty: "let's get the gaps report built"), all still one way:
|
|
// - any later change to a member's username or sponsor goes to /v1/join again (names them; a sponsor only lands where the
|
|
// hub has none), old members included, not only accounts made since the flag went on;
|
|
// - a DELIBERATE sponsor change (sponsorfollow: adopt, rescue, release, expire->expiry, admin) goes to /v1/sponsor-change;
|
|
// - every MemberActivated on the InstantAdPay contract goes to /v1/contract-bind (contract 'iap', the sponsor by wallet),
|
|
// by email when the wallet belongs to an account here, else by wallet alone.
|
|
// - every paid Purchase goes to /v1/contract-spend (2026-11-14, rule 2: the contract with money spent decides the network
|
|
// sponsor when two contracts hold different ones).
|
|
// Where the hub and InstantAdPay name different sponsors, nothing is forced on either side: the case goes to `disagree`
|
|
// (Admin > /api/admin/hub) for Marty, since an InstantAdPay member bound on our contract cannot move anyway.
|
|
'use strict';
|
|
const crypto = require('crypto');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
let R = null, st = null, chain_ = Promise.resolve(), timer = null, sending = false, interval = null;
|
|
const MAX_UP = 25, EVENT_TRIES = 5, OUT_TRIES = 20, KEEP_DONE = 5000;
|
|
const SHELL_ORIGINS = new Set(['linkspin', 'btc4hits', 'hub']);
|
|
const DELIBERATE = new Set(['adopt', 'rescue', 'release', 'expire', 'expiry', 'admin']); // sponsorfollow.js kinds the hub accepts // came here from another site: that site tells the hub itself
|
|
const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim());
|
|
const URL_ = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
|
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
|
|
const SITE = () => String(process.env.HUB_SITE || 'iap').trim().toLowerCase();
|
|
const on = () => enabled() && !!URL_() && SECRET().length >= 32;
|
|
const norm = v => String(v || '').trim().toLowerCase();
|
|
const FILE = () => path.join(R.dataDir, 'hubsync.json');
|
|
function load() {
|
|
if (st) return st;
|
|
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
|
if (!st || typeof st !== 'object') st = {};
|
|
st.since = Number(st.since) || Date.now(); // only accounts made after the flag first went on are reported as joins
|
|
st.done = st.done || {}; st.tries = st.tries || {}; st.outbox = st.outbox || []; st.reported = st.reported || {};
|
|
st.disagree = st.disagree || {}; st.log = st.log || [];
|
|
st.stats = Object.assign({ batches: 0, events: 0, applied: 0, skipped: 0, ignored: 0, gaveUp: 0, sent: 0, refused: 0, sendErrors: 0 }, st.stats || {});
|
|
return st;
|
|
}
|
|
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('hubsync save', e.message); } }
|
|
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
|
|
// deps: { dataDir, accounts, lsinbound }
|
|
function init(deps) { R = deps; load(); save(); }
|
|
|
|
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
|
|
function verify(headers, raw) {
|
|
if (SECRET().length < 32) return false;
|
|
const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || '');
|
|
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return false;
|
|
const want = sign(ts, raw);
|
|
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
|
|
}
|
|
async function hubPost(p, body, timeout) {
|
|
const raw = JSON.stringify(body); const ts = String(Date.now());
|
|
const r = await fetch(URL_() + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(timeout || 15000) });
|
|
let j = null; try { j = await r.json(); } catch (e) {}
|
|
return { status: r.status, body: j };
|
|
}
|
|
async function resolve(q) {
|
|
const r = await hubPost('/v1/resolve', q);
|
|
if (r.status !== 200) throw new Error('hub resolve ' + r.status);
|
|
return (r.body && r.body.person) || null;
|
|
}
|
|
const doorOf = p => norm(p && p.firstDoor && p.firstDoor.site).replace(/[^a-z0-9_-]/g, '').slice(0, 30) || 'network';
|
|
// Rule 2 (Marty 2026-11-14): the sponsor written here is the one the InstantAdPay CONTRACT holds for them when it holds them
|
|
// (person.locks.iap), never the plain network sponsor, which may come from another contract where they spent money
|
|
const CONTRACT = 'iap';
|
|
const sponsorFor = p => { const l = p && p.locks && p.locks[CONTRACT]; if (l) return (l.sponsor && l.sponsor.email) || null; return (p && p.sponsor && p.sponsor.email) || null; };
|
|
const rowOf = p => ({ email: norm(p.email), username: p.username || null, wallet: p.wallet || null, sponsorEmail: sponsorFor(p), joinedAt: Number(p.firstDoor && p.firstDoor.at) || null, profile: null });
|
|
|
|
// what InstantAdPay and the hub each say the sponsor is; a difference is recorded, never forced
|
|
async function compare(email, hubSponsorEmail, how) {
|
|
const sp = await R.accounts.sponsorOf(email); const here = sp ? norm(sp.email) : null; const there = norm(hubSponsorEmail) || null;
|
|
const s = load();
|
|
if (here === there) { delete s.disagree[email]; return; }
|
|
s.disagree[email] = { at: Date.now(), iap: here, hub: there, how };
|
|
}
|
|
|
|
async function memberJoined(ev) {
|
|
if (norm(ev.data && ev.data.site) === SITE()) return 'own';
|
|
const first = await resolve({ id: ev.personId });
|
|
if (!first || !first.email) return first ? 'no-email' : 'unknown'; // the hub must give this site seeEmails
|
|
if (first.blocked) return 'blocked';
|
|
const email = norm(first.email); const A = R.accounts;
|
|
const existing = await A.byEmail(email);
|
|
const rows = [rowOf(first)]; const doors = { [email]: doorOf(first) }; const seen = new Set([email]);
|
|
if (existing && !A.isUnclaimedShell(existing)) rows[0].wallet = null; // a real account links its own wallet here
|
|
// sponsors not on InstantAdPay yet come along as waiting accounts too (lsinbound builds them from rows in the same batch)
|
|
let p = first;
|
|
for (let i = 0; i < MAX_UP && sponsorFor(p); i++) {
|
|
const se = norm(sponsorFor(p)); if (seen.has(se) || await A.byEmail(se)) break;
|
|
const up = await resolve({ email: se }); if (!up || !up.email || up.blocked) break;
|
|
seen.add(se); rows.push(rowOf(up)); doors[se] = doorOf(up); p = up;
|
|
}
|
|
const sum = await R.lsinbound.receive(rows, { via: 'hub', refOf: e => 'hub:' + (doors[e] || 'network') });
|
|
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
|
|
await compare(email, rows[0].sponsorEmail, 'hub-join');
|
|
note({ type: 'joined', email, door: doors[email], created: sum ? sum.created : 0, existed: !!existing });
|
|
return 'applied';
|
|
}
|
|
async function walletConnected(ev) {
|
|
const p = await resolve({ id: ev.personId });
|
|
if (!p || !p.email || !p.wallet || p.blocked) return 'skip';
|
|
const a = await R.accounts.byEmail(p.email);
|
|
if (!a) return 'not-here'; // member.joined makes the account; a wallet alone does not
|
|
if (!R.accounts.isUnclaimedShell(a) || a.address) return 'kept'; // claimed accounts link their own wallet here
|
|
const sum = await R.lsinbound.receive([rowOf(p)], { via: 'hub', refOf: () => 'hub:' + doorOf(p) });
|
|
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
|
|
return 'applied';
|
|
}
|
|
// member.erased (2026-11-15): the hub erased someone; erase.js takes them out here too, found by the SHA-256 of the email
|
|
// (the event carries nothing else). Refused here (a wallet, a member number, a team) = noted for Marty, never retried.
|
|
async function memberErased(ev) {
|
|
if (!R.erase) return 'ignored';
|
|
const r = await R.erase.byHash(ev.data && ev.data.emailHash, 'hub');
|
|
if (r.result === 'refused') note({ type: 'erase-refused', hash: String(ev.data.emailHash).slice(0, 16), error: String(r.error || '').slice(0, 200) });
|
|
else note({ type: 'erased', hash: String((ev.data && ev.data.emailHash) || '').slice(0, 16), result: r.result });
|
|
return r.result === 'erased' ? 'applied' : 'ignored';
|
|
}
|
|
async function apply(ev) {
|
|
if (ev.type === 'member.joined') return memberJoined(ev);
|
|
if (ev.type === 'wallet.connected') return walletConnected(ev);
|
|
if (ev.type === 'member.erased') return memberErased(ev);
|
|
// network sign-in (2026-11-15): a member the hub blocked, or who chose "Sign out everywhere" on any site, is signed out here too
|
|
if (ev.type === 'member.blocked' || ev.type === 'member.signedout') {
|
|
if (!R.endSessions) return 'ignored';
|
|
const p = await resolve({ id: ev.personId }); if (!p || !p.email) return 'ignored';
|
|
const n = await R.endSessions(p.email, p.wallet || null);
|
|
note({ type: ev.type === 'member.blocked' ? 'blocked-signed-out' : 'signed-out-everywhere', sessions: n });
|
|
return n ? 'applied' : 'ignored';
|
|
}
|
|
// sponsor.changed is IGNORED here on purpose (checked 2026-11-14 for the switch-on): it would need the deliberate-change
|
|
// record (at / by / previous sponsor) to go through sponsorfollow's rule, and a member locked on the InstantAdPay contract
|
|
// must never move anyway (the contract pays whoever it holds). qa/hubsync.test.cjs proves a locked member stays put.
|
|
return 'ignored';
|
|
}
|
|
function prune() {
|
|
const s = load(); const seqs = Object.keys(s.done).map(Number).sort((a, b) => a - b);
|
|
for (const q of seqs.slice(0, Math.max(0, seqs.length - KEEP_DONE))) delete s.done[q];
|
|
}
|
|
async function handle(events) {
|
|
const s = load(); s.stats.batches++; let failed = null;
|
|
for (const ev of Array.isArray(events) ? events : []) {
|
|
const seq = Number(ev && ev.seq); if (!seq) continue;
|
|
if (s.done[seq]) { s.stats.skipped++; continue; } // delivered twice: already applied
|
|
s.stats.events++;
|
|
try {
|
|
const r = await apply(ev);
|
|
s.done[seq] = Date.now(); delete s.tries[seq];
|
|
if (r === 'applied') s.stats.applied++; else s.stats.ignored++;
|
|
} catch (e) {
|
|
s.tries[seq] = (s.tries[seq] || 0) + 1;
|
|
console.error('hubsync event', seq, ev.type, e.message);
|
|
if (s.tries[seq] >= EVENT_TRIES) { s.done[seq] = Date.now(); delete s.tries[seq]; s.stats.gaveUp++; note({ type: 'gave-up', seq, event: ev.type, error: String(e.message).slice(0, 160) }); continue; }
|
|
failed = e; break; // answer 503: the hub sends this one (and everything after it) again
|
|
}
|
|
}
|
|
prune(); save();
|
|
return failed ? { status: 503, body: { error: 'retry' } } : { status: 200, body: { ok: true } };
|
|
}
|
|
// the POST /api/hub/events handler: { status, body }. Batches run one at a time.
|
|
function receive(headers, raw) {
|
|
if (!R || !enabled()) return Promise.resolve({ status: 404, body: { error: 'not found' } });
|
|
if (!verify(headers, raw)) return Promise.resolve({ status: 401, body: { error: 'unauthorized' } });
|
|
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return Promise.resolve({ status: 400, body: { error: 'bad json' } }); }
|
|
const run = chain_.then(() => handle(b.events)); chain_ = run.catch(() => {}); return run;
|
|
}
|
|
|
|
// ---------- outbound ----------
|
|
function enqueue(kind, email) {
|
|
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
|
s.outbox.push({ kind, email, at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
|
}
|
|
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(e => console.error('hubsync flush', e.message)); }, 2000); }
|
|
// accounts.onChange: a new account made here, or a later username / sponsor change on any account, goes to /v1/join;
|
|
// a deliberate sponsor change also goes to /v1/sponsor-change
|
|
function touch(email) {
|
|
if (!R || !on() || !email) return;
|
|
(async () => {
|
|
const e = norm(email); const a = await R.accounts.byEmail(e); const s = load();
|
|
if (!a || SHELL_ORIGINS.has(a.joinedVia)) return;
|
|
const sp = await R.accounts.sponsorOf(e); const spE = sp ? norm(sp.email) : '';
|
|
const key = (a.username || '') + '|' + spE;
|
|
const rep = s.reported[e];
|
|
if (!rep) { s.reported[e] = { u: a.username || null, k: key }; enqueue('join', e); } // new here, or an older member's first change since the flag
|
|
else if (rep.k !== key) { rep.u = a.username || null; rep.k = key; enqueue('join', e); }
|
|
const rec = R.follow && R.follow.get ? R.follow.get(e) : null;
|
|
if (rec && DELIBERATE.has(rec.by) && norm(rec.sponsorEmail) === spE && Number(rec.at) > 0 && s.reported[e].sc !== Number(rec.at)) {
|
|
s.reported[e].sc = Number(rec.at); enqueue('sponsor', e);
|
|
}
|
|
save();
|
|
})().catch(err => console.error('hubsync touch', err.message));
|
|
}
|
|
// chain.onEvent (once across copies): a payout switch-on on the InstantAdPay contract goes to /v1/contract-bind
|
|
function onChain(ev) {
|
|
if (ev && ev.type === 'Purchase') return onPurchase(ev);
|
|
if (!R || !on() || !ev || ev.type !== 'MemberActivated' || !ev.account) return;
|
|
(async () => {
|
|
let spW = null; try { const m = ev.sponsorId ? await R.chain.member(ev.sponsorId) : null; spW = m && m.account ? norm(m.account) : null; } catch (e) {}
|
|
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
|
s.outbox.push({ kind: 'bind', email: norm(ev.account), wallet: norm(ev.account), sponsorWallet: spW, at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
|
})().catch(err => console.error('hubsync onChain', err.message));
|
|
}
|
|
// chain.onEvent: money paid into the InstantAdPay contract (Purchase with POL in) goes to /v1/contract-spend (Marty 2026-11-14,
|
|
// rule 2: when two contracts hold different sponsors, the one with money spent decides the network sponsor). Keyed by the
|
|
// buyer's position wallet, the same key as its bind, so the bind is always sent first; the tx hash makes a resend count once.
|
|
// A 404 (bind not there yet, or a linked extra position the hub does not know) is retried like any other miss.
|
|
function onPurchase(ev) {
|
|
if (!R || !on() || !ev.buyerId || !(Number(ev.priceCents) > 0)) return;
|
|
try { if (BigInt(ev.paidWei || '0') <= 0n) return; } catch (e) { return; } // nothing paid in: not a spend
|
|
(async () => {
|
|
const m = await R.chain.member(ev.buyerId); const w = m && m.account ? norm(m.account) : null; if (!w) return;
|
|
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
|
s.outbox.push({ kind: 'spend', email: w, wallet: w, cents: Number(ev.priceCents), tx: ev.tx || null, paidAt: Number(ev.ts) || Date.now(), at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
|
})().catch(err => console.error('hubsync onPurchase', err.message));
|
|
}
|
|
// accounts.onWalletLinked: a main wallet linked here goes to /v1/wallet
|
|
function wallet(email) {
|
|
if (!R || !on() || !email) return;
|
|
(async () => {
|
|
const a = await R.accounts.byEmail(email);
|
|
if (a && a.address && !R.accounts.isUnclaimedShell(a)) enqueue('wallet', norm(email)); // a waiting account's wallet came from a sync
|
|
})().catch(err => console.error('hubsync wallet', err.message));
|
|
}
|
|
// sponsorfollow / tank.js label a window expiry 'expire'; the hub (and its DELIBERATE list) calls it 'expiry' (fixed 2026-11-15:
|
|
// before, IAP window-expiry moves never reached the hub as a sponsor change)
|
|
const HUB_BY = { expire: 'expiry' };
|
|
const hubBy = by => HUB_BY[by] || by;
|
|
const ROUTE = { join: '/v1/join', wallet: '/v1/wallet', sponsor: '/v1/sponsor-change', bind: '/v1/contract-bind', spend: '/v1/contract-spend' };
|
|
async function bodyFor(item) {
|
|
if (item.kind === 'spend') {
|
|
let owner = null; try { owner = (await R.accounts.byAddress(item.wallet)) || (R.accounts.positionOwner ? await R.accounts.positionOwner(item.wallet) : null); } catch (e) {}
|
|
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, cents: item.cents, tx: item.tx || undefined, at: item.paidAt };
|
|
}
|
|
if (item.kind === 'bind') {
|
|
let owner = null; try { owner = await R.accounts.byAddress(item.wallet); } catch (e) {}
|
|
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, sponsorRef: item.sponsorWallet || '' };
|
|
}
|
|
const a = await R.accounts.byEmail(item.email); if (!a) return null;
|
|
if (item.kind === 'sponsor') {
|
|
const sp = await R.accounts.sponsorOf(a.email); const rec = R.follow && R.follow.get ? R.follow.get(a.email) : null;
|
|
if (!rec || !DELIBERATE.has(rec.by) || norm(rec.sponsorEmail) !== (sp ? norm(sp.email) : '')) return null; // superseded since
|
|
return { email: a.email, sponsorEmail: sp ? sp.email : null, by: hubBy(rec.by) };
|
|
}
|
|
if (item.kind === 'wallet') return a.address ? { email: a.email, wallet: a.address } : null;
|
|
const sp = await R.accounts.sponsorOf(a.email);
|
|
return { email: a.email, ref: sp ? sp.email : (a.sponsorRef || undefined), username: a.username || undefined };
|
|
}
|
|
async function flush(force) { // force (tests, admin): ignore the backoff wait
|
|
if (!R || !on() || sending) return { skipped: true };
|
|
sending = true; const s = load(); const now = Date.now(); const held = new Set(); let sent = 0;
|
|
try {
|
|
for (const item of s.outbox.slice()) {
|
|
if (held.has(item.email)) continue; // keep each member's calls in order (join before wallet)
|
|
if (item.next > now && !force) { held.add(item.email); continue; }
|
|
const drop = (why, code) => { s.outbox.splice(s.outbox.indexOf(item), 1); if (why) note({ type: 'out-' + why, kind: item.kind, email: item.email, code: code || null }); };
|
|
let r = null;
|
|
try {
|
|
const body = await bodyFor(item); if (!body) { drop('gone'); save(); continue; }
|
|
r = await hubPost(ROUTE[item.kind] || '/v1/wallet', body);
|
|
} catch (e) { r = { status: 0, body: { error: e.message } }; }
|
|
const code = (r.body && r.body.error) || null;
|
|
if (r.status >= 200 && r.status < 300) {
|
|
drop(null); s.stats.sent++; sent++;
|
|
if (item.kind === 'join' && r.body && r.body.person) await compare(item.email, r.body.person.sponsor && r.body.person.sponsor.email, 'iap-join');
|
|
} else if ((r.status === 400 || r.status === 409) || (r.status === 403 && code === 'blocked') || (item.kind === 'sponsor' && r.status === 404)) {
|
|
drop('refused', code); s.stats.refused++;
|
|
} else {
|
|
item.tries++; s.stats.sendErrors++;
|
|
if (item.tries >= OUT_TRIES) drop('gave-up', code || String(r.status));
|
|
else { item.next = now + Math.min(3600000, 30000 * Math.pow(2, item.tries)); held.add(item.email); }
|
|
}
|
|
save();
|
|
}
|
|
} finally { sending = false; }
|
|
return { sent, waiting: s.outbox.length };
|
|
}
|
|
// password sign-ups do not fire accounts.onChange until they pick a username: every 10 minutes, any account made here since
|
|
// the flag went on that the hub has not heard about yet is queued
|
|
async function reconcile() {
|
|
if (!R || !on()) return { skipped: true };
|
|
const s = load(); let queued = 0;
|
|
for (const a of await R.accounts.listAll(1e6)) {
|
|
const e = norm(a.email);
|
|
if (!e || s.reported[e] || SHELL_ORIGINS.has(a.joinedVia) || Number(a.created) < s.since) continue;
|
|
s.reported[e] = { u: a.username || null }; s.outbox.push({ kind: 'join', email: e, at: Date.now(), tries: 0, next: 0 }); queued++;
|
|
}
|
|
if (queued) { save(); kick(); }
|
|
return { queued };
|
|
}
|
|
function start() {
|
|
if (interval) return;
|
|
interval = setInterval(() => flush().catch(e => console.error('hubsync flush', e.message)), 30000);
|
|
const rec = setInterval(() => reconcile().catch(e => console.error('hubsync reconcile', e.message)), 10 * 60000);
|
|
for (const t of [interval, rec]) if (t.unref) t.unref();
|
|
}
|
|
// ---------- rule 3: the holding tank asks the hub (Marty 2026-11-14) ----------
|
|
// The tank never offers anyone locked on ANY network contract, or anyone the hub already knows a sponsor for. tank.js asks
|
|
// through its hooks (networkHeld, networkLocked, network); server.js wires them only with HUB_ENABLED, so with the flag off
|
|
// the tank works exactly as before. One /v1/locked {emails, detail} call per 2,000 emails, cached per email: fresh for 10
|
|
// minutes. CONSERVATIVE when the hub cannot be reached: the last answer stands for up to 1 hour, after that the person is
|
|
// held ('unknown', not offered, not moved to the tank, not auto-assigned) until the hub answers again. A held tank for a
|
|
// while is the safe side; offering someone a contract already holds is not. After a failed call the hub is left alone
|
|
// for 2 minutes (page views must not each wait for a timeout).
|
|
const HELD_FRESH_MS = 10 * 60000, HELD_STALE_MS = 60 * 60000, HELD_DOWN_MS = 2 * 60000, HELD_CHUNK = 2000;
|
|
const held = new Map(); let heldDownUntil = 0, heldBusy = Promise.resolve();
|
|
async function refreshHeld(emails, timeout) {
|
|
const run = heldBusy.then(async () => {
|
|
const now = Date.now(); const miss = emails.filter(e => { const c = held.get(e); return !c || now - c.at > HELD_FRESH_MS; });
|
|
if (!miss.length || now < heldDownUntil) return;
|
|
try {
|
|
for (let i = 0; i < miss.length; i += HELD_CHUNK) {
|
|
const part = miss.slice(i, i + HELD_CHUNK);
|
|
const r = await hubPost('/v1/locked', { emails: part, detail: true, ids: true }, timeout || 5000); // ids: hub id + door per row (a hub without it ignores the flag)
|
|
if (r.status !== 200 || !r.body || !r.body.found || typeof r.body.found !== 'object') throw new Error('hub locked ' + r.status);
|
|
if (held.size > 60000) held.clear();
|
|
const at = Date.now(); for (const e of part) held.set(e, { at, row: r.body.found[e] || null });
|
|
}
|
|
} catch (e) { heldDownUntil = Date.now() + HELD_DOWN_MS; load().stats.heldErrors = (load().stats.heldErrors || 0) + 1; console.log('hubsync: hub /v1/locked unreachable:', e.message); }
|
|
});
|
|
heldBusy = run.catch(() => {}); return run;
|
|
}
|
|
const whyHeld = (c, now) => (!c || now - c.at > HELD_STALE_MS ? 'unknown' : c.row && c.row.locked ? 'locked' : c.row && c.row.sponsored ? 'sponsored' : null);
|
|
// accounts -> Map email -> 'locked' | 'sponsored' | 'unknown' for the ones the tank must not offer
|
|
async function heldAmong(accts, opts) {
|
|
const out = new Map(); if (!R || !on()) return out;
|
|
const emails = [...new Set((accts || []).map(a => norm(a && a.email)).filter(Boolean))]; if (!emails.length) return out;
|
|
await refreshHeld(emails, opts && opts.timeout);
|
|
const now = Date.now(); for (const e of emails) { const w = whyHeld(held.get(e), now); if (w) out.set(e, w); }
|
|
return out;
|
|
}
|
|
// release, rescue and expiry moves: 'locked' (on any network contract) | 'unknown' (hub not answering) | null
|
|
async function lockedAnywhere(email) {
|
|
if (!R || !on()) return null; const e = norm(email); if (!e) return null;
|
|
await refreshHeld([e]); const w = whyHeld(held.get(e), Date.now());
|
|
return w === 'locked' || w === 'unknown' ? w : null;
|
|
}
|
|
// the sponsor the hub knows for a tank member, for tank.alignToNetwork: this contract's lock first, else the network sponsor
|
|
// OFF unless HUB_TANK_ALIGN=on: aligning moves sponsors (and on LinkSpin a linked wallet then has its payouts switched on, which
|
|
// locks that sponsor on the contract), so the first run over a full tank is Marty's deliberate step, not a side effect of the
|
|
// deploy. While it is off the people the hub knows a sponsor for are simply held out of the tank (rule 3).
|
|
const alignOn = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_TANK_ALIGN || '').trim());
|
|
async function hubSponsor(email) {
|
|
if (!R || !on() || !alignOn()) return null; const e = norm(email); if (!e) return null;
|
|
await refreshHeld([e]); const c = held.get(e); if (!c || !c.row || Date.now() - c.at > HELD_STALE_MS) return null;
|
|
const l = c.row.locks && Object.prototype.hasOwnProperty.call(c.row.locks, CONTRACT) ? c.row.locks[CONTRACT] : undefined;
|
|
const sp = norm(l !== undefined ? l : c.row.sponsorEmail);
|
|
return sp && sp !== e ? { sponsorEmail: sp, via: l !== undefined ? 'network hub, InstantAdPay contract' : 'network hub' } : null;
|
|
}
|
|
|
|
// the hub id and first door of a person the tank cache holds (5xYourTeam draft pool, 2026-11-15): { id, door } | null. Read-only, no call.
|
|
function hubInfo(email) { const c = held.get(norm(email)); return c && c.row && c.row.id ? { id: c.row.id, door: c.row.door || null } : null; }
|
|
function adminView() {
|
|
const s = load();
|
|
return Object.assign({ enabled: enabled(), on: on(), site: SITE(), url: URL_(), since: s.since, outbox: s.outbox.length, retrying: Object.keys(s.tries).length,
|
|
disagree: Object.keys(s.disagree).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() });
|
|
}
|
|
module.exports = { _state: load, _save: save, _forgetHeld: email => held.delete(norm(email)), _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
|