Network hub listener (hubsync.js), off unless HUB_ENABLED

POST /api/hub/events: signed hub hooks (HUB_SECRET, 5-minute window), each seq applied once, 503 so the hub retries.
member.joined from another door: /v1/resolve the person (climbing to sponsors not here yet) and make waiting accounts
through lsinbound.receive (joinedVia 'hub', joinedRef 'hub:<door>'); existing accounts keep their sponsor and the
difference is listed in /api/admin/hub. wallet.connected fills waiting accounts only; sponsor.changed is a TODO.
Our own new accounts and wallet links go to /v1/join and /v1/wallet from a persisted outbox (hubsync.json), never
in the way of a sign-up. With the flag off nothing is initialised, wired, routed or written; the LinkSpin sync is
unchanged. Test: qa/hubsync.test.cjs against a local network-hub (needs /v1/resolve by id, branch hub-resolve-id).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-12 17:02:45 -06:00
parent 74354346a3
commit 5c896cb782
6 changed files with 465 additions and 6 deletions
+2 -1
View File
@@ -484,7 +484,8 @@ async function count() { return impl().count(); }
// It exists so the LinkSpin line is already in place; it is not a member yet, so the sweeps that mail, count or adopt
// members (listAll by default) leave it out. It becomes an ordinary account the first time its owner signs in (lastSeen).
// BTC4Hits members imported 2026-11-11 (btc4hits-migration, joinedVia 'btc4hits') are the same kind of waiting account.
const SHELL_VIAS = new Set(['linkspin', 'btc4hits']);
// Network hub members who joined at another door (hubsync.js, 2026-11-12, only while HUB_ENABLED) arrive as joinedVia 'hub'.
const SHELL_VIAS = new Set(['linkspin', 'btc4hits', 'hub']);
const isUnclaimedShell = a => !!a && SHELL_VIAS.has(a.joinedVia) && !a.lastSeen && !a.memberId;
// the limit counts members, not waiting accounts: newest-first LIMIT before the filter let thousands of waiting accounts push
// older real members out of the sweeps that read listAll(5000) (tank, coach, leaderboard, Friday, Wednesday)
+240
View File
@@ -0,0 +1,240 @@
// Network hub sync (2026-11-12, Marty 2026-11-06: one membership from any door; the hub is the single identity).
// Everything here sleeps unless HUB_ENABLED is on: server.js does not even init this module without it, so no file is
// written, no route answers and no hook is wired. The InstantAdPay <-> LinkSpin direct sync (lssync.js / lsinbound.js)
// keeps running exactly as before either way.
//
// Inbound (POST /api/hub/events, signed by the hub with HUB_SECRET: X-Hub-Ts + X-Hub-Sig = hex HMAC-SHA256(ts + newline +
// raw body), 5-minute window). The hub only moves its cursor after a 2xx and may send an event twice:
// member.joined someone joined at another door: /v1/resolve the person (and, climbing, any sponsor not here yet) and
// hand the rows to lsinbound.receive, the same waiting-account path LinkSpin-first members take, with
// joinedVia 'hub' and joinedRef 'hub:<door>'. First-platform rule as there: an account that already
// exists here keeps its sponsor and only gets empty fields filled. Joins from this site are skipped.
// wallet.connected filled only on a waiting account that still has no wallet (lsinbound fill rules). A claimed account
// links its own wallet here; the hub's wallet is not proof of ownership on InstantAdPay.
// sponsor.changed 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).
// anything else ignored.
// Each seq is applied once (done map). A failing event answers 503 so the hub retries it; after 5 tries it is set aside
// in the log so one bad row cannot hold every later event back.
//
// Outbound (/v1/join, /v1/wallet, signed as HUB_SITE): new accounts made here since the flag first went on and every main
// wallet linked here go into a persisted outbox (DATA_DIR/hubsync.json) and are sent in order, never in the way of a
// sign-up. Retried with backoff on 5xx / network / 404-before-join; a 400/409 refusal is final and logged.
// Where the hub and InstantAdPay name different sponsors, nothing is forced on either side: the case goes to `disagree`
// (Admin > /api/admin/hub) for Marty, since an InstantAdPay member bound on our contract cannot move anyway.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
let R = null, st = null, chain_ = Promise.resolve(), timer = null, sending = false, interval = null;
const MAX_UP = 25, EVENT_TRIES = 5, OUT_TRIES = 20, KEEP_DONE = 5000;
const SHELL_ORIGINS = new Set(['linkspin', 'btc4hits', 'hub']); // came here from another site: that site tells the hub itself
const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim());
const URL_ = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
const SITE = () => String(process.env.HUB_SITE || 'iap').trim().toLowerCase();
const on = () => enabled() && !!URL_() && SECRET().length >= 32;
const norm = v => String(v || '').trim().toLowerCase();
const FILE = () => path.join(R.dataDir, 'hubsync.json');
function load() {
if (st) return st;
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
if (!st || typeof st !== 'object') st = {};
st.since = Number(st.since) || Date.now(); // only accounts made after the flag first went on are reported as joins
st.done = st.done || {}; st.tries = st.tries || {}; st.outbox = st.outbox || []; st.reported = st.reported || {};
st.disagree = st.disagree || {}; st.log = st.log || [];
st.stats = Object.assign({ batches: 0, events: 0, applied: 0, skipped: 0, ignored: 0, gaveUp: 0, sent: 0, refused: 0, sendErrors: 0 }, st.stats || {});
return st;
}
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('hubsync save', e.message); } }
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
// deps: { dataDir, accounts, lsinbound }
function init(deps) { R = deps; load(); save(); }
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
function verify(headers, raw) {
if (SECRET().length < 32) return false;
const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || '');
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return false;
const want = sign(ts, raw);
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
}
async function hubPost(p, body) {
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) });
let j = null; try { j = await r.json(); } catch (e) {}
return { status: r.status, body: j };
}
async function resolve(q) {
const r = await hubPost('/v1/resolve', q);
if (r.status !== 200) throw new Error('hub resolve ' + r.status);
return (r.body && r.body.person) || null;
}
const doorOf = p => norm(p && p.firstDoor && p.firstDoor.site).replace(/[^a-z0-9_-]/g, '').slice(0, 30) || 'network';
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 });
// what InstantAdPay and the hub each say the sponsor is; a difference is recorded, never forced
async function compare(email, hubSponsorEmail, how) {
const sp = await R.accounts.sponsorOf(email); const here = sp ? norm(sp.email) : null; const there = norm(hubSponsorEmail) || null;
const s = load();
if (here === there) { delete s.disagree[email]; return; }
s.disagree[email] = { at: Date.now(), iap: here, hub: there, how };
}
async function memberJoined(ev) {
if (norm(ev.data && ev.data.site) === SITE()) return 'own';
const first = await resolve({ id: ev.personId });
if (!first || !first.email) return first ? 'no-email' : 'unknown'; // the hub must give this site seeEmails
if (first.blocked) return 'blocked';
const email = norm(first.email); const A = R.accounts;
const existing = await A.byEmail(email);
const rows = [rowOf(first)]; const doors = { [email]: doorOf(first) }; const seen = new Set([email]);
if (existing && !A.isUnclaimedShell(existing)) rows[0].wallet = null; // a real account links its own wallet here
// sponsors not on InstantAdPay yet come along as waiting accounts too (lsinbound builds them from rows in the same batch)
let p = first;
for (let i = 0; i < MAX_UP && p.sponsor && p.sponsor.email; i++) {
const se = norm(p.sponsor.email); if (seen.has(se) || await A.byEmail(se)) break;
const up = await resolve({ email: se }); if (!up || !up.email || up.blocked) break;
seen.add(se); rows.push(rowOf(up)); doors[se] = doorOf(up); p = up;
}
const sum = await R.lsinbound.receive(rows, { via: 'hub', refOf: e => 'hub:' + (doors[e] || 'network') });
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
await compare(email, rows[0].sponsorEmail, 'hub-join');
note({ type: 'joined', email, door: doors[email], created: sum ? sum.created : 0, existed: !!existing });
return 'applied';
}
async function walletConnected(ev) {
const p = await resolve({ id: ev.personId });
if (!p || !p.email || !p.wallet || p.blocked) return 'skip';
const a = await R.accounts.byEmail(p.email);
if (!a) return 'not-here'; // member.joined makes the account; a wallet alone does not
if (!R.accounts.isUnclaimedShell(a) || a.address) return 'kept'; // claimed accounts link their own wallet here
const sum = await R.lsinbound.receive([rowOf(p)], { via: 'hub', refOf: () => 'hub:' + doorOf(p) });
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
return 'applied';
}
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.
return 'ignored';
}
function prune() {
const s = load(); const seqs = Object.keys(s.done).map(Number).sort((a, b) => a - b);
for (const q of seqs.slice(0, Math.max(0, seqs.length - KEEP_DONE))) delete s.done[q];
}
async function handle(events) {
const s = load(); s.stats.batches++; let failed = null;
for (const ev of Array.isArray(events) ? events : []) {
const seq = Number(ev && ev.seq); if (!seq) continue;
if (s.done[seq]) { s.stats.skipped++; continue; } // delivered twice: already applied
s.stats.events++;
try {
const r = await apply(ev);
s.done[seq] = Date.now(); delete s.tries[seq];
if (r === 'applied') s.stats.applied++; else s.stats.ignored++;
} catch (e) {
s.tries[seq] = (s.tries[seq] || 0) + 1;
console.error('hubsync event', seq, ev.type, e.message);
if (s.tries[seq] >= EVENT_TRIES) { s.done[seq] = Date.now(); delete s.tries[seq]; s.stats.gaveUp++; note({ type: 'gave-up', seq, event: ev.type, error: String(e.message).slice(0, 160) }); continue; }
failed = e; break; // answer 503: the hub sends this one (and everything after it) again
}
}
prune(); save();
return failed ? { status: 503, body: { error: 'retry' } } : { status: 200, body: { ok: true } };
}
// the POST /api/hub/events handler: { status, body }. Batches run one at a time.
function receive(headers, raw) {
if (!R || !enabled()) return Promise.resolve({ status: 404, body: { error: 'not found' } });
if (!verify(headers, raw)) return Promise.resolve({ status: 401, body: { error: 'unauthorized' } });
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return Promise.resolve({ status: 400, body: { error: 'bad json' } }); }
const run = chain_.then(() => handle(b.events)); chain_ = run.catch(() => {}); return run;
}
// ---------- outbound ----------
function enqueue(kind, email) {
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
s.outbox.push({ kind, email, at: Date.now(), tries: 0, next: 0 }); save(); kick();
}
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(e => console.error('hubsync flush', e.message)); }, 2000); }
// accounts.onChange: a new account made here (or its first username) goes to /v1/join
function touch(email) {
if (!R || !on() || !email) return;
(async () => {
const e = norm(email); const a = await R.accounts.byEmail(e); const s = load();
if (!a || SHELL_ORIGINS.has(a.joinedVia) || Number(a.created) < s.since) return;
const rep = s.reported[e];
if (!rep) { s.reported[e] = { u: a.username || null }; enqueue('join', e); }
else if (a.username && rep.u !== a.username) { rep.u = a.username; enqueue('join', e); } // join again names them on the hub
})().catch(err => console.error('hubsync touch', err.message));
}
// accounts.onWalletLinked: a main wallet linked here goes to /v1/wallet
function wallet(email) {
if (!R || !on() || !email) return;
(async () => {
const a = await R.accounts.byEmail(email);
if (a && a.address && !R.accounts.isUnclaimedShell(a)) enqueue('wallet', norm(email)); // a waiting account's wallet came from a sync
})().catch(err => console.error('hubsync wallet', err.message));
}
async function bodyFor(item) {
const a = await R.accounts.byEmail(item.email); if (!a) return null;
if (item.kind === 'wallet') return a.address ? { email: a.email, wallet: a.address } : null;
const sp = await R.accounts.sponsorOf(a.email);
return { email: a.email, ref: sp ? sp.email : (a.sponsorRef || undefined), username: a.username || undefined };
}
async function flush(force) { // force (tests, admin): ignore the backoff wait
if (!R || !on() || sending) return { skipped: true };
sending = true; const s = load(); const now = Date.now(); const held = new Set(); let sent = 0;
try {
for (const item of s.outbox.slice()) {
if (held.has(item.email)) continue; // keep each member's calls in order (join before wallet)
if (item.next > now && !force) { held.add(item.email); continue; }
const drop = (why, code) => { s.outbox.splice(s.outbox.indexOf(item), 1); if (why) note({ type: 'out-' + why, kind: item.kind, email: item.email, code: code || null }); };
let r = null;
try {
const body = await bodyFor(item); if (!body) { drop('gone'); save(); continue; }
r = await hubPost(item.kind === 'join' ? '/v1/join' : '/v1/wallet', body);
} catch (e) { r = { status: 0, body: { error: e.message } }; }
const code = (r.body && r.body.error) || null;
if (r.status >= 200 && r.status < 300) {
drop(null); s.stats.sent++; sent++;
if (item.kind === 'join' && r.body && r.body.person) await compare(item.email, r.body.person.sponsor && r.body.person.sponsor.email, 'iap-join');
} else if ((r.status === 400 || r.status === 409) || (r.status === 403 && code === 'blocked')) {
drop('refused', code); s.stats.refused++;
} else {
item.tries++; s.stats.sendErrors++;
if (item.tries >= OUT_TRIES) drop('gave-up', code || String(r.status));
else { item.next = now + Math.min(3600000, 30000 * Math.pow(2, item.tries)); held.add(item.email); }
}
save();
}
} finally { sending = false; }
return { sent, waiting: s.outbox.length };
}
// password sign-ups do not fire accounts.onChange until they pick a username: every 10 minutes, any account made here since
// the flag went on that the hub has not heard about yet is queued
async function reconcile() {
if (!R || !on()) return { skipped: true };
const s = load(); let queued = 0;
for (const a of await R.accounts.listAll(1e6)) {
const e = norm(a.email);
if (!e || s.reported[e] || SHELL_ORIGINS.has(a.joinedVia) || Number(a.created) < s.since) continue;
s.reported[e] = { u: a.username || null }; s.outbox.push({ kind: 'join', email: e, at: Date.now(), tries: 0, next: 0 }); queued++;
}
if (queued) { save(); kick(); }
return { queued };
}
function start() {
if (interval) return;
interval = setInterval(() => flush().catch(e => console.error('hubsync flush', e.message)), 30000);
const rec = setInterval(() => reconcile().catch(e => console.error('hubsync reconcile', e.message)), 10 * 60000);
for (const t of [interval, rec]) if (t.unref) t.unref();
}
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() });
}
module.exports = { init, enabled, on, receive, touch, wallet, flush, reconcile, start, adminView, _sign: sign };
+5 -4
View File
@@ -127,7 +127,7 @@ async function place(email, depth, ctx) {
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
if (sp) tok = tokenOf(sp); else { s.pending[email] = r.sponsorEmail; ctx.sum.pendingSponsor++; }
}
const x = await A.ensure(email, tok, 'linkspin', 'linkspin');
const x = await A.ensure(email, tok, ctx.via || 'linkspin', ctx.refOf ? ctx.refOf(email) : 'linkspin'); // hubsync.js passes its own via (2026-11-12)
if (!x || x.error) { conflict(ctx.sum, email, 'create', x && x.error); return null; }
a = x.account;
if (x.created) { ctx.sum.created++; wrote = true; note({ type: 'shell', email, sponsor: tok || null, pending: tok ? null : (r.sponsorEmail || null) }); }
@@ -156,10 +156,10 @@ async function resolvePending(ctx) {
note({ type: 'sponsored', email, sponsor: tokenOf(sp) });
}
}
async function handle(rows) {
async function handle(rows, opts) {
const s = load(); s.stats.batches++;
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
const ctx = { sum, done: new Set() }; const batch = [];
const ctx = { sum, done: new Set(), via: opts && opts.via, refOf: opts && opts.refOf }; const batch = [];
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
try {
@@ -176,7 +176,8 @@ async function handle(rows) {
return Object.assign({ proto: SF.PROTO }, sum); // proto 2: this side understands sponsor follow + network tank facts
}
// batches are applied one at a time (two overlapping posts must not both create the same sponsor shell)
function receive(rows) { const run = chain_.then(() => handle(rows)); chain_ = run.catch(() => {}); return run; }
// opts (hubsync.js only): { via, refOf(email) } names where a new waiting account came from; LinkSpin's posts pass none
function receive(rows, opts) { const run = chain_.then(() => handle(rows, opts)); chain_ = run.catch(() => {}); return run; }
function adminView() {
const s = load();
return Object.assign({}, s.stats, { knownRows: Object.keys(s.rows).length, pendingSponsors: Object.keys(s.pending).length, last: s.last || null, lastError: s.stats.lastError || null, recent: s.log.slice(-25).reverse() });
+204
View File
@@ -0,0 +1,204 @@
// Network hub sync (hubsync.js) against a REAL network-hub started in this process (JSON mode, throwaway DATA_DIR), with
// InstantAdPay's own accounts / lssync / lsinbound in JSON mode on another throwaway dir. Synthetic members only.
// Then the flag-off check: server.js started with and without HUB_ENABLED.
// node qa/hubsync.test.cjs (HUB_DIR = the network-hub checkout; needs /v1/resolve by {id})
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const http = require('http');
const crypto = require('crypto');
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')));
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)));
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-'));
const IAP_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-iap-'));
(async () => {
// InstantAdPay's hook receiver: the same call server.js makes for POST /api/hub/events
let hubsync = null;
const iapSrv = http.createServer((req, res) => {
const chunks = []; req.on('data', c => chunks.push(c)); req.on('end', async () => {
const r = await hubsync.receive(req.headers, Buffer.concat(chunks).toString('utf8'));
res.writeHead(r.status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(r.body));
});
});
const iapPort = await listen(iapSrv);
// the hub: iap gets hooks and sees emails (it needs them to make accounts); ctb is the other door
process.env.DATA_DIR = HUB_DATA;
process.env.HUB_SITES = JSON.stringify({ iap: { secret: IAP_SECRET, hook: 'http://127.0.0.1:' + iapPort + '/api/hub/events', seeEmails: true }, ctb: { secret: CTB_SECRET, seeEmails: true } });
const hubReq = m => require(path.join(HUB_DIR, m));
const hubConfig = hubReq('lib/config'); const hubStore = hubReq('lib/store'); const hooks = hubReq('lib/hooks');
const hubSrv = await hubReq('server').start(0); const hubPort = hubSrv.address().port;
const HUB = 'http://127.0.0.1:' + hubPort;
const deliver = () => hooks.deliver('iap', hubConfig.SITES.iap);
async function ctb(p, body) { // a call from another door
const raw = JSON.stringify(body), ts = String(Date.now());
const r = await fetch(HUB + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': 'ctb', 'X-Hub-Ts': ts, 'X-Hub-Sig': sig(CTB_SECRET, ts, raw) }, body: raw });
return r.json();
}
const hubPerson = email => hubReq('lib/people').byEmail(email);
// InstantAdPay's side, JSON mode
const accounts = require(path.join(ROOT, 'accounts.js')); accounts.init({ dataDir: IAP_DATA });
const lssync = require(path.join(ROOT, 'lssync.js')); const lsinbound = require(path.join(ROOT, 'lsinbound.js'));
lssync.init({ dataDir: IAP_DATA, accounts }); lsinbound.init({ dataDir: IAP_DATA, accounts, lssync });
const old = (await accounts.ensure('old.member@example.test', '', null, null)).account; // made before the flag went on
await accounts.setUsername(old.email, 'oldie');
await new Promise(r => setTimeout(r, 5));
process.env.HUB_ENABLED = '1'; process.env.HUB_URL = HUB; process.env.HUB_SECRET = IAP_SECRET; process.env.HUB_SITE = 'iap';
hubsync = require(path.join(ROOT, 'hubsync.js'));
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound });
accounts.onChange(e => { lssync.touch(e); hubsync.touch(e); }); accounts.onWalletLinked(e => hubsync.wallet(e)); // as server.js wires it
const settle = () => new Promise(r => setTimeout(r, 50));
const signed = (events, secret, ts) => { const raw = JSON.stringify({ events }); ts = ts || String(Date.now()); return { headers: { 'x-hub-ts': ts, 'x-hub-sig': sig(secret || IAP_SECRET, ts, raw) }, raw }; };
await t('hook signature: wrong secret and a stale timestamp are refused, a good one is accepted', async () => {
let s = signed([], 'z'.repeat(40)); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 401);
s = signed([], IAP_SECRET, String(Date.now() - 6 * 60000)); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 401);
s = signed([]); s.headers['x-hub-sig'] = s.headers['x-hub-sig'].replace(/^./, c => c === 'a' ? 'b' : 'a'); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 401);
s = signed([]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200);
});
let ann, bob;
await t('round trip: two CTB joins reach InstantAdPay as waiting accounts, sponsor line kept', async () => {
await ctb('/v1/join', { email: 'ann@example.test', username: 'annctb' });
await ctb('/v1/join', { email: 'bob@example.test', username: 'bobctb', ref: 'annctb' });
assert.strictEqual(await deliver(), 2);
ann = await accounts.byEmail('ann@example.test'); bob = await accounts.byEmail('bob@example.test');
assert.ok(ann && bob, 'both accounts exist');
assert.strictEqual(bob.joinedVia, 'hub'); assert.strictEqual(bob.joinedRef, 'hub:ctb');
assert.ok(accounts.isUnclaimedShell(bob), 'a waiting account, left out of the sweeps');
assert.strictEqual(bob.sponsorRef, ann.username || ann.code); assert.strictEqual(bob.username, 'bobctb');
assert.strictEqual((await accounts.listAll(100)).filter(a => a.joinedVia === 'hub').length, 0, 'listAll leaves the waiting accounts out');
assert.strictEqual(hubStore.cursor('iap'), hubStore.eventsAfter(0, 100).length, 'hub cursor moved after the 2xx');
});
await t('the same events delivered again change nothing', async () => {
const before = JSON.stringify(await accounts.listAll(100, { shells: true }));
const skipped = hubsync.adminView().skipped;
hubStore.setCursor('iap', 0); await hubStore.flush();
assert.strictEqual(await deliver(), 2);
assert.strictEqual(JSON.stringify(await accounts.listAll(100, { shells: true })), before);
assert.strictEqual(hubsync.adminView().skipped, skipped + 2);
});
await t('a sponsor not on InstantAdPay yet comes along (climbs the hub line)', async () => {
await ctb('/v1/join', { email: 'dee@example.test', username: 'deectb' });
await ctb('/v1/join', { email: 'carl@example.test', username: 'carlctb', ref: 'deectb' });
const evs = hubStore.eventsAfter(hubStore.cursor('iap'), 10); const carlEv = evs.find(e => e.personId === hubPerson('carl@example.test').id);
const s = signed([carlEv]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200); // carl's event alone, before dee's
const dee = await accounts.byEmail('dee@example.test'); const carl = await accounts.byEmail('carl@example.test');
assert.ok(dee && dee.joinedVia === 'hub', 'sponsor shell built'); assert.strictEqual(carl.sponsorRef, dee.username || dee.code);
await deliver(); // dee's own event later: already there, nothing new
assert.strictEqual((await accounts.listAll(100, { shells: true })).filter(a => a.email === 'dee@example.test').length, 1);
});
await t('an InstantAdPay sign-up is reported to the hub under its InstantAdPay sponsor; its own event is skipped', async () => {
await accounts.touchSeen(ann.email); // ann claimed her waiting account by signing in
const r = await accounts.ensure('erin@example.test', ann.username || ann.code, null, null); assert.ok(r.created);
await settle(); await hubsync.flush(true);
const p = hubPerson('erin@example.test'); assert.ok(p, 'hub has erin');
assert.strictEqual(p.door.site, 'iap'); assert.strictEqual(p.sponsorId, hubPerson('ann@example.test').id);
const applied = hubsync.adminView().applied; await deliver();
assert.strictEqual(hubsync.adminView().applied, applied, 'own join not applied back');
await accounts.setUsername('erin@example.test', 'erin_iap'); await settle(); await hubsync.flush(true);
assert.strictEqual(hubPerson('erin@example.test').aliases.iap, 'erin_iap', 'username follows');
});
await t('a wallet linked on InstantAdPay reaches the hub', async () => {
const x = await accounts.linkWallet('erin@example.test', W('e')); assert.ok(!x.error, x.error);
await settle(); await hubsync.flush(true);
assert.strictEqual(hubPerson('erin@example.test').wallet, W('e'));
});
await t('wallet.connected fills a waiting account, never a claimed one', async () => {
await ctb('/v1/wallet', { email: 'bob@example.test', wallet: W('b') });
await ctb('/v1/wallet', { email: 'ann@example.test', wallet: W('a') });
await deliver();
assert.strictEqual((await accounts.byEmail('bob@example.test')).address, W('b'));
assert.strictEqual((await accounts.byEmail('ann@example.test')).address, null, 'ann signed in: she links her own wallet here');
});
await t('an existing InstantAdPay account keeps its sponsor; the difference is recorded', async () => {
await accounts.setSponsorRef(old.email, ann.username || ann.code);
await ctb('/v1/join', { email: old.email, ref: 'bobctb' }); await deliver();
const a = await accounts.byEmail(old.email);
assert.strictEqual(a.sponsorRef, ann.username || ann.code, 'InstantAdPay sponsor stands');
assert.strictEqual(a.joinedVia, null, 'not turned into a waiting account');
const d = hubsync.adminView().disagreements.find(x => x.email === old.email);
assert.ok(d && d.iap === 'ann@example.test' && d.hub === 'bob@example.test', JSON.stringify(d));
assert.ok(!hubsync.adminView().disagreements.find(x => x.email === 'erin@example.test'), 'agreeing members are not listed');
});
await t('a hub that is down: the hook answers 503 (hub retries), the outbox keeps the join, sign-up is not blocked', async () => {
await ctb('/v1/join', { email: 'fay@example.test' });
process.env.HUB_URL = 'http://127.0.0.1:1';
await assert.rejects(deliver(), /503/);
assert.strictEqual(await accounts.byEmail('fay@example.test'), null);
const r = await accounts.ensure('gus@example.test', '', null, null); assert.ok(r.created, 'sign-up went through');
await settle(); await hubsync.flush(true);
const saved = JSON.parse(fs.readFileSync(path.join(IAP_DATA, 'hubsync.json'), 'utf8'));
assert.ok(saved.outbox.find(i => i.email === 'gus@example.test' && i.tries === 1), 'persisted with a retry count');
process.env.HUB_URL = HUB;
await deliver(); assert.ok(await accounts.byEmail('fay@example.test'), 'retried event applied');
await hubsync.flush(true); assert.ok(hubPerson('gus@example.test'), 'join sent once the hub is back');
assert.strictEqual(hubsync.adminView().outbox, 0);
});
await t('a refused call is final (409 wallet taken), not retried forever', async () => {
await accounts.ensure('hal@example.test', '', null, null); await settle(); await hubsync.flush(true);
await ctb('/v1/join', { email: 'ivy@example.test' }); await ctb('/v1/wallet', { email: 'ivy@example.test', wallet: W('9') });
await accounts.linkWallet('hal@example.test', W('9')); await settle(); await hubsync.flush(true);
const v = hubsync.adminView(); assert.strictEqual(v.outbox, 0); assert.ok(v.recent.find(l => l.type === 'out-refused' && l.code === 'wallet_taken'));
});
await t('sponsor.changed and unknown event types are acknowledged and ignored', async () => {
const s = signed([{ seq: 99001, type: 'sponsor.changed', personId: hubPerson('bob@example.test').id, data: { by: 'admin' } }, { seq: 99002, type: 'member.blocked', personId: 'h_0000000000000000', data: {} }]);
assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200);
});
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);
await accounts.ensure('jon@example.test', '', null, null); await settle();
assert.ok(!JSON.parse(fs.readFileSync(path.join(IAP_DATA, 'hubsync.json'), 'utf8')).outbox.length);
process.env.HUB_ENABLED = '1';
});
hubSrv.close(); iapSrv.close();
// server.js itself: without HUB_ENABLED the route does not exist and no hubsync file is written; with it, unsigned = 401
async function boot(env) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-site-')); const port = 18000 + Math.floor(Math.random() * 2000);
const ch = spawn(process.execPath, ['server.js'], { cwd: ROOT, env: Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_PASSWORD: 'localtest', HUB_ENABLED: '', HUB_URL: '', HUB_SECRET: '' }, env), stdio: 'ignore' });
for (let i = 0; i < 120; i++) { try { await fetch('http://127.0.0.1:' + port + '/'); break; } catch (e) { await new Promise(r => setTimeout(r, 250)); } }
return { ch, dir, url: 'http://127.0.0.1:' + port };
}
for (const [label, env, want] of [['off', {}, 'off'], ['on', { HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:1', HUB_SECRET: IAP_SECRET }, 401]]) {
await t('server.js with the flag ' + label, async () => {
const b = await boot(env);
try {
const r = await fetch(b.url + '/api/hub/events', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"events":[]}' });
const reg = await fetch(b.url + '/api/partner/registry', { method: 'POST', body: '{}' });
assert.strictEqual(reg.status, 503, 'LinkSpin route unchanged (no LS secret here)');
if (want === 'off') { assert.notStrictEqual(r.status, 401); assert.notStrictEqual(r.status, 200); assert.ok(!fs.existsSync(path.join(b.dir, 'hubsync.json')), 'no hubsync file'); }
else { assert.strictEqual(r.status, want); assert.ok(fs.existsSync(path.join(b.dir, 'hubsync.json'))); }
} finally { b.ch.kill(); }
});
}
console.log(`\n${n - fails}/${n} passed`);
process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });
+2
View File
@@ -74,6 +74,8 @@ elif [ "$MODE" = "policy" ]; then
node qa/profile-policy.test.cjs || status=1
elif [ "$MODE" = "bixpay" ]; then
node qa/bixpay.test.cjs || status=1
elif [ "$MODE" = "hub" ]; then
node qa/hubsync.test.cjs || status=1 # needs the network-hub checkout beside this repo (HUB_DIR to override)
elif [ "$MODE" = "walletnudge" ]; then
node qa/walletnudge.test.cjs || status=1
elif [ "$MODE" = "tankhold" ]; then
+12 -1
View File
@@ -54,6 +54,7 @@ const lssync = require('./lssync');
const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23)
const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07)
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
const hubsync = require('./hubsync'); // network hub: members from other doors arrive as waiting accounts, ours are reported (2026-11-12, only with HUB_ENABLED)
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22)
const bixpay = require('./bixpay'); // BixPay Visa card: partner-link field, sponsor-follows resolver, tracked clicks (2026-10-29, gated by site config bixpayLive)
let follow = null, followStore = null;
@@ -538,7 +539,9 @@ async function boot() {
marks.ensureTable().catch(e => console.error('marks table', e.message));
lsconv.init({ db, dataDir: DATA_DIR });
lsreport.init({ db, dataDir: DATA_DIR });
accounts.onWalletLinked(e => { lsreport.wallet(e).catch(err => console.error('lsreport wallet', err.message)); });
accounts.onWalletLinked(hubsync.enabled()
? e => { lsreport.wallet(e).catch(err => console.error('lsreport wallet', err.message)); hubsync.wallet(e); }
: e => { lsreport.wallet(e).catch(err => console.error('lsreport wallet', err.message)); });
auth.onSeen((email, req) => lsconv.noteSession(email, clientIp(req), req.headers['user-agent'])); // own-click tests on LinkSpin (2026-10-26)
setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref();
chain.init({ onEvent: ev => {
@@ -672,6 +675,8 @@ async function boot() {
// LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest
lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email));
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore });
// network hub (hubsync.js): nothing at all happens here unless HUB_ENABLED is on; the LinkSpin sync above runs either way
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account
@@ -3610,6 +3615,12 @@ const server = http.createServer(async (req, res) => {
const rv = await refuel.view(email);
return json(res, 200, { ok: true, refuel: rv, facts: rv.on ? await engine.facts({ site: 'iap', adminMember, ads, coach }, email) : null });
}
// -- network hub hooks (hubsync.js, 2026-11-12): signed with HUB_SECRET (X-Hub-Ts + X-Hub-Sig), 5-minute window. Only with HUB_ENABLED.
if (p === '/api/hub/events' && req.method === 'POST' && hubsync.enabled()) {
let raw; try { raw = (await readRaw(req, 2e6)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
const r = await hubsync.receive(req.headers, raw); return json(res, r.status, r.body);
}
if (p === '/api/admin/hub' && req.method === 'GET' && hubsync.enabled()) { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, hubsync.adminView()); }
if (p === '/api/partner/registry' && req.method === 'POST') {
const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
const b = sg.body;