// 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; 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'); // 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); console.log('hubsync: ok (11 checks)'); } finally { hub.close(); ls.close(); } process.exit(0); })().catch(e => { console.error('hubsync: FAIL', e.stack || e.message); process.exit(1); });