// BTC4Hits bridge + admin spin links (2026-11-11). Boots a throwaway LinkSpin (temp DATA_DIR, JSON stores, no mail key,
// ADMIN_PASSWORD=localtest) and checks:
// /from/btc4hits: 200, the sponsor cookie is cleared, angle b4h + forced first-touch source legacy:btc4hits, sign-in copy,
// no em dash in the copy; a sign-up through it gets NO welcome-back credits (legacy grant rule is fw/t1 only)
// /api/admin/rotations: POST with urls[] makes one spin link with every destination at weight 1, GET lists links + sources,
// DELETE removes it; auth required.
// node qa/btc4hits-bridge.test.mjs (B4H_PORT to move the port)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const SITE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const PORT = Number(process.env.B4H_PORT || 8831), BASE = 'http://127.0.0.1:' + PORT;
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pass = 0, fail = 0; const ok = (c, n, x) => { if (c) { pass++; console.log('ok ' + n); } else { fail++; console.log('FAIL ' + n + (x ? '\n ' + x : '')); } };
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'b4h-ls-')); fs.mkdirSync(path.join(dir, 'uploads'), { recursive: true });
const now = Date.now();
fs.writeFileSync(path.join(dir, 'accounts.json'), JSON.stringify({ v: 2, byEmail: { 'owner@qa.test': { email: 'owner@qa.test', pass: null, sponsorRef: '', code: 'cowner1', username: 'owner', address: null, created: now - 86400000, joinedVia: 'carried', joinedRef: 'network' } }, byAddress: {}, byCode: { cowner1: 'owner@qa.test' }, joins: 0, positions: {} }));
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: dir, ADMIN_EMAIL: 'admin@qa.test', ADMIN_PASSWORD: 'localtest', DATABASE_URL: '', SENDGRID_API_KEY: '', SENDGRID_KEY: '', OUTBOUND: '', LS_SYNC_SECRET: '', ENGINE_KEY: '', ENGINE_KEY_FILE: '' });
const log = path.join(dir, 'server.log');
const proc = spawn(process.execPath, ['server.js'], { cwd: SITE, env, stdio: ['ignore', fs.openSync(log, 'w'), fs.openSync(log, 'a')] });
const admin = (pth, method, body, auth = true) => fetch(BASE + pth, { method, headers: Object.assign({ 'Content-Type': 'application/json' }, auth ? { Authorization: 'Bearer localtest' } : {}), body: body ? JSON.stringify(body) : undefined });
try {
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(BASE + '/api/config', { signal: AbortSignal.timeout(2000) })).status < 500; } catch (e) { await sleep(1000); } }
ok(up, 'local LinkSpin up');
// 1. the bridge page
const r = await fetch(BASE + '/from/btc4hits?src=splash', { headers: { Cookie: 'iap.sponsor=someone' } });
const html = await r.text(); const ck = r.headers.getSetCookie ? r.headers.getSetCookie() : [];
ok(r.status === 200, '/from/btc4hits answers 200', String(r.status));
ok(ck.some(c => /^iap\.sponsor=;/.test(c) && /Max-Age=0/.test(c)), 'sponsor cookie cleared (no sponsor from the bridge itself)', ck.join(' | '));
ok(ck.some(c => /^iap\.angle=b4h;/.test(c)), 'angle b4h remembered');
ok(ck.some(c => c.startsWith('iap.ref=' + encodeURIComponent('legacy:btc4hits:splash') + ';')), 'forced first-touch source legacy:btc4hits', ck.join(' | '));
ok(/
BTC4Hits is now LinkSpin\. \| LinkSpin<\/title>/.test(html) && html.includes('class="squeeze"'), 'title + squeeze layout');
ok(html.includes('join.js?v=20261111b4h'), 'join.js version bumped');
const js = fs.readFileSync(path.join(SITE, 'public', 'assets', 'join.js'), 'utf8'); const b4h = (js.match(/\n\s+b4h: \{[^\n]+/) || [''])[0];
ok(b4h.includes('Sign in with your BTC4Hits email') && b4h.includes("cta: 'Sign in with your email'"), 'sign-in call to action in the b4h copy');
ok(!/—/.test(b4h) && !/—/.test(html.match(/[^<]*/)[0]), 'no em dash in the copy');
// a brand-new sign-up arriving through the bridge: no welcome-back credits
const st = await (await fetch(BASE + '/api/auth/email/start', { method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: 'iap.angle=b4h; iap.ref=legacy%3Abtc4hits' }, body: JSON.stringify({ email: 'newb4h@qa.test', fts: Date.now() - 8000 }) })).json();
if (st.devCode) {
const v = await fetch(BASE + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: 'iap.angle=b4h; iap.ref=legacy%3Abtc4hits' }, body: JSON.stringify({ email: 'newb4h@qa.test', code: st.devCode }) });
ok(v.status === 200, 'sign-up through the bridge works', String(v.status));
await sleep(300);
ok(!fs.existsSync(path.join(dir, 'legacy-grants.json')) && !/legacy grant/.test(fs.readFileSync(log, 'utf8')), 'no welcome-back credits granted');
const a = JSON.parse(fs.readFileSync(path.join(dir, 'accounts.json'), 'utf8')).byEmail['newb4h@qa.test'];
ok(a && a.joinedVia === 'b4h' && a.joinedRef === 'legacy:btc4hits', 'account records angle b4h + source legacy:btc4hits', JSON.stringify(a && { v: a.joinedVia, r: a.joinedRef }));
// 1b. Holding tank menu item (2026-11-11): the summary route, and the rail item in a real browser
const cookies = (v.headers.getSetCookie ? v.headers.getSetCookie() : []).map(c => c.split(';')[0]);
const sum = await (await fetch(BASE + '/api/my/tank/summary', { headers: { Cookie: cookies.join('; ') } })).json();
ok(sum.adopter === false && sum.cap === 10 && typeof sum.waiting === 'number', '/api/my/tank/summary: a new member is not an adopter, cap 10 from the setting', JSON.stringify(sum));
ok((await fetch(BASE + '/api/my/tank/summary')).status === 401, '/api/my/tank/summary needs a sign-in');
try {
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
const browser = await chromium.launch();
const shot = async (summary) => {
const ctx = await browser.newContext(); await ctx.addCookies(cookies.map(c => { const i = c.indexOf('='); return { name: c.slice(0, i), value: c.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
if (summary) await page.route('**/api/my/tank/summary', r => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(summary) }));
await page.goto(BASE + '/links', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2500);
const out = await page.evaluate(() => { const a = document.getElementById('crTank'); return a ? { hidden: a.hidden, href: a.getAttribute('href'), title: a.title, badge: (a.querySelector('.rbadge') || {}).textContent || '', label: (a.querySelector('.lbl') || {}).textContent || '' } : null; });
await ctx.close(); return Object.assign({ errs }, out || {});
};
const s1 = await shot(null);
ok(s1.href === '/tools#line' && s1.hidden === true, 'rail: Holding tank item hidden for a member who cannot adopt', JSON.stringify(s1));
const s2 = await shot({ adopter: true, eligible: true, full: false, held: 2, cap: 10, waiting: 1234 });
ok(s2.hidden === false && s2.label === 'Holding tank' && s2.badge === '999+', 'rail: shown for an adopter, with the waiting badge', JSON.stringify(s2));
ok(/You can adopt up to 10 people at a time\./.test(s2.title) && /1,234 waiting/.test(s2.title) && !/\u2014/.test(s2.title), 'rail: one line with the cap from the setting', s2.title);
const s3 = await shot({ adopter: true, eligible: false, full: true, held: 7, cap: 7, waiting: 0 });
ok(s3.hidden === false && !s3.badge && /up to 7 people at a time/.test(s3.title), 'rail: an adopter at the cap still sees it; cap read from the response (7), no badge when nobody waits', JSON.stringify(s3));
ok(!s1.errs.length && !s2.errs.length, 'no page errors', JSON.stringify(s1.errs.concat(s2.errs)).slice(0, 200));
await browser.close();
} catch (e) { ok(false, 'browser check ran', e.message); }
} else ok(false, 'dev sign-in code available', JSON.stringify(st));
// 2. admin spin links
ok((await admin('/api/admin/rotations?email=owner@qa.test', 'GET', null, false)).status === 401, 'GET needs admin');
const urls = ['https://example.com/a', 'https://example.org/b', 'example.net/c'].map(u => ({ url: u, label: 'x' }));
const p = await (await admin('/api/admin/rotations', 'POST', { email: 'owner@qa.test', source: { name: 'BTC4Hits', site: 'btc4hits.com' }, links: [{ name: 'BTC4Hits rotator #7', url: urls[0].url, fallback: urls[0].url, urls }] })).json();
ok(p.ok && p.links[0].dests === 3 && p.links[0].code, 'POST makes one link with 3 destinations', JSON.stringify(p));
const g = await (await admin('/api/admin/rotations?email=owner@qa.test', 'GET')).json();
const rot = (g.rotations || []).find(x => x.name === 'BTC4Hits rotator #7');
ok(rot && rot.destinations.length === 3 && rot.destinations.every(d => d.weight === 1 && d.active) && rot.destinations[2].url === 'https://example.net/c', 'GET lists it: 3 active destinations, weight 1, cleaned URLs');
ok(rot && rot.sourceId && (g.sources || []).some(s => s.id === rot.sourceId && s.name === 'BTC4Hits'), 'attached to the BTC4Hits source');
ok(typeof g.linkBase === 'string' && g.linkBase.endsWith('/r/'), 'linkBase given');
const red = await fetch(BASE + '/r/' + rot.code, { redirect: 'manual', headers: { 'User-Agent': 'curl/8' } });
ok(red.status >= 301 && red.status <= 308 && urls.some(u => red.headers.get('location').startsWith(u.url.startsWith('http') ? u.url : 'https://' + u.url)), '/r/ redirects to one of them', red.status + ' ' + red.headers.get('location'));
const d = await admin('/api/admin/rotations?email=owner@qa.test&id=' + rot.id, 'DELETE');
ok(d.status === 200, 'DELETE removes it');
const g2 = await (await admin('/api/admin/rotations?email=owner@qa.test', 'GET')).json();
ok(!(g2.rotations || []).length, 'gone after DELETE');
ok((await admin('/api/admin/rotations?email=nobody@qa.test', 'GET')).status === 404, 'unknown member -> 404');
} finally { proc.kill(); }
console.log('\n' + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);