From 836c7b17c26437ae4df41928bda1809a95351f0a Mon Sep 17 00:00:00 2001 From: martbost Date: Sat, 14 Nov 2026 08:51:58 -0600 Subject: [PATCH] Hub switch-on (Marty 2026-11-14). Rule 2: a hub arrival (and a sponsor climbed for it) gets person.locks.iap's sponsor when the InstantAdPay contract holds them, never the plain network sponsor; sponsor.changed stays ignored. Quiet: lssync never pushes a hub waiting account to LinkSpin (its registry route would switch payouts on and email them). Rule 3: the holding tank (waiting, release, expiry, rescue, readyTick, autoAssign) leaves out anyone the hub reports locked on any contract or sponsored; /v1/locked detail cached 10 min, last answer kept 1 h, after that held (unknown). Alignment to the hub sponsor only with HUB_TANK_ALIGN=on. Needs network-hub b44dba6. qa/hubsync.test.cjs 19/19 (mail audit with recording mailer, messages, fetch and https), iap-qa member: ALL PASSED Co-Authored-By: Claude Opus 5.5 --- hubsync.js | 84 ++++++++++++++++++++++++++++----- lssync.js | 8 +++- qa/hubsync.test.cjs | 111 +++++++++++++++++++++++++++++++++++++++++++- server.js | 6 ++- tank.js | 43 ++++++++++++++--- 5 files changed, 231 insertions(+), 21 deletions(-) diff --git a/hubsync.js b/hubsync.js index 24a11df..f93904a 100644 --- a/hubsync.js +++ b/hubsync.js @@ -11,8 +11,11 @@ // 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 TODO: no clean path yet. lsinbound's follow rule needs sponsorSetAt / By / PrevEmail, which the hub -// view does not expose, and a 'contract' change is not one of the deliberate kinds. Ignored (logged). +// 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). // 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. @@ -69,9 +72,9 @@ function verify(headers, raw) { const want = sign(ts, raw); return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig)); } -async function hubPost(p, body) { +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(15000) }); + 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 }; } @@ -81,7 +84,11 @@ async function resolve(q) { 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'; -const rowOf = p => ({ email: norm(p.email), username: p.username || null, wallet: p.wallet || null, sponsorEmail: (p.sponsor && p.sponsor.email) || null, joinedAt: Number(p.firstDoor && p.firstDoor.at) || null, profile: null }); +// 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) { @@ -102,8 +109,8 @@ async function memberJoined(ev) { 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 && p.sponsor && p.sponsor.email; i++) { - const se = norm(p.sponsor.email); if (seen.has(se) || await A.byEmail(se)) break; + 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; } @@ -126,8 +133,9 @@ async function walletConnected(ev) { async function apply(ev) { if (ev.type === 'member.joined') return memberJoined(ev); if (ev.type === 'wallet.connected') return walletConnected(ev); - // TODO sponsor.changed: needs the deliberate-change record (at / by / previous sponsor) in the hub view before it can go - // through sponsorfollow's rule like LinkSpin's changes do. Until then the hub's change is ignored here. + // 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() { @@ -286,9 +294,63 @@ function start() { 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 }, timeout || 5000); + 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; +} + 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 }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() }); + 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 = { init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, _sign: sign }; +module.exports = { init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } }; diff --git a/lssync.js b/lssync.js index 772853c..2635edd 100644 --- a/lssync.js +++ b/lssync.js @@ -75,10 +75,14 @@ async function push(rows) { } st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent; } +// QUIET (Marty 2026-11-14, "join one = join all"): a waiting account the network hub made here (joinedVia 'hub', never signed +// in) is never pushed to LinkSpin. The hub tells LinkSpin itself, quietly; pushed from here, LinkSpin's registry route would +// link the wallet and its engine would switch payouts on and email them. Once they sign in here they sync like anyone. +const hubShell = a => !!a && a.joinedVia === 'hub' && R.accounts.isUnclaimedShell && R.accounts.isUnclaimedShell(a); // an account just changed: send its row shortly (debounced so a join + username + wallet in a row go as one) function touch(email) { if (!on() || !email) return; pending.set(String(email).toLowerCase(), Date.now()); - if (!timer) timer = setTimeout(async () => { timer = null; const st = load(); const emails = [...pending.keys()].filter(e => !muted.has(e)); for (const e of emails) pending.delete(e); try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a) { const r = await rowFor(a); if (st.hashes[r.email] !== hashOf(r)) rows.push(r); } } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000); + if (!timer) timer = setTimeout(async () => { timer = null; const st = load(); const emails = [...pending.keys()].filter(e => !muted.has(e)); for (const e of emails) pending.delete(e); try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a && !hubShell(a)) { const r = await rowFor(a); if (st.hashes[r.email] !== hashOf(r)) rows.push(r); } } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000); } // the reconcile pass: only rows whose hash changed since the last push async function tick(force) { @@ -88,7 +92,7 @@ async function tick(force) { const all = await R.accounts.listAll(50000, { shells: true }); const st = load(); const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); } const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } } - const rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); } + const rows = []; for (const a of all) { if (!a.email || muted.has(a.email) || hubShell(a)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); } const sent = rows.length ? await push(rows) : 0; return { accounts: all.length, changed: rows.length, sent }; } catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; } diff --git a/qa/hubsync.test.cjs b/qa/hubsync.test.cjs index 0688e45..7be16ef 100644 --- a/qa/hubsync.test.cjs +++ b/qa/hubsync.test.cjs @@ -12,13 +12,18 @@ const assert = require('assert'); const { spawn } = require('child_process'); const ROOT = path.join(__dirname, '..'); -const HUB_DIR = process.env.HUB_DIR || ['..', path.join('..', '..')].flatMap(up => ['network-hub-resolve-id', 'network-hub'].map(d => path.join(ROOT, up, d))).find(d => fs.existsSync(path.join(d, 'server.js'))); +const HUB_DIR = process.env.HUB_DIR || ['..', path.join('..', '..')].flatMap(up => ['network-hub', 'network-hub-resolve-id'].map(d => path.join(ROOT, up, d))).find(d => fs.existsSync(path.join(d, 'server.js'))); let fails = 0, n = 0; async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e && e.stack ? e.stack.split('\n').slice(0, 3).join(' | ') : e); } } const IAP_SECRET = 'i'.repeat(40), CTB_SECRET = 'c'.repeat(40); const W = k => '0x' + String(k).repeat(40).slice(0, 40); const sig = (secret, ts, raw) => crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex'); const listen = srv => new Promise(ok => srv.listen(0, '127.0.0.1', () => ok(srv.address().port))); +// mail audit (2026-11-14): every outbound request this process makes is recorded; only the local hub and site may be called. +// mailer.js sends with https.request (SendGrid), Telegram and Sendy go out over https too, so both doors are watched. +const outside = []; +{ const realFetch = global.fetch; global.fetch = (u, o) => { const s = String(u && u.url ? u.url : u); if (!/^http:[/][/]127[.]0[.]0[.]1:/.test(s)) outside.push(s); return realFetch(u, o); }; + const https = require('https'); const realReq = https.request; https.request = function (...a) { outside.push('https ' + JSON.stringify((a[0] && a[0].hostname) || a[0])); return realReq.apply(this, a); }; } delete process.env.DATABASE_URL; delete process.env.LS_SYNC_SECRET; // JSON stores, LinkSpin push off const HUB_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-hub-')); @@ -192,6 +197,110 @@ const IAP_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-iap-')); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200); }); + const HP = hubReq('lib/people'); + await t('rule 2 on arrival: someone the InstantAdPay contract holds arrives under that lock sponsor, not the network sponsor; sponsor.changed never moves them', async () => { + await ctb('/v1/join', { email: 'lx@example.test', username: 'lockx' }); // their sponsor on the InstantAdPay contract + await ctb('/v1/join', { email: 'ly@example.test', username: 'locky' }); // their sponsor on LinkSpin, where the money was spent + await ctb('/v1/join', { email: 'lk@example.test', username: 'lockkid', ref: 'locky' }); + HP.bindContract({ site: 'iap', contract: 'iap', email: 'lk@example.test', wallet: W('3'), sponsorRef: 'lockx', at: 1000 }); + HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'lk@example.test', wallet: W('3'), sponsorRef: 'locky', at: 2000, spentCents: 2500 }); + await hubStore.flush(); + const hp = hubPerson('lk@example.test'); + assert.strictEqual(hp.sponsorId, hubPerson('ly@example.test').id, 'network sponsor = LinkSpin (money spent there)'); + assert.strictEqual(hp.bindings.iap.sponsorId, hubPerson('lx@example.test').id); + await deliver(); + const kid = await accounts.byEmail('lk@example.test'); const lx = await accounts.byEmail('lx@example.test'); + assert.ok(kid && lx, 'both arrived'); + assert.strictEqual(kid.sponsorRef, lx.username || lx.code, 'the InstantAdPay lock sponsor is written here'); + const s = signed([{ seq: 99101, type: 'sponsor.changed', personId: hp.id, data: { by: 'contract', contract: 'linkspin' } }]); + assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200); + assert.strictEqual((await accounts.byEmail('lk@example.test')).sponsorRef, lx.username || lx.code, 'sponsor.changed is ignored'); + // climbing: a lock sponsor not on InstantAdPay yet comes along before the member (their event alone) + await ctb('/v1/join', { email: 'lz@example.test', username: 'lockz' }); + await ctb('/v1/join', { email: 'lk2@example.test', username: 'lockkid2', ref: 'locky' }); + HP.bindContract({ site: 'iap', contract: 'iap', email: 'lk2@example.test', wallet: W('4'), sponsorRef: 'lockz', at: 3000, spentCents: 2000 }); + HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'lk2@example.test', wallet: W('4'), sponsorRef: 'locky', at: 1500, spentCents: 2000 }); // earlier spend: network = locky + await hubStore.flush(); + assert.strictEqual(hubPerson('lk2@example.test').sponsorId, hubPerson('ly@example.test').id); + const ev = hubStore.eventsAfter(0, 1e6).find(e => e.type === 'member.joined' && e.personId === hubPerson('lk2@example.test').id); + const s2 = signed([ev]); assert.strictEqual((await hubsync.receive(s2.headers, s2.raw)).status, 200); + const lz = await accounts.byEmail('lz@example.test'); + assert.ok(lz, 'the lock sponsor came along'); assert.strictEqual((await accounts.byEmail('lk2@example.test')).sponsorRef, lz.username || lz.code); + await deliver(); + }); + + // the holding tank, as server.js wires it with HUB_ENABLED, with a mailer and messages that only record + const tank = require(path.join(ROOT, 'tank.js')); + const sent = []; + const mailer = { hasKey: () => true, send: async (...a) => { sent.push(['mail', a[0], a[1]]); } }; + const messages = { sendChat: async (...a) => { sent.push(['chat', a[2]]); }, deliver: async (...a) => { sent.push(['notice', a[2]]); }, lastFrom: async () => Date.now() }; // every sponsor 'just wrote': rescue warnings are not what this checks + tank.init({ dataDir: IAP_DATA, accounts, chain: { recentEvents: () => [], member: async () => null }, messages, mailer, + hooks: { network: async (email, address) => (await hubsync.hubSponsor(email)) || lsinbound.networkSponsor(email, address), networkHeld: a => hubsync.heldAmong(a), networkLocked: e => hubsync.lockedAnywhere(e) } }); + + await t('rule 3: the tank never offers anyone locked on any network contract or sponsored in the hub; release refuses a locked member', async () => { + await ctb('/v1/join', { email: 'tk1@example.test', username: 'tk1ctb', ref: 'annctb' }); // the hub knows a sponsor + for (const e of ['tk1', 'tk2', 'tk3']) assert.ok((await accounts.ensure(e + '@example.test', '', null, null)).created); // signed up here, no sponsor + await settle(); await hubsync.flush(true); + HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'tk2@example.test', wallet: W('5'), sponsorRef: '' }); await hubStore.flush(); // locked, top of that tree + hubsync._heldReset(); + const held = await hubsync.heldAmong([await accounts.byEmail('tk1@example.test'), await accounts.byEmail('tk2@example.test'), await accounts.byEmail('tk3@example.test')]); + assert.deepStrictEqual([...held.entries()].sort(), [['tk1@example.test', 'sponsored'], ['tk2@example.test', 'locked']]); + const w = (await tank.waiting()).map(x => x.email); + assert.ok(w.includes('tk3@example.test'), 'a free member is offered'); + assert.ok(!w.includes('tk1@example.test') && !w.includes('tk2@example.test'), 'sponsored and locked are not: ' + w.join(',')); + // tk2 under erin here, not activated here: releasing them to the tank is refused, the hub's lock elsewhere stands + const erin = await accounts.byEmail('erin@example.test'); await accounts.setSponsorRef('tk2@example.test', erin.username || erin.code); + const r = await tank.release('erin@example.test', 'tk2@example.test'); + assert.ok(r.error && /locked/.test(r.error), JSON.stringify(r)); + assert.strictEqual((await accounts.byEmail('tk2@example.test')).sponsorRef, erin.username || erin.code); + // the 15-minute tick: with HUB_TANK_ALIGN off tk1 is only held; with it on, aligned to the sponsor the hub knows (ann has a real account here), quietly + await tank.readyTick(); assert.strictEqual((await accounts.byEmail('tk1@example.test')).sponsorRef || '', '', 'alignment from the hub is off by default'); + process.env.HUB_TANK_ALIGN = 'on'; await tank.readyTick(); delete process.env.HUB_TANK_ALIGN; + assert.strictEqual((await accounts.byEmail('tk1@example.test')).sponsorRef, ann.username || ann.code, 'aligned to the hub sponsor'); + }); + + await t('rule 3 fail-safe: hub unreachable past the 1-hour cache = nobody it was asked about is offered; back = offered again', async () => { + process.env.HUB_URL = 'http://127.0.0.1:1'; hubsync._heldAge(30 * 60000); + assert.ok((await tank.waiting()).map(x => x.email).includes('tk3@example.test'), 'within the hour the last answer stands'); + hubsync._heldReset(); // nothing cached, hub down + assert.ok(!(await tank.waiting()).map(x => x.email).includes('tk3@example.test'), 'unknown = held'); + assert.strictEqual(await hubsync.lockedAnywhere('tk3@example.test'), 'unknown'); + process.env.HUB_URL = HUB; hubsync._heldReset(); + assert.ok((await tank.waiting()).map(x => x.email).includes('tk3@example.test')); + }); + + await t('mail audit: hub arrivals (new, sponsor climbed, existing filled, wallet) and the tank ticks send no mail, chat, notice or outside call', async () => { + sent.length = 0; outside.length = 0; + await ctb('/v1/join', { email: 'ma@example.test', username: 'mailtop' }); await ctb('/v1/wallet', { email: 'ma@example.test', wallet: W('6') }); + await ctb('/v1/join', { email: 'mb@example.test', username: 'mailkid', ref: 'mailtop' }); await ctb('/v1/wallet', { email: 'mb@example.test', wallet: W('8') }); + process.env.HUB_ENABLED = ''; await accounts.ensure('mc@example.test', '', null, null); process.env.HUB_ENABLED = '1'; // here before the hub knew them + await ctb('/v1/join', { email: 'mc@example.test', username: 'mailfill' }); // an existing InstantAdPay account: empty fields filled + const evs = hubStore.eventsAfter(hubStore.cursor('iap'), 100); + const kid = evs.find(e => e.personId === hubPerson('mb@example.test').id && e.type === 'member.joined'); + const s = signed([kid]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200); // the kid first: the sponsor climbs + await deliver(); + assert.ok(await accounts.byEmail('ma@example.test') && await accounts.byEmail('mb@example.test')); + assert.strictEqual((await accounts.byEmail('mb@example.test')).address, W('8')); + assert.strictEqual((await accounts.byEmail('mc@example.test')).username, 'mailfill', 'filled'); + await settle(); await hubsync.flush(true); await tank.readyTick(); await tank.sweep(); await settle(); await hubsync.flush(true); + assert.deepStrictEqual(JSON.parse(fs.readFileSync(path.join(IAP_DATA, 'hubsync.json'), 'utf8')).outbox, []); + assert.deepStrictEqual(sent, [], 'nothing sent'); + assert.deepStrictEqual(outside, [], 'no outside call'); + // the old direct LinkSpin sync never pushes a waiting account the hub made (LinkSpin's registry route would switch payouts + // on and email them); a member who signs up here still goes + const pushed = []; const lsStub = http.createServer((req, res) => { let d = ''; req.on('data', c => { d += c; }); req.on('end', () => { try { for (const r of JSON.parse(d).rows || []) pushed.push(r.email); } catch (e) {} res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"ok":true,"proto":2}'); }); }); + process.env.LS_URL = 'http://127.0.0.1:' + await listen(lsStub); process.env.LS_SYNC_SECRET = 's'.repeat(40); + try { + await lssync.tick(true); + assert.ok(pushed.length > 0, 'the sync ran'); + for (const e of ['ma@example.test', 'mb@example.test', 'lk@example.test', 'bob@example.test']) assert.ok(!pushed.includes(e), e + ' (a hub waiting account) was pushed'); + assert.ok(pushed.includes('erin@example.test'), 'an InstantAdPay sign-up still syncs'); + } finally { delete process.env.LS_SYNC_SECRET; lsStub.close(); } + // and the hub path itself never loads a mail module + const loaded = Object.keys(require.cache).map(f => path.basename(f)); + for (const m of ['mailer.js', 'sendy.js', 'messages.js', 'drip.js']) assert.ok(!loaded.includes(m), m + ' is loaded'); + }); + await t('flag off: the module answers 404 and reports nothing', async () => { process.env.HUB_ENABLED = ''; const s = signed([]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 404); diff --git a/server.js b/server.js index 5c7bdbf..8b81396 100644 --- a/server.js +++ b/server.js @@ -728,7 +728,11 @@ async function boot() { activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null }); tank.init({ capOpen: () => siteConfig().tankAdoptCap, dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore, // activation hold + 24-hour safety net (2026-10-27): a tank member is never bound under the fallback position - hooks: { network: (email, address) => lsinbound.networkSponsor(email, address), isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em), + // network hub rule 3 (2026-11-14, only with HUB_ENABLED): the hub's sponsor comes first for alignment, and nobody it reports + // locked on a network contract or sponsored is offered, moved to the tank or auto-assigned (hubsync.js: cache + fail-safe) + hooks: { network: async (email, address) => (hubsync.enabled() ? await hubsync.hubSponsor(email).catch(() => null) : null) || lsinbound.networkSponsor(email, address), + networkHeld: hubsync.enabled() ? accts => hubsync.heldAmong(accts) : null, networkLocked: hubsync.enabled() ? email => hubsync.lockedAnywhere(email) : null, + isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em), payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1, assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text), // switch-on-payouts reminders after an assignment (2026-10-27): one send per key across both app copies (deploy overlap), diff --git a/tank.js b/tank.js index 9e88310..0bb7395 100644 --- a/tank.js +++ b/tank.js @@ -86,11 +86,26 @@ const countAll = async email => (await impl().countFor(email)) + remoteCount(ema const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2'); const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email)); const inTank = a => !a.sponsorRef && !a.memberId; // arrived with no sponsor (or fell back), still free +// Rule 3 (Marty 2026-11-14): never offer anyone locked on ANY network contract or whom the network hub already knows a sponsor +// for (hooks.networkHeld = hubsync.heldAmong, wired only with HUB_ENABLED). A hook that throws holds everyone it was asked +// about: the conservative side. No hook (flag off, tests) = nothing held, the tank as before. +const lc = v => String(v || '').trim().toLowerCase(); +async function heldSet(accts) { + if (!hooks.networkHeld || !accts.length) return new Map(); + try { return (await hooks.networkHeld(accts)) || new Map(); } catch (e) { console.error('tank networkHeld', e.message); return new Map(accts.map(a => [lc(a.email), 'unknown'])); } +} +// release / rescue / expiry: 'locked' | 'unknown' | null (hooks.networkLocked = hubsync.lockedAnywhere) +const HELD_WHY = { locked: 'they are locked on a network contract', sponsored: 'it already knows a sponsor for them', unknown: 'nothing (it is not answering)' }; +async function lockedWhy(email) { + if (!hooks.networkLocked) return null; + try { return (await hooks.networkLocked(email)) || null; } catch (e) { return 'unknown'; } +} // waiting list: newest sign-in first so a live one is easy to spot async function waiting() { const all = await accounts.listAll(5000); - const rows = all.filter(a => inTank(a) && !remoteOpen(a.email)); // one network tank: someone adopted on LinkSpin is not waiting here + const cand = all.filter(a => inTank(a) && !remoteOpen(a.email)); // one network tank: someone adopted on LinkSpin is not waiting here + const held = await heldSet(cand); const rows = cand.filter(a => !held.has(lc(a.email))); // rule 3: locked or sponsored elsewhere // what each of them has earned by surfing on their own, no sponsor (Marty, 2026-09-29), so an adopter can spot the workers const tot = ads && ads.earnedTotals ? await ads.earnedTotals(rows.map(a => a.email)) : {}; return rows.map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, @@ -178,6 +193,8 @@ async function release(ownerEmail, directEmail) { const toks = [owner.code, owner.username, owner.memberId ? String(owner.memberId) : null].filter(Boolean).map(String); if (!toks.includes(String(direct.sponsorRef || ''))) return { error: 'That member is not in your line.' }; if (direct.memberId) return { error: 'That member has already bought; on-chain sponsorship cannot move.' }; + const lk = await lockedWhy(d); // rule 3: someone a network contract holds never goes to the tank + if (lk) return { error: lk === 'locked' ? nameOf(direct) + ' is locked to a sponsor on a network contract, so they cannot go to the holding tank.' : 'The network record for ' + nameOf(direct) + ' cannot be checked right now. Try again in a few minutes.' }; // picked up from the tank recently? then it is not theirs to drop yet (Bradley churned three in 80 seconds, 2026-09-13) const openAds = (await impl().open(null)).filter(ad => ad.adoptee === d); let young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS); @@ -208,6 +225,9 @@ async function sweep() { if (!a) { await impl().setStatus(ad.id, 'expired'); continue; } if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; } if (await impl().countFor(ad.adoptee) >= MAX_ADOPTIONS) { await impl().setStatus(ad.id, 'expired'); kept++; continue; } + const lk = await lockedWhy(ad.adoptee); // rule 3: a person a network contract holds stays with the adopter, never back in the tank + if (lk === 'unknown') continue; // the hub is not answering: try again next hour + if (lk === 'locked') { await impl().setStatus(ad.id, 'expired'); kept++; continue; } await setSponsor(ad.adoptee, '', 'expire', 'adoption window ended'); await impl().setStatus(ad.id, 'expired'); back++; } @@ -272,11 +292,14 @@ async function markContacted(sponsorEmail, leadEmail) { async function rescueSweep() { const now = Date.now(); let warned = 0, rescued = 0, dead = 0; - for (const a of await accounts.listAll(5000)) { + const all = await accounts.listAll(5000); + await heldSet(all.filter(a => !a.memberId && !a.address && a.sponsorRef)); // one batched hub call warms the cache for lockedWhy below + for (const a of all) { if (a.memberId || a.address || !a.sponsorRef) continue; // bound, wallet, or already in the tank if (await impl().hasRecord(a.email)) continue; // adopted / rescued before: the tank's window rules const pv = store && store.get(a.email); if (remoteCount(a.email) || (pv && pv.by !== 'admin')) continue; // adopted / released / rescued on LinkSpin: the tank's window rules there + if (await lockedWhy(a.email)) continue; // rule 3: locked on a network contract (or the hub is not answering): no warning, no move const sp = await sponsorOf(a); if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day if (now - (a.created || 0) < 86400000) continue; @@ -385,7 +408,7 @@ async function previousSponsors(email) { async function alignToNetwork(a) { if (!a || !inTank(a) || !hooks.network) return null; const e = String(a.email || '').toLowerCase(); if (!e) return null; - const n = hooks.network(e, a.address || null); if (!n || !n.sponsorEmail) return null; + const n = await Promise.resolve(hooks.network(e, a.address || null)).catch(() => null); if (!n || !n.sponsorEmail) return null; // the hub's answer is async const spEmail = String(n.sponsorEmail).toLowerCase(); if (spEmail === e) return null; if ((await previousSponsors(e)).has(spEmail)) return null; // never back to someone they were released or rescued from const sp = await accounts.byEmail(spEmail); @@ -396,7 +419,7 @@ async function alignToNetwork(a) { for (let i = 0; cur && i < 60; i++) { if (cur.email === e || seen.has(cur.email)) return null; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); } const fresh = await accounts.byEmail(e); if (!fresh || !inTank(fresh)) return null; const r = await accounts.setSponsorRef(e, token); if (r && r.error) return null; - const st = RS.load(); const why = 'aligned to network sponsor ' + nameOf(sp) + ' from LinkSpin (' + (n.via || 'email') + ')'; + const st = RS.load(); const why = 'aligned to network sponsor ' + nameOf(sp) + (/hub/.test(n.via || '') ? ' (' + n.via + ')' : ' from LinkSpin (' + (n.via || 'email') + ')'); st.aligned.push({ email: e, to: sp.email, toName: nameOf(sp), via: n.via || 'email', at: clock(), why }); if (st.aligned.length > 300) st.aligned = st.aligned.slice(-300); if (st.ready[e] && !st.ready[e].done) { st.ready[e].done = clock(); st.ready[e].aligned = sp.email; } @@ -447,8 +470,14 @@ async function autoAssignRun() { due.push([e, rec, a]); } due.sort((x, y) => x[1].readyAt - y[1].readyAt); + const netHeld = await heldSet(due.map(x => x[2])); let pool = null; for (const [e, rec, a] of due) { + if (netHeld.has(e)) { // rule 3: never auto-assigned; the admin hears once (their network sponsor has no usable account here yet, or the hub is not answering) + out.held++; + if (!rec.networkHeldAlerted) { rec.networkHeldAlerted = clock(); RS.save(); if (hooks.adminAlert) { try { await hooks.adminAlert(BRAND + ' holding tank: ' + nameOf(a) + ' (' + e + ') is held and NOT auto-assigned: the network hub says ' + (HELD_WHY[netHeld.get(e)] || netHeld.get(e)) + ', and that sponsor could not be used here. Set their sponsor in Admin if it should be someone here.'); } catch (err) {} } } + continue; + } if (!pool) pool = await rotation(e); let done = null; for (const c of pool) { @@ -481,10 +510,12 @@ async function autoAssignRun() { // run the safety net. `fresh` = members who became ready and were not announced yet (server.js posts them). async function readyTick() { const st = RS.load(); const fresh = []; let aligned = 0; - for (const a of await accounts.listAll(5000)) { - if (!inTank(a)) continue; + const tankers = (await accounts.listAll(5000)).filter(inTank); + const netHeld = await heldSet(tankers); // one batched hub call; alignToNetwork below reads the same cache + for (const a of tankers) { if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; } if (remoteOpen(a.email)) continue; + if (netHeld.has(lc(a.email))) continue; // rule 3: not announced, no 24-hour clock while the network holds them const rec = markReady(a); // linkedNow: the member was on the site when they became ready, so they linked the wallet just now; otherwise the // wallet predates this tank visit (e.g. a dormant member returned by a sponsor; Marty 2026-10-29: the notice read as a