Files
linkspin/qa/partner-vabspins.test.mjs
T

61 lines
6.3 KiB
JavaScript

// ViralAdBlitz "Use one of my spin links" (/api/partner/vab/links op 'spins', Marty 2026-11-15).
// Boots server.js on its own port with a throwaway seeded data dir (JSON store, no DB) and checks: the signature, the member's
// own spin links only (never another account's, never the partner-made tracked text-ad links), the public /r/ url on the
// link host, active destination count, paused flag, the hosts list, by username or email, unknown account -> account false.
// node qa/partner-vabspins.test.mjs (from the site dir; PORT default 8975)
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 || 8975); 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(), 'vabspins-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@vab.test': acct('one@vab.test', 'vabone', 930001), 'two@vab.test': acct('two@vab.test', 'vabtwo', 930002) }, 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,spare-links.test.org' }));
const dest = (id, url, active) => ({ id, url, label: '', weight: 1, active: active !== false, added: now });
const rot = (id, owner, code, name, dests, extra) => Object.assign({ id, owner, name, code, fallback: '', destinations: dests, created: now, paused: false, nextDest: dests.length + 1 }, extra || {});
fs.writeFileSync(path.join(DATA, 'rotator.json'), JSON.stringify({ v: 1, hits: [], conv: [], rotations: [
rot(1, 'one@vab.test', 'onespin1', 'My three offers', [dest(1, 'https://a.example.org/'), dest(2, 'https://b.example.org/'), dest(3, 'https://c.example.org/', false)]),
rot(2, 'one@vab.test', 'onespin2', 'Resting link', [dest(1, 'https://d.example.org/')], { paused: true }),
rot(3, 'one@vab.test', 'onevab42', 'ViralAdBlitz: Grow your list', [dest(1, 'https://e.example.org/')], { partner: 'vab:42' }),
rot(4, 'two@vab.test', 'twospin1', 'Someone else', [dest(1, 'https://f.example.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@vab.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 = {}) {
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/vab/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); }
let r = await call({ username: 'vabone', op: 'spins' }, { sec: 'y'.repeat(64) }); ok(r._status === 401 && !r.spins, 'a wrong signature is refused', r);
r = await call({ username: 'vabone', op: 'spins' }, { ts: now - 3600000 }); ok(r._status === 401, 'an old timestamp is refused', r);
r = await call({ username: 'nobody', op: 'spins' }); ok(r._status === 200 && r.account === false && !r.spins && Array.isArray(r.hosts) && r.hosts.includes('spin-links.test.org'), 'no LinkSpin account: account false, no links, the public link hosts', r);
r = await call({ username: 'vabone', op: 'spins' });
ok(r._status === 200 && r.account && r.username === 'vabone' && r.host === 'spin-links.test.org', 'spins: the account by network username, the clean link host', r);
const codes = (r.spins || []).map(x => x.code).sort();
ok(JSON.stringify(codes) === JSON.stringify(['onespin1', 'onespin2']), 'only the member\'s own spin links (not the partner-made text-ad link, not another account\'s)', codes);
const s1 = (r.spins || []).find(x => x.code === 'onespin1') || {}; const s2 = (r.spins || []).find(x => x.code === 'onespin2') || {};
ok(s1.url === 'https://spin-links.test.org/r/onespin1' && s1.name === 'My three offers' && s1.destinations === 2 && s1.paused === false, 'each link: public /r/ url, name, active destinations, not paused', s1);
ok(s2.paused === true && s2.destinations === 1, 'a paused link says so', s2);
ok(Array.isArray(r.hosts) && r.hosts.includes('spin-links.test.org') && r.hosts.includes('spare-links.test.org') && r.hosts.length >= 3, 'hosts: the app host plus every configured link domain', r.hosts);
ok(Object.keys(s1).sort().join(',') === 'code,destinations,name,paused,url', 'no destination urls or other account facts in a link', Object.keys(s1));
ok(!('email' in r) && !('stats' in r), 'no email or stats in the answer', Object.keys(r));
r = await call({ email: 'two@vab.test', op: 'spins' });
ok(r.account && (r.spins || []).length === 1 && r.spins[0].code === 'twospin1', 'by email: the other member sees only their own link', r.spins);
const rf = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations;
ok(rf.length === 4, 'read only: no link made or changed', rf.length);
} 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);