Merge branch 'hub-listener'

This commit is contained in:
martbost
2026-11-13 07:51:48 -06:00
4 changed files with 334 additions and 1 deletions
+193
View File
@@ -0,0 +1,193 @@
// Network hub link (2026-11-12, Marty 2026-11-06: one membership from any door; the hub is the single identity; the contract
// sponsor is the truth; with no binding, the earliest join wins). Two directions, both OFF unless HUB_ENABLED=1:
// IN POST /api/hub/events body {events:[{seq, at, type, personId, data}]}, headers X-Hub-Ts (ms) + X-Hub-Sig = hex
// HMAC-SHA256(ts + "\n" + rawBody) with HUB_SECRET (network-hub lib/signing.js). Older than 5 minutes = refused. The hub
// only moves its cursor on a 2xx, so events can arrive twice: each seq is applied once (DATA_DIR/hubsync.json lastSeq).
// member.joined from another door: /v1/resolve {id} for the person, then the SAME waiting (shell) account the InstantAdPay
// registry sync makes (/api/partner/registry in server.js): accounts.ensure(email, '', 'carried', 'network'), then only
// EMPTY fields are filled (username, sponsor, wallet last, while carry.hold keeps activation off). The sponsor is placed
// first (up to 25 levels up) so the line exists. A sponsor already set here is never moved: a disagreement is logged.
// wallet.connected: fills an empty wallet here, same as the registry sync. Every other event is acknowledged and ignored.
// OUT accounts.onChange -> touch(email): a persisted outbox (DATA_DIR/hubsync.json) reports LinkSpin's own joins
// (/v1/join, sponsor named by email) and wallet links (/v1/wallet). Never blocks sign-up; failures retry with backoff.
// The InstantAdPay<->LinkSpin sync (iapsync.js, /api/partner/registry) is not touched by any of this.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
let R = null, state = null, timer = null, flushing = false, inbound = Promise.resolve();
const ENABLED = () => /^(1|true|on|yes)$/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 || 'linkspin').trim().toLowerCase();
const on = () => ENABLED() && SECRET().length >= 32 && /^https?:\/\//.test(URL_());
const WINDOW_MS = 5 * 60 * 1000;
const MAX_UP = 25; // how far up a sponsor line is placed for one event (bad data must not hang a request)
const FILE = () => path.join(R.dataDir, 'hubsync.json');
const norm = v => String(v || '').trim().toLowerCase();
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2'); // logs and the admin view never show a full address
function load() {
if (state) return state;
try { state = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { state = null; }
if (!state || typeof state !== 'object') state = {};
state.lastSeq = Number(state.lastSeq) || 0; state.outbox = state.outbox || {}; state.sent = state.sent || {};
state.disagree = state.disagree || {}; state.stats = state.stats || { events: 0, shells: 0, filled: 0, joins: 0, wallets: 0, dropped: 0, errors: 0 };
return state;
}
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
function init(deps) { R = deps; state = null; load(); } // { dataDir, accounts, registry, carry, follow (sponsorfollow store) }
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
async function call(route, body) {
const raw = JSON.stringify(body); const ts = String(Date.now());
let r;
try { r = await fetch(URL_() + route, { 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) }); }
catch (e) { throw new Error('hub ' + route + ' unreachable'); }
let out = null; try { out = await r.json(); } catch (e) {}
if (r.status >= 500 || r.status === 401) throw new Error('hub ' + route + ' ' + r.status); // down, redeploying (503) or misconfigured: try again later
return { status: r.status, body: out || {} };
}
async function resolveId(id) {
if (!id) return null;
const r = await call('/v1/resolve', { id });
return r.status === 200 && r.body.person ? r.body.person : null;
}
const refEmail = async ref => { if (!ref) return null; const a = (await R.accounts.byUsername(ref)) || (await R.accounts.byCode(ref)); return a ? norm(a.email) : null; };
function noteDisagree(e, hubSponsor, here, how) {
load().disagree[e] = { at: Date.now(), hub: hubSponsor || null, here: here || null, how }; save();
console.log('hubsync sponsor differs', how, mask(e));
}
// ---- inbound -------------------------------------------------------------------------------------------------------------
// a hub person gets a LinkSpin account the way an InstantAdPay person does: a waiting shell, empty fields filled, nothing moved
async function place(p, depth, seen) {
const e = norm(p.email); if (!e || p.blocked || seen.has(e)) return null; seen.add(e);
let sp = p.sponsor && p.sponsor.email ? await R.accounts.byEmail(p.sponsor.email) : null;
if (!sp && p.sponsor && p.sponsor.id && depth < MAX_UP) { // the sponsor is new here too: their line first
const up = await resolveId(p.sponsor.id);
if (up && up.email) { await place(up, depth + 1, seen); sp = await R.accounts.byEmail(up.email); }
}
R.carry.hold([e]);
try {
if (!(await R.registry.get(e))) { // a new row only: the registry is what InstantAdPay told us, iapsync's loop guard reads it
try { await R.registry.upsert({ email: e, username: p.username || null, wallet: p.wallet || null, sponsorEmail: sp ? sp.email : null, joinedAt: p.firstDoor && p.firstDoor.at, firstProperty: (p.firstDoor && p.firstDoor.site) || 'network' }); } catch (err) {}
}
let a = await R.accounts.byEmail(e);
if (!a) { const x = await R.accounts.ensure(e, '', 'carried', 'network'); if (x.created) load().stats.shells++; a = await R.accounts.byEmail(e); }
if (!a) return null;
if (p.username && !a.username) { try { const r = await R.accounts.setUsername(e, p.username); if (r && !r.error) load().stats.filled++; } catch (err) {} }
if (sp && norm(sp.email) !== e) {
if (!a.sponsorRef) {
const pv = R.follow && R.follow.get(e); // emptied on purpose here (released / rescued): an ordinary fill does not refill it
const deliberate = pv && pv.by && ['adopt', 'rescue', 'release', 'expiry', 'admin'].includes(pv.by) && !pv.sponsorEmail;
if (!deliberate && (sp.username || sp.code)) { try { await R.accounts.setSponsorRef(e, sp.username || sp.code); load().stats.filled++; } catch (err) {} }
} else {
const here = await refEmail(a.sponsorRef);
if (here !== norm(sp.email)) noteDisagree(e, sp.email, here, 'inbound'); // LinkSpin's line stands; TODO(Marty): who settles these
}
}
if (p.wallet && !a.address) { try { const r = await R.accounts.linkWallet(e, p.wallet); if (r && !r.error) load().stats.filled++; } catch (err) {} }
return a;
} finally { R.carry.unhold([e]); }
}
async function apply(ev) {
const type = String(ev.type || '');
if (type === 'member.joined') {
if (norm(ev.data && ev.data.site) === SITE()) return; // our own join coming back
const p = await resolveId(ev.personId);
if (p && p.email) await place(p, 0, new Set());
} else if (type === 'wallet.connected') { // fill an empty wallet only, same rule as the InstantAdPay registry sync
const p = await resolveId(ev.personId); if (!p || !p.email || !p.wallet || p.blocked) return;
const a = await R.accounts.byEmail(p.email);
if (a && !a.address) { R.carry.hold([a.email]); try { await R.accounts.linkWallet(a.email, p.wallet); } finally { R.carry.unhold([a.email]); } }
}
// TODO(hub): sponsor.changed needs the sponsorfollow.js decision (chain binding, window, provenance); until it is wired, ignored.
// TODO(hub): member.blocked / unblocked, entitlement.changed, wallet.changed and the wallet-change events: ignored for now.
}
function verify(headers, raw) {
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)) > WINDOW_MS) return false;
const want = sign(ts, raw);
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
}
// -> {status, body}. One batch at a time, in seq order; a seq already applied is skipped. A hub that cannot be reached
// answers 503 so the hub sends the batch again; a bad event is counted and passed (it must not stop every later one).
function receive(headers, raw) {
const run = inbound.then(async () => {
if (!on()) return { status: 404, body: { error: 'not_found' } };
if (!verify(headers, raw)) return { status: 401, body: { error: 'unauthorized' } };
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return { status: 400, body: { error: 'bad_json' } }; }
const st = load(); const events = (Array.isArray(b.events) ? b.events : []).slice().sort((x, y) => Number(x.seq) - Number(y.seq));
let applied = 0, skipped = 0;
for (const ev of events) {
const seq = Number(ev && ev.seq) || 0;
if (!seq || seq <= st.lastSeq) { skipped++; continue; }
try { await apply(ev); applied++; st.stats.events++; }
catch (e) {
if (/^hub /.test(e.message)) { save(); return { status: 503, body: { error: 'retry', seq } }; }
st.stats.errors++; st.lastError = { at: Date.now(), seq, error: String(e.message).slice(0, 160) }; console.error('hubsync event', seq, e.message);
}
st.lastSeq = seq; save();
}
return { status: 200, body: { ok: true, applied, skipped, lastSeq: st.lastSeq } };
});
inbound = run.catch(() => {});
return run;
}
// ---- outbound ------------------------------------------------------------------------------------------------------------
function touch(email) {
if (!on() || !email) return;
const e = norm(email); const st = load();
if (!st.outbox[e]) { st.outbox[e] = { at: Date.now(), tries: 0, next: 0 }; save(); }
if (!timer) timer = setTimeout(() => { timer = null; flush().catch(err => console.error('hubsync flush', err.message)); }, 3000);
}
async function report(e) {
const a = await R.accounts.byEmail(e); if (!a) return;
const st = load(); const s = st.sent[e] || {};
if (a.joinedVia !== 'carried') { // a waiting copy of someone from another door: that door reports them
const sp = a.sponsorRef ? await R.accounts.sponsorOf(e) : null;
const ref = sp ? norm(sp.email) : (a.sponsorRef || null);
const key = (a.username || '') + '|' + (ref || '');
if (s.j !== key) {
const r = await call('/v1/join', { email: e, ref: ref || undefined, username: a.username || undefined });
if (r.status === 200) {
st.stats.joins++;
const hubSp = r.body.person && r.body.person.sponsor ? norm(r.body.person.sponsor.email) : null;
if (sp && hubSp && hubSp !== norm(sp.email)) noteDisagree(e, hubSp, sp.email, 'join'); // TODO(Marty): hub says earliest join elsewhere
} else { st.stats.dropped++; console.log('hubsync join refused', r.status, r.body.error || '', mask(e)); }
s.j = key;
}
}
const w = norm(a.address);
if (w && s.w !== w) {
const r = await call('/v1/wallet', { email: e, wallet: w });
if (r.status === 200) st.stats.wallets++;
else { // 404: a waiting copy the hub has not heard of (its own door reports it); 409: the hub holds another wallet
st.stats.dropped++; console.log('hubsync wallet refused', r.status, r.body.error || '', mask(e)); }
s.w = w;
}
st.sent[e] = s;
}
async function flush() {
if (!on() || flushing) return { skipped: true };
flushing = true; let done = 0, failed = 0;
try {
const st = load(); const now = Date.now();
for (const [e, o] of Object.entries(st.outbox)) {
if (o.next > now) continue;
try { await report(e); delete st.outbox[e]; done++; }
catch (err) { o.tries++; o.next = Date.now() + Math.min(3600000, 30000 * 2 ** Math.min(o.tries, 7)); o.error = String(err.message).slice(0, 120); failed++; st.stats.errors++; }
save();
}
} finally { flushing = false; }
return { done, failed };
}
const tick = () => flush();
function adminView() {
const st = load();
return { on: on(), url: URL_(), site: SITE(), lastSeq: st.lastSeq, outbox: Object.keys(st.outbox).length, stats: st.stats, lastError: st.lastError || null,
disagree: Object.entries(st.disagree).slice(-50).map(([e, d]) => ({ member: mask(e), hub: mask(d.hub), here: mask(d.here), how: d.how, at: d.at })), disagreeTotal: Object.keys(st.disagree).length };
}
module.exports = { init, on, receive, touch, flush, tick, adminView };
+131
View File
@@ -0,0 +1,131 @@
// hubsync.js against a real network hub (2026-11-12): the hub runs in this process in JSON mode on a temp DATA_DIR and posts
// its events to a local copy of LinkSpin's /api/hub/events route; LinkSpin's accounts + registry are the JSON stores in
// another temp folder. Synthetic people only. HUB_DIR=<network-hub checkout> node qa/hubsync.test.cjs
'use strict';
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const http = require('http');
const crypto = require('crypto');
const HUB_DIR = process.env.HUB_DIR || [path.join(__dirname, '..', '..', 'network-hub'), path.join(__dirname, '..', '..', '..', 'network-hub')].find(d => fs.existsSync(path.join(d, 'server.js')));
const LS_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-hub-')); const HUB_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hub-data-'));
const LS_SECRET = 'l'.repeat(40), CTB_SECRET = 'c'.repeat(40);
delete process.env.DATABASE_URL; delete process.env.HUB_ENABLED;
const accounts = require(path.join(__dirname, '..', 'accounts.js'));
const registry = require(path.join(__dirname, '..', 'registry.js'));
const carry = require(path.join(__dirname, '..', 'carry.js'));
const hubsync = require(path.join(__dirname, '..', 'hubsync.js'));
accounts.init({ dataDir: LS_DIR }); registry.init({ dataDir: LS_DIR });
hubsync.init({ dataDir: LS_DIR, accounts, registry, carry, follow: null });
accounts.onChange(e => hubsync.touch(e));
const E = n => n + '@example.test';
const W = n => '0x' + String(n).padStart(40, '0');
(async () => {
// LinkSpin's route, exactly as server.js wires it
const ls = http.createServer((req, res) => {
let d = ''; req.on('data', c => { d += c; }); req.on('end', async () => {
if (req.url !== '/api/hub/events' || !hubsync.on()) { res.writeHead(404); return res.end('{}'); }
const r = await hubsync.receive(req.headers, d); res.writeHead(r.status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(r.body));
});
});
await new Promise(r => ls.listen(0, r)); const lsPort = ls.address().port;
// 1. flag off: nothing is queued, the route answers 404, no state file is written
hubsync.touch(E('nobody'));
assert.strictEqual(hubsync.on(), false);
assert.strictEqual((await hubsync.receive({}, '{"events":[]}')).status, 404);
assert.strictEqual(hubsync.adminView().outbox, 0, 'nothing queued while off');
assert.ok(!fs.existsSync(path.join(LS_DIR, 'hubsync.json')), 'no state written while off');
// the hub, JSON mode, with LinkSpin's hook pointed at the local route
process.env.DATA_DIR = HUB_DATA; process.env.HUB_ADMIN_SECRET = 'a'.repeat(40);
process.env.HUB_SITES = JSON.stringify({ linkspin: { secret: LS_SECRET, hook: `http://127.0.0.1:${lsPort}/api/hub/events`, seeEmails: true }, ctb: { secret: CTB_SECRET, seeEmails: true } });
const { start } = require(path.join(HUB_DIR, 'server.js'));
const hooks = require(path.join(HUB_DIR, 'lib', 'hooks.js')); const hstore = require(path.join(HUB_DIR, 'lib', 'store.js')); const { sign } = require(path.join(HUB_DIR, 'lib', 'signing.js'));
const hub = await start(0); const hubPort = hub.address().port;
const ctb = async (route, body) => { const raw = JSON.stringify(body); const ts = String(Date.now()); const r = await fetch(`http://127.0.0.1:${hubPort}${route}`, { method: 'POST', body: raw, headers: { 'X-Hub-Site': 'ctb', 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(CTB_SECRET, ts, raw) } }); return r.json(); };
process.env.HUB_ENABLED = '1'; process.env.HUB_URL = `http://127.0.0.1:${hubPort}`; process.env.HUB_SECRET = LS_SECRET;
assert.strictEqual(hubsync.on(), true);
const lastSeq = () => hstore.eventsAfter(0, 1e6).slice(-1)[0].seq;
try {
// 2. signature: a bad signature and a stale timestamp are refused
const raw = '{"events":[]}'; const ts = String(Date.now());
const hmac = (t, b) => crypto.createHmac('sha256', LS_SECRET).update(t + '\n' + b).digest('hex');
assert.strictEqual((await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': hmac(ts, raw + ' ') }, raw)).status, 401, 'bad signature');
const old = String(Date.now() - 6 * 60000);
assert.strictEqual((await hubsync.receive({ 'x-hub-ts': old, 'x-hub-sig': hmac(old, raw) }, raw)).status, 401, 'older than 5 minutes');
assert.strictEqual((await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': hmac(ts, raw) }, raw)).status, 200);
// 3. CTB joins become waiting LinkSpin accounts under the hub sponsor
await ctb('/v1/join', { email: E('ann'), username: 'ann' });
await ctb('/v1/join', { email: E('bob'), username: 'bobby', ref: 'ann' });
await hooks.tick();
const ann = await accounts.byEmail(E('ann')), bob = await accounts.byEmail(E('bob'));
assert.ok(ann && bob, 'shells created');
assert.strictEqual(bob.joinedVia, 'carried'); assert.strictEqual(bob.joinedRef, 'network');
assert.strictEqual(bob.username, 'bobby'); assert.strictEqual((await accounts.sponsorOf(E('bob'))).email, E('ann'));
assert.strictEqual((await registry.get(E('bob'))).firstProperty, 'ctb');
assert.strictEqual(hubsync.adminView().stats.shells, 2);
// 4. the same events delivered twice change nothing
const before = JSON.stringify(await accounts.listAll(100)); const evs = hubsync.adminView().stats.events;
hstore.setCursor('linkspin', 0); await hstore.flush(); await hooks.tick();
assert.strictEqual(JSON.stringify(await accounts.listAll(100)), before, 'duplicate delivery is a no-op');
assert.strictEqual(hubsync.adminView().stats.events, evs, 'seqs already applied are skipped');
// 5. a sponsor new to LinkSpin is placed first, from the hub, even when only the member's event arrives
await ctb('/v1/join', { email: E('dave'), username: 'dave' }); const daveSeq = lastSeq();
await ctb('/v1/join', { email: E('erin'), username: 'erin', ref: 'dave' });
hstore.setCursor('linkspin', daveSeq); await hstore.flush(); await hooks.tick();
assert.ok(await accounts.byEmail(E('dave')), 'sponsor placed first');
assert.strictEqual((await accounts.sponsorOf(E('erin'))).email, E('dave'));
// 6. wallet.connected fills an empty wallet
await ctb('/v1/wallet', { email: E('bob'), wallet: W(7) }); await hooks.tick();
assert.strictEqual((await accounts.byEmail(E('bob'))).address, W(7));
// 7. LinkSpin's own sign-up and wallet reach the hub, sponsor named by email
await accounts.ensure(E('zed'), 'ann', '', null); await accounts.setUsername(E('zed'), 'zed');
await hubsync.flush();
let hz = await ctb('/v1/resolve', { email: E('zed') });
assert.strictEqual(hz.person.sponsor.email, E('ann')); assert.strictEqual(hz.person.firstDoor.site, 'linkspin'); assert.strictEqual(hz.person.username, 'zed');
await accounts.linkWallet(E('zed'), W(9)); await hubsync.flush();
hz = await ctb('/v1/resolve', { email: E('zed') }); assert.strictEqual(hz.person.wallet, W(9));
const zedBefore = JSON.stringify(await accounts.byEmail(E('zed')));
await hooks.tick(); // our own join and wallet come back from the hub: nothing changes here
assert.strictEqual(JSON.stringify(await accounts.byEmail(E('zed'))), zedBefore);
assert.strictEqual(hubsync.adminView().stats.shells, 4, 'no shell made for our own member');
// 8. hub and LinkSpin disagree: the earlier CTB join under ann is the hub's answer, LinkSpin's own line stands, it is logged
await ctb('/v1/join', { email: E('pat'), ref: 'ann' });
await accounts.ensure(E('pat'), 'zed', '', null); await hubsync.flush();
assert.strictEqual((await accounts.sponsorOf(E('pat'))).email, E('zed'), 'LinkSpin line not moved');
assert.strictEqual((await ctb('/v1/resolve', { email: E('pat') })).person.sponsor.email, E('ann'), 'hub keeps the earliest join');
const dv = hubsync.adminView(); assert.strictEqual(dv.disagreeTotal, 1); assert.ok(!JSON.stringify(dv.disagree).includes(E('pat')), 'admin view masks emails');
await hooks.tick(); assert.strictEqual((await accounts.sponsorOf(E('pat'))).email, E('zed'));
// 9. hub down: the join waits in the persisted outbox and goes once the hub is back
process.env.HUB_URL = 'http://127.0.0.1:1';
await accounts.ensure(E('quinn'), 'ann', '', null); await hubsync.flush();
assert.strictEqual(hubsync.adminView().outbox, 1, 'kept for retry');
assert.ok(JSON.parse(fs.readFileSync(path.join(LS_DIR, 'hubsync.json'), 'utf8')).outbox[E('quinn')], 'outbox persisted');
process.env.HUB_URL = `http://127.0.0.1:${hubPort}`;
const st = JSON.parse(fs.readFileSync(path.join(LS_DIR, 'hubsync.json'), 'utf8')); st.outbox[E('quinn')].next = 0; fs.writeFileSync(path.join(LS_DIR, 'hubsync.json'), JSON.stringify(st));
hubsync.init({ dataDir: LS_DIR, accounts, registry, carry, follow: null }); // reload from disk, as after a restart
await hubsync.flush();
assert.strictEqual(hubsync.adminView().outbox, 0);
assert.strictEqual((await ctb('/v1/resolve', { email: E('quinn') })).person.firstDoor.site, 'linkspin');
// 10. hub unreachable while LinkSpin is receiving: 503 so the hub sends again, nothing skipped
await hooks.tick(); await ctb('/v1/join', { email: E('rose') });
process.env.HUB_URL = 'http://127.0.0.1:1'; const seqNow = hubsync.adminView().lastSeq;
await hooks.tick(); assert.strictEqual(hubsync.adminView().lastSeq, seqNow, 'not advanced while the hub cannot be asked');
process.env.HUB_URL = `http://127.0.0.1:${hubPort}`; await hooks.tick();
assert.ok(await accounts.byEmail(E('rose')), 'arrived on the retry');
console.log('hubsync: ok (10 checks)');
} finally { hub.close(); ls.close(); }
process.exit(0);
})().catch(e => { console.error('hubsync: FAIL', e.stack || e.message); process.exit(1); });
+2
View File
@@ -81,6 +81,8 @@ elif [ "$MODE" = "sponsorfollow" ]; then
node qa/sponsorfollow.test.cjs || status=1
node qa/carry-hold.test.cjs || status=1
node qa/carry-activate.test.cjs || status=1
elif [ "$MODE" = "hubsync" ]; then
node qa/hubsync.test.cjs || status=1 # needs a network-hub checkout with /v1/resolve {id}: HUB_DIR=<path>
elif [ "$MODE" = "tankhold" ]; then
node qa/tank-hold.test.mjs || status=1
elif [ "$MODE" = "nas" ]; then
+8 -1
View File
@@ -45,6 +45,7 @@ const leaderboard = require('./leaderboard');
const toolkit = require('./toolkit');
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15)
const hubsync = require('./hubsync'); // network hub link, inert unless HUB_ENABLED=1 (2026-11-12)
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to InstantAdPay until chain-bound + one network tank (2026-10-22)
let follow = null, followStore = null;
const IAP_BASE = () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
@@ -730,7 +731,8 @@ async function boot() {
// member numbers for accounts the engine activated before 2026-10-18 (the ledger names people by them); 60 s after boot so a deploy's old copy is gone
setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000);
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => iapsync.touch(email));
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => { iapsync.touch(email); hubsync.touch(email); });
hubsync.init({ dataDir: DATA_DIR, accounts, registry, carry, follow: followStore }); setInterval(() => hubsync.tick().catch(e => console.error('hubsync', e.message)), 30 * 1000); // touch/tick do nothing while HUB_ENABLED is off
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
@@ -2996,6 +2998,11 @@ const server = http.createServer(async (req, res) => {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); return json(res, 200, await carry.seedAll(Number(b.limit) || 0));
}
if (p === '/api/hub/events' && req.method === 'POST' && hubsync.on()) { // network hub events (hubsync.js); with HUB_ENABLED off this route does not exist
const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > 2e6) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); });
const r = await hubsync.receive(req.headers, raw); return json(res, r.status, r.body);
}
if (p === '/api/admin/hubsync' && req.method === 'GET' && hubsync.on()) { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, hubsync.adminView()); }
// -- live registry sync from InstantAdPay (2026-10-08): signed rows (HMAC LS_SYNC_SECRET over ts + newline + raw body),
// upserted into the registry; new people become shell accounts with their line, existing shells pick up a username,
// wallet or sponsor they did not have. Only the posted rows are touched.