Files
linkspin/qa/partner-vablinks.test.mjs

64 lines
7.0 KiB
JavaScript

// ViralAdBlitz tracked text-ad links (/api/partner/vab/links, 2026-11-15; the same endpoint as DownlineHydra's, site vab).
// Boots server.js on its own port with a throwaway seeded data dir (JSON store, no DB, no mail key, no chain keys) and checks:
// the signature, one link per text ad on the member's own account with the "ViralAdBlitz" source and the ad id as sub-id, an edited
// ad link updating the same code, a DownlineHydra link with the same id kept apart, stats per site, unknown partner sites refused.
// node qa/partner-vablinks.test.mjs (from the site dir; PORT default 8974)
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawn } from 'node:child_process';
const PORT = Number(process.env.PORT || 8974); const BASE = 'http://127.0.0.1:' + PORT; const SEC = crypto.randomBytes(32).toString('hex');
let pass = 0, fail = 0; const ok = (c, what, x) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (x !== undefined ? ' -> ' + JSON.stringify(x).slice(0, 400) : '')); } };
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'vab-qa-'));
const now = Date.now();
const acct = (email, username, memberId) => ({ email, username, code: username.slice(0, 7), memberId, created: now - 86400000, sponsorRef: '' });
const accounts = { v: 2, byEmail: { 'one@dh.test': acct('one@dh.test', 'dhone', 920001), 'two@dh.test': acct('two@dh.test', 'dhtwo', 920002) }, byAddress: {}, byCode: {}, joins: 2, positions: {} };
for (const a of Object.values(accounts.byEmail)) accounts.byCode[a.code] = a.email;
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(accounts));
fs.writeFileSync(path.join(DATA, 'site.json'), JSON.stringify({ linkDomains: 'spin-links.test.org' }));
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NETWORK_SSO_SECRET: SEC, ADMIN_PASSWORD: 'x'.repeat(16), ADMIN_EMAIL: 'admin@dh.test' });
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'HUB_ENABLED', 'HUB_URL']) delete env[k];
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'ignore', 'ignore'] });
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function call(body, o = {}, site = 'vab') {
const raw = JSON.stringify(body); const ts = String(o.ts || Date.now()); const sig = crypto.createHmac('sha256', o.sec || SEC).update('net.v1.' + ts + '\n' + raw).digest('hex');
const r = await fetch(BASE + '/api/partner/' + site + '/links', { method: 'POST', body: raw, headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } });
return Object.assign({ _status: r.status }, await r.json().catch(() => ({})));
}
try {
for (let i = 0; i < 60; i++) { try { if ((await fetch(BASE + '/api/config')).ok) break; } catch (e) {} await sleep(500); }
const AD = [{ id: '42', name: 'Grow your list', url: 'https://mylist.example.org/?ref=one' }];
let r = await call({ email: 'one@dh.test', op: 'ensure', links: AD }, { sec: 'y'.repeat(64) }); ok(r._status === 401, 'a wrong signature is refused');
r = await call({ email: 'one@dh.test', op: 'ensure', links: AD }, {}, 'zz'); ok(r._status === 404 || (r._status >= 400 && !r.links), 'an unknown partner site is not served', r);
r = await call({ email: 'nobody@dh.test', op: 'ensure', links: AD }); ok(r._status === 200 && r.account === false, 'no LinkSpin account: account false', r);
r = await call({ email: 'one@dh.test', op: 'ensure', links: AD });
const c42 = r.links && r.links['42'] && r.links['42'].code;
ok(r.account && r.host === 'spin-links.test.org' && /^[a-z0-9]{6}$/.test(c42 || '') && r.links['42'].created, 'ensure: a new link for the ad (id field), clean host', r);
ok(r.links['42'].link === 'https://spin-links.test.org/r/' + c42 + '?s1=42&placement=42', 'the link carries the ad id as s1 and placement', r.links['42'].link);
const src = JSON.parse(fs.readFileSync(path.join(DATA, 'sources.json'), 'utf8')); const mine = (src.items || src.sources || []).filter(x => x.owner === 'one@dh.test');
ok(mine.length === 1 && mine[0].template === 'viraladblitz' && mine[0].name === 'ViralAdBlitz' && r.sourceId === mine[0].id, 'the account has one "ViralAdBlitz" source (network template)', mine);
let rot = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations.filter(x => x.owner === 'one@dh.test');
ok(rot.length === 1 && rot[0].partner === 'vab:42' && rot[0].name === 'ViralAdBlitz: Grow your list' && rot[0].sourceId === mine[0].id && rot[0].destinations[0].url === AD[0].url, 'the link is tagged vab:42 with that source and points at the ad link', rot);
r = await call({ email: 'one@dh.test', op: 'ensure', links: [{ id: '42', name: 'Grow your list', url: 'https://mylist.example.org/?ref=one&v=2' }] });
rot = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations.filter(x => x.owner === 'one@dh.test');
ok(r.links['42'].code === c42 && !r.links['42'].created && rot.length === 1 && rot[0].destinations[0].url.endsWith('&v=2'), 'an edited ad link updates the same LinkSpin link', r);
r = await call({ email: 'one@dh.test', op: 'ensure', links: [{ program: '42', url: 'https://other.example.org/' }] }, {}, 'dh');
rot = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations.filter(x => x.owner === 'one@dh.test');
ok(r.links['42'] && r.links['42'].code !== c42 && rot.length === 2 && rot.some(x => x.partner === 'dh:42'), 'a DownlineHydra program with the same id is a separate link', rot.map(x => x.partner));
const hit = await fetch(BASE + '/r/' + c42 + '?s1=42&placement=42', { redirect: 'manual', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36' } });
const loc = hit.headers.get('location') || '';
ok(hit.status >= 300 && hit.status < 400 && loc.startsWith('https://mylist.example.org/?ref=one&v=2'), 'the redirect lands on the ad link', [hit.status, loc]);
await sleep(300);
r = await call({ email: 'one@dh.test', op: 'stats' });
ok(r.account && r.stats['42'] && r.stats['42'].hits === 1 && r.stats['42'].unique30 === 1 && Object.keys(r.stats).length === 1, 'vab stats: the ad click, only the vab links', r.stats);
r = await call({ email: 'one@dh.test', op: 'stats' }, {}, 'dh');
ok(r.account && r.stats['42'] && r.stats['42'].hits === 0, 'dh stats do not see the vab click', r.stats);
const rep = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).hits.find(h => h.r === rot.find(x => x.partner === 'vab:42').id);
ok(rep && rep.sr === mine[0].id && rep.q && rep.q.s1 === '42', 'the click is recorded under the ViralAdBlitz source with the ad sub-id', rep);
} catch (e) { fail++; console.error(e); }
finally { srv.kill(); await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} }
console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);