836c7b17c2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
337 lines
27 KiB
JavaScript
337 lines
27 KiB
JavaScript
// 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', 'network-hub-resolve-id'].map(d => path.join(ROOT, up, d))).find(d => fs.existsSync(path.join(d, 'server.js')));
|
|
let fails = 0, n = 0;
|
|
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e && e.stack ? e.stack.split('\n').slice(0, 3).join(' | ') : e); } }
|
|
const IAP_SECRET = 'i'.repeat(40), CTB_SECRET = 'c'.repeat(40);
|
|
const W = k => '0x' + String(k).repeat(40).slice(0, 40);
|
|
const sig = (secret, ts, raw) => crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
|
const listen = srv => new Promise(ok => srv.listen(0, '127.0.0.1', () => ok(srv.address().port)));
|
|
// mail audit (2026-11-14): every outbound request this process makes is recorded; only the local hub and site may be called.
|
|
// mailer.js sends with https.request (SendGrid), Telegram and Sendy go out over https too, so both doors are watched.
|
|
const outside = [];
|
|
{ const realFetch = global.fetch; global.fetch = (u, o) => { const s = String(u && u.url ? u.url : u); if (!/^http:[/][/]127[.]0[.]0[.]1:/.test(s)) outside.push(s); return realFetch(u, o); };
|
|
const https = require('https'); const realReq = https.request; https.request = function (...a) { outside.push('https ' + JSON.stringify((a[0] && a[0].hostname) || a[0])); return realReq.apply(this, a); }; }
|
|
|
|
delete process.env.DATABASE_URL; delete process.env.LS_SYNC_SECRET; // JSON stores, LinkSpin push off
|
|
const HUB_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-hub-'));
|
|
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('rule 2: a paid Purchase on the InstantAdPay contract reaches the hub and moves the network sponsor to this contract (2026-11-14)', async () => {
|
|
// tureia2003's shape: locked on LinkSpin under silverstussy (activated only), then bound AND paid here under paidtowatch
|
|
await ctb('/v1/join', { email: 'ptw@example.test', username: 'ptw' }); await ctb('/v1/wallet', { email: 'ptw@example.test', wallet: W('d') });
|
|
await ctb('/v1/join', { email: 'sil@example.test', username: 'sil' }); await ctb('/v1/wallet', { email: 'sil@example.test', wallet: W('f') });
|
|
await ctb('/v1/join', { email: 'tur@example.test', ref: 'sil', username: 'tur' });
|
|
await ctb('/v1/contract-bind', { contract: 'linkspin', email: 'tur@example.test', wallet: W('7'), sponsorRef: W('f') });
|
|
assert.strictEqual(hubPerson('tur@example.test').sponsorId, hubPerson('sil@example.test').id);
|
|
const members = { 5: { account: W('d') }, 12: { account: W('7') } };
|
|
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound, chain: { member: async id => members[id] || null } });
|
|
hubsync.onChain({ type: 'MemberActivated', id: 12, account: W('7'), sponsorId: 5 });
|
|
hubsync.onChain({ type: 'Purchase', buyerId: 12, priceCents: 0, paidWei: '0', tx: '0xfree' }); // nothing paid in: not a spend
|
|
hubsync.onChain({ type: 'Purchase', buyerId: 12, priceCents: 3500, paidWei: '1000', tx: '0xpaid', ts: 1700000000000 });
|
|
hubsync.onChain({ type: 'Purchase', buyerId: 12, priceCents: 3500, paidWei: '1000', tx: '0xpaid', ts: 1700000000000 }); // seen twice
|
|
await settle(); await hubsync.flush(true);
|
|
const p = hubPerson('tur@example.test');
|
|
assert.strictEqual(p.bindings.iap.sponsorId, hubPerson('ptw@example.test').id);
|
|
assert.strictEqual(p.bindings.iap.spentCents, 3500, 'one purchase counted once');
|
|
assert.strictEqual(p.bindings.linkspin.sponsorId, hubPerson('sil@example.test').id, 'the LinkSpin lock keeps its sponsor');
|
|
assert.strictEqual(p.sponsorId, hubPerson('ptw@example.test').id, 'network sponsor = the contract with money spent');
|
|
assert.strictEqual(hubsync.adminView().outbox, 0);
|
|
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound });
|
|
});
|
|
|
|
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);
|
|
});
|
|
|
|
const HP = hubReq('lib/people');
|
|
await t('rule 2 on arrival: someone the InstantAdPay contract holds arrives under that lock sponsor, not the network sponsor; sponsor.changed never moves them', async () => {
|
|
await ctb('/v1/join', { email: 'lx@example.test', username: 'lockx' }); // their sponsor on the InstantAdPay contract
|
|
await ctb('/v1/join', { email: 'ly@example.test', username: 'locky' }); // their sponsor on LinkSpin, where the money was spent
|
|
await ctb('/v1/join', { email: 'lk@example.test', username: 'lockkid', ref: 'locky' });
|
|
HP.bindContract({ site: 'iap', contract: 'iap', email: 'lk@example.test', wallet: W('3'), sponsorRef: 'lockx', at: 1000 });
|
|
HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'lk@example.test', wallet: W('3'), sponsorRef: 'locky', at: 2000, spentCents: 2500 });
|
|
await hubStore.flush();
|
|
const hp = hubPerson('lk@example.test');
|
|
assert.strictEqual(hp.sponsorId, hubPerson('ly@example.test').id, 'network sponsor = LinkSpin (money spent there)');
|
|
assert.strictEqual(hp.bindings.iap.sponsorId, hubPerson('lx@example.test').id);
|
|
await deliver();
|
|
const kid = await accounts.byEmail('lk@example.test'); const lx = await accounts.byEmail('lx@example.test');
|
|
assert.ok(kid && lx, 'both arrived');
|
|
assert.strictEqual(kid.sponsorRef, lx.username || lx.code, 'the InstantAdPay lock sponsor is written here');
|
|
const s = signed([{ seq: 99101, type: 'sponsor.changed', personId: hp.id, data: { by: 'contract', contract: 'linkspin' } }]);
|
|
assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200);
|
|
assert.strictEqual((await accounts.byEmail('lk@example.test')).sponsorRef, lx.username || lx.code, 'sponsor.changed is ignored');
|
|
// climbing: a lock sponsor not on InstantAdPay yet comes along before the member (their event alone)
|
|
await ctb('/v1/join', { email: 'lz@example.test', username: 'lockz' });
|
|
await ctb('/v1/join', { email: 'lk2@example.test', username: 'lockkid2', ref: 'locky' });
|
|
HP.bindContract({ site: 'iap', contract: 'iap', email: 'lk2@example.test', wallet: W('4'), sponsorRef: 'lockz', at: 3000, spentCents: 2000 });
|
|
HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'lk2@example.test', wallet: W('4'), sponsorRef: 'locky', at: 1500, spentCents: 2000 }); // earlier spend: network = locky
|
|
await hubStore.flush();
|
|
assert.strictEqual(hubPerson('lk2@example.test').sponsorId, hubPerson('ly@example.test').id);
|
|
const ev = hubStore.eventsAfter(0, 1e6).find(e => e.type === 'member.joined' && e.personId === hubPerson('lk2@example.test').id);
|
|
const s2 = signed([ev]); assert.strictEqual((await hubsync.receive(s2.headers, s2.raw)).status, 200);
|
|
const lz = await accounts.byEmail('lz@example.test');
|
|
assert.ok(lz, 'the lock sponsor came along'); assert.strictEqual((await accounts.byEmail('lk2@example.test')).sponsorRef, lz.username || lz.code);
|
|
await deliver();
|
|
});
|
|
|
|
// the holding tank, as server.js wires it with HUB_ENABLED, with a mailer and messages that only record
|
|
const tank = require(path.join(ROOT, 'tank.js'));
|
|
const sent = [];
|
|
const mailer = { hasKey: () => true, send: async (...a) => { sent.push(['mail', a[0], a[1]]); } };
|
|
const messages = { sendChat: async (...a) => { sent.push(['chat', a[2]]); }, deliver: async (...a) => { sent.push(['notice', a[2]]); }, lastFrom: async () => Date.now() }; // every sponsor 'just wrote': rescue warnings are not what this checks
|
|
tank.init({ dataDir: IAP_DATA, accounts, chain: { recentEvents: () => [], member: async () => null }, messages, mailer,
|
|
hooks: { network: async (email, address) => (await hubsync.hubSponsor(email)) || lsinbound.networkSponsor(email, address), networkHeld: a => hubsync.heldAmong(a), networkLocked: e => hubsync.lockedAnywhere(e) } });
|
|
|
|
await t('rule 3: the tank never offers anyone locked on any network contract or sponsored in the hub; release refuses a locked member', async () => {
|
|
await ctb('/v1/join', { email: 'tk1@example.test', username: 'tk1ctb', ref: 'annctb' }); // the hub knows a sponsor
|
|
for (const e of ['tk1', 'tk2', 'tk3']) assert.ok((await accounts.ensure(e + '@example.test', '', null, null)).created); // signed up here, no sponsor
|
|
await settle(); await hubsync.flush(true);
|
|
HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'tk2@example.test', wallet: W('5'), sponsorRef: '' }); await hubStore.flush(); // locked, top of that tree
|
|
hubsync._heldReset();
|
|
const held = await hubsync.heldAmong([await accounts.byEmail('tk1@example.test'), await accounts.byEmail('tk2@example.test'), await accounts.byEmail('tk3@example.test')]);
|
|
assert.deepStrictEqual([...held.entries()].sort(), [['tk1@example.test', 'sponsored'], ['tk2@example.test', 'locked']]);
|
|
const w = (await tank.waiting()).map(x => x.email);
|
|
assert.ok(w.includes('tk3@example.test'), 'a free member is offered');
|
|
assert.ok(!w.includes('tk1@example.test') && !w.includes('tk2@example.test'), 'sponsored and locked are not: ' + w.join(','));
|
|
// tk2 under erin here, not activated here: releasing them to the tank is refused, the hub's lock elsewhere stands
|
|
const erin = await accounts.byEmail('erin@example.test'); await accounts.setSponsorRef('tk2@example.test', erin.username || erin.code);
|
|
const r = await tank.release('erin@example.test', 'tk2@example.test');
|
|
assert.ok(r.error && /locked/.test(r.error), JSON.stringify(r));
|
|
assert.strictEqual((await accounts.byEmail('tk2@example.test')).sponsorRef, erin.username || erin.code);
|
|
// the 15-minute tick: with HUB_TANK_ALIGN off tk1 is only held; with it on, aligned to the sponsor the hub knows (ann has a real account here), quietly
|
|
await tank.readyTick(); assert.strictEqual((await accounts.byEmail('tk1@example.test')).sponsorRef || '', '', 'alignment from the hub is off by default');
|
|
process.env.HUB_TANK_ALIGN = 'on'; await tank.readyTick(); delete process.env.HUB_TANK_ALIGN;
|
|
assert.strictEqual((await accounts.byEmail('tk1@example.test')).sponsorRef, ann.username || ann.code, 'aligned to the hub sponsor');
|
|
});
|
|
|
|
await t('rule 3 fail-safe: hub unreachable past the 1-hour cache = nobody it was asked about is offered; back = offered again', async () => {
|
|
process.env.HUB_URL = 'http://127.0.0.1:1'; hubsync._heldAge(30 * 60000);
|
|
assert.ok((await tank.waiting()).map(x => x.email).includes('tk3@example.test'), 'within the hour the last answer stands');
|
|
hubsync._heldReset(); // nothing cached, hub down
|
|
assert.ok(!(await tank.waiting()).map(x => x.email).includes('tk3@example.test'), 'unknown = held');
|
|
assert.strictEqual(await hubsync.lockedAnywhere('tk3@example.test'), 'unknown');
|
|
process.env.HUB_URL = HUB; hubsync._heldReset();
|
|
assert.ok((await tank.waiting()).map(x => x.email).includes('tk3@example.test'));
|
|
});
|
|
|
|
await t('mail audit: hub arrivals (new, sponsor climbed, existing filled, wallet) and the tank ticks send no mail, chat, notice or outside call', async () => {
|
|
sent.length = 0; outside.length = 0;
|
|
await ctb('/v1/join', { email: 'ma@example.test', username: 'mailtop' }); await ctb('/v1/wallet', { email: 'ma@example.test', wallet: W('6') });
|
|
await ctb('/v1/join', { email: 'mb@example.test', username: 'mailkid', ref: 'mailtop' }); await ctb('/v1/wallet', { email: 'mb@example.test', wallet: W('8') });
|
|
process.env.HUB_ENABLED = ''; await accounts.ensure('mc@example.test', '', null, null); process.env.HUB_ENABLED = '1'; // here before the hub knew them
|
|
await ctb('/v1/join', { email: 'mc@example.test', username: 'mailfill' }); // an existing InstantAdPay account: empty fields filled
|
|
const evs = hubStore.eventsAfter(hubStore.cursor('iap'), 100);
|
|
const kid = evs.find(e => e.personId === hubPerson('mb@example.test').id && e.type === 'member.joined');
|
|
const s = signed([kid]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200); // the kid first: the sponsor climbs
|
|
await deliver();
|
|
assert.ok(await accounts.byEmail('ma@example.test') && await accounts.byEmail('mb@example.test'));
|
|
assert.strictEqual((await accounts.byEmail('mb@example.test')).address, W('8'));
|
|
assert.strictEqual((await accounts.byEmail('mc@example.test')).username, 'mailfill', 'filled');
|
|
await settle(); await hubsync.flush(true); await tank.readyTick(); await tank.sweep(); await settle(); await hubsync.flush(true);
|
|
assert.deepStrictEqual(JSON.parse(fs.readFileSync(path.join(IAP_DATA, 'hubsync.json'), 'utf8')).outbox, []);
|
|
assert.deepStrictEqual(sent, [], 'nothing sent');
|
|
assert.deepStrictEqual(outside, [], 'no outside call');
|
|
// the old direct LinkSpin sync never pushes a waiting account the hub made (LinkSpin's registry route would switch payouts
|
|
// on and email them); a member who signs up here still goes
|
|
const pushed = []; const lsStub = http.createServer((req, res) => { let d = ''; req.on('data', c => { d += c; }); req.on('end', () => { try { for (const r of JSON.parse(d).rows || []) pushed.push(r.email); } catch (e) {} res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"ok":true,"proto":2}'); }); });
|
|
process.env.LS_URL = 'http://127.0.0.1:' + await listen(lsStub); process.env.LS_SYNC_SECRET = 's'.repeat(40);
|
|
try {
|
|
await lssync.tick(true);
|
|
assert.ok(pushed.length > 0, 'the sync ran');
|
|
for (const e of ['ma@example.test', 'mb@example.test', 'lk@example.test', 'bob@example.test']) assert.ok(!pushed.includes(e), e + ' (a hub waiting account) was pushed');
|
|
assert.ok(pushed.includes('erin@example.test'), 'an InstantAdPay sign-up still syncs');
|
|
} finally { delete process.env.LS_SYNC_SECRET; lsStub.close(); }
|
|
// and the hub path itself never loads a mail module
|
|
const loaded = Object.keys(require.cache).map(f => path.basename(f));
|
|
for (const m of ['mailer.js', 'sendy.js', 'messages.js', 'drip.js']) assert.ok(!loaded.includes(m), m + ' is loaded');
|
|
});
|
|
|
|
await t('flag off: the module answers 404 and reports nothing', async () => {
|
|
process.env.HUB_ENABLED = '';
|
|
const s = signed([]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 404);
|
|
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); });
|