// 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= 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; // 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 over https, Telegram and Sendy 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); }; } 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)); // the wallet hook as server.js wires it: the engine would switch payouts on (gas, a lock, the "payouts are switched on" mail) const activations = []; accounts.onWalletLinked(async email => { if (hubsync.isQuiet(email)) return; activations.push(email); }); 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, 'hub'); // quiet (2026-11-14): hub-made accounts that never signed in are out of every default list (mailings, sweeps), in with { shells: true } assert.ok(!(await accounts.listAll(1000)).some(a => a.email === E('bob')), 'hub shell left out of default lists'); assert.ok((await accounts.listAll(1000, { shells: true })).some(a => a.email === E('bob')), 'hub shell listed with shells: true'); 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'); // 11. rule 2 (2026-11-14): a LinkSpin activation alone does not decide against a contract with money spent; a paid // LinkSpin Purchase is reported once (tx) and only after its bind const per = e => hstore.byEmailKey(e); await ctb('/v1/join', { email: E('ptw'), username: 'ptw' }); await ctb('/v1/wallet', { email: E('ptw'), wallet: W(91) }); await ctb('/v1/join', { email: E('sil'), username: 'sil' }); await ctb('/v1/wallet', { email: E('sil'), wallet: W(92) }); await ctb('/v1/join', { email: E('tur'), ref: 'ptw', username: 'tur' }); await ctb('/v1/contract-bind', { contract: 'iap', email: E('tur'), wallet: W(93), sponsorRef: W(91), spentCents: 3500 }); const members = { 7: { account: W(92) }, 8: { account: W(93) } }; hubsync.init({ dataDir: LS_DIR, accounts, registry, carry, follow: null, chain: { member: async id => members[id] || null } }); hubsync.onChain({ type: 'MemberActivated', id: 8, account: W(93), sponsorId: 7 }); hubsync.onChain({ type: 'Purchase', buyerId: 8, priceCents: 1000, paidWei: '5', tx: '0xls1', ts: Date.now() + 60000 }); hubsync.onChain({ type: 'Purchase', buyerId: 8, priceCents: 1000, paidWei: '5', tx: '0xls1', ts: Date.now() + 60000 }); await new Promise(r => setTimeout(r, 50)); await hubsync.flush(); const tur = per(E('tur')); assert.strictEqual(tur.bindings.linkspin.sponsorId, per(E('sil')).id, 'LinkSpin lock under its own sponsor'); assert.strictEqual(tur.bindings.linkspin.spentCents, 1000, 'one purchase counted once'); assert.strictEqual(tur.sponsorId, per(E('ptw')).id, 'the earlier spend (InstantAdPay) still decides'); assert.strictEqual(hubsync.adminView().stats.spends, 1); // 12. rule 2 on arrival (2026-11-14): someone the LinkSpin contract holds arrives under THAT lock's sponsor, not the network // sponsor (another contract where money was spent); a later sponsor.changed never moves them const HP = require(path.join(HUB_DIR, 'lib', 'people.js')); await ctb('/v1/join', { email: E('lx'), username: 'lockx' }); await ctb('/v1/join', { email: E('ly'), username: 'locky' }); await ctb('/v1/join', { email: E('lk'), username: 'lockkid', ref: 'locky' }); HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: E('lk'), wallet: W(81), sponsorRef: 'lockx', at: 1000 }); HP.bindContract({ site: 'iap', contract: 'iap', email: E('lk'), wallet: W(81), sponsorRef: 'locky', at: 2000, spentCents: 2500 }); await hstore.flush(); assert.strictEqual(per(E('lk')).sponsorId, per(E('ly')).id, 'network sponsor = InstantAdPay (money spent there)'); await hooks.tick(); assert.strictEqual((await accounts.sponsorOf(E('lk'))).email, E('lx'), 'the LinkSpin lock sponsor is written here'); const lkSeq = lastSeq() + 1000; const evRaw = JSON.stringify({ events: [{ seq: lkSeq, type: 'sponsor.changed', personId: per(E('lk')).id, data: { by: 'contract', contract: 'iap' } }] }); const evTs = String(Date.now()); assert.strictEqual((await hubsync.receive({ 'x-hub-ts': evTs, 'x-hub-sig': crypto.createHmac('sha256', LS_SECRET).update(evTs + '\n' + evRaw).digest('hex') }, evRaw)).status, 200); assert.strictEqual((await accounts.sponsorOf(E('lk'))).email, E('lx'), 'sponsor.changed is ignored'); hstore.setCursor('linkspin', lastSeq()); await hstore.flush(); // the test event above moved lastSeq past the hub's numbering const st0 = JSON.parse(fs.readFileSync(path.join(LS_DIR, 'hubsync.json'), 'utf8')); st0.lastSeq = lastSeq(); fs.writeFileSync(path.join(LS_DIR, 'hubsync.json'), JSON.stringify(st0)); hubsync.init({ dataDir: LS_DIR, accounts, registry, carry, follow: null }); // 13. rule 3: the tank never offers anyone locked on any network contract, sponsored in the hub, or a hub waiting copy that // never signed in here; release refuses a locked member. Tank as server.js wires it, mailer and messages only record. const tank = require(path.join(__dirname, '..', '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() }; tank.init({ dataDir: LS_DIR, accounts, chain: { recentEvents: () => [], memberIdByAccount: async () => 0 }, messages, mailer, hooks: { network: async e => hubsync.hubSponsor(e), networkHeld: a => hubsync.heldAmong(a), networkLocked: e => hubsync.lockedAnywhere(e) } }); await ctb('/v1/join', { email: E('hs') }); await hooks.tick(); // a CTB join with no sponsor anywhere: a waiting copy here assert.ok(await accounts.byEmail(E('hs')), 'waiting copy made'); await ctb('/v1/join', { email: E('tk1'), username: 'tk1ctb', ref: 'ann' }); // the hub knows a sponsor for (const n of ['tk1', 'tk2', 'tk3']) assert.ok((await accounts.ensure(E(n), '', '', null)).created); // signed up here, no sponsor await hubsync.flush(); HP.bindContract({ site: 'iap', contract: 'iap', email: E('tk2'), wallet: W(82), sponsorRef: '' }); await hstore.flush(); // locked, top of that tree hubsync._heldReset(); const held = await hubsync.heldAmong(await Promise.all(['tk1', 'tk2', 'tk3', 'hs'].map(n => accounts.byEmail(E(n))))); assert.deepStrictEqual([...held.entries()].sort(), [[E('hs'), 'hub-shell'], [E('tk1'), 'sponsored'], [E('tk2'), 'locked']]); let w = (await tank.waiting()).map(x => x.email); assert.ok(w.includes(E('tk3')), 'a free member is offered'); for (const n of ['tk1', 'tk2', 'hs']) assert.ok(!w.includes(E(n)), n + ' is not offered: ' + w.join(',')); await accounts.setSponsorRef(E('tk2'), 'zed'); const rel = await tank.release(E('zed'), E('tk2')); assert.ok(rel.error && /locked/.test(rel.error), JSON.stringify(rel)); assert.strictEqual((await accounts.sponsorOf(E('tk2'))).email, E('zed')); await tank.readyTick(); assert.strictEqual((await accounts.byEmail(E('tk1'))).sponsorRef || '', '', 'alignment from the hub is off by default'); process.env.HUB_TANK_ALIGN = 'on'; await tank.readyTick(); delete process.env.HUB_TANK_ALIGN; // aligns tk1 to the sponsor the hub knows, and leaves the waiting copy alone assert.strictEqual((await accounts.sponsorOf(E('tk1'))).email, E('ann'), 'aligned to the hub sponsor'); assert.strictEqual((await accounts.byEmail(E('hs'))).sponsorRef || '', '', 'the waiting copy is not touched'); // 14. fail-safe: hub unreachable past the 1-hour cache = held; within the hour the last answer stands; back = offered again process.env.HUB_URL = 'http://127.0.0.1:1'; hubsync._heldAge(30 * 60000); assert.ok((await tank.waiting()).map(x => x.email).includes(E('tk3')), 'within the hour'); hubsync._heldReset(); assert.ok(!(await tank.waiting()).map(x => x.email).includes(E('tk3')), 'unknown = held'); assert.strictEqual(await hubsync.lockedAnywhere(E('tk3')), 'unknown'); process.env.HUB_URL = `http://127.0.0.1:${hubPort}`; hubsync._heldReset(); assert.ok((await tank.waiting()).map(x => x.email).includes(E('tk3'))); // 15. mail audit: hub arrivals with wallets (new, sponsor climbed first, an empty wallet filled later) switch nothing on and // send no mail, chat, notice or outside call; neither do the tank ticks afterwards sent.length = 0; outside.length = 0; activations.length = 0; await ctb('/v1/join', { email: E('ma'), username: 'mailtop' }); await ctb('/v1/wallet', { email: E('ma'), wallet: W(83) }); await ctb('/v1/join', { email: E('mb'), username: 'mailkid', ref: 'mailtop' }); await ctb('/v1/wallet', { email: E('mb'), wallet: W(84) }); await ctb('/v1/join', { email: E('mc'), username: 'mailfill' }); const mbEv = hstore.eventsAfter(0, 1e6).find(e => e.type === 'member.joined' && e.personId === per(E('mb')).id); hstore.setCursor('linkspin', mbEv.seq - 1); await hstore.flush(); // the kid's join first: the sponsor is placed from the hub await hooks.tick(); await ctb('/v1/wallet', { email: E('mc'), wallet: W(85) }); await hooks.tick(); // wallet.connected on a waiting copy assert.strictEqual((await accounts.byEmail(E('mb'))).address, W(84)); assert.strictEqual((await accounts.byEmail(E('mc'))).address, W(85)); assert.strictEqual((await accounts.sponsorOf(E('mb'))).email, E('ma')); await hubsync.flush(); await tank.readyTick(); await tank.sweep(); assert.deepStrictEqual(activations, [], 'no payouts switch-on for wallets filled from the hub'); assert.deepStrictEqual(sent, [], 'nothing sent'); assert.deepStrictEqual(outside, [], 'no outside call'); 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 accounts.linkWallet(E('tk3'), W(86)); assert.deepStrictEqual(activations, [E('tk3')], 'a wallet linked here still switches payouts on'); console.log('hubsync: ok (15 checks)'); } finally { hub.close(); ls.close(); } process.exit(0); })().catch(e => { console.error('hubsync: FAIL', e.stack || e.message); process.exit(1); });