diff --git a/qa/convpixel.test.mjs b/qa/convpixel.test.mjs
new file mode 100644
index 0000000..121615d
--- /dev/null
+++ b/qa/convpixel.test.mjs
@@ -0,0 +1,204 @@
+// Conversion pixel, InstantAdPay half (2026-10-23), end to end against a LOCAL copy and a MOCK LinkSpin.
+// node qa/convpixel.test.mjs (or: bash qa/run.sh convpixel)
+// Boots server.js on its own port with a throwaway DATA_DIR seeded with two advertisers and a few campaigns (JSON store,
+// DATABASE_URL blank, no mail key, devCode sign-in, a minimal environment so no live secret can leak in), LS_URL pointing at a
+// mock LinkSpin on localhost that verifies the HMAC on every call, records the pushed clicks and answers op summary.
+// Nothing touches production or a real member. Checks: lsclk on the 302 (existing params and #hash kept, a LinkSpin /r/ link
+// gets it, an existing lsclk is never replaced, an unparsable target goes out unchanged), the click rows pushed with a valid
+// signature and the contract fields, the owner's own click flagged self=1 and not counted, the proxies, the Campaigns pane
+// showing goals and cost per goal (300 credits / 4 = 75), LinkSpin down: pane still loads, panel says so, rows kept and
+// pushed once it is back. Exit code 1 on any failure.
+import http from 'node:http';
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const SITE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
+const PORT = Number(process.env.CONV_PORT || 8831), MPORT = PORT + 1;
+const B = 'http://127.0.0.1:' + PORT, MOCK = 'http://127.0.0.1:' + MPORT;
+const SECRET = 'qa-convpixel-' + crypto.randomBytes(24).toString('hex'); // throwaway, 32+ chars
+const ADMIN = 'localtest';
+const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-conv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
+const OUT = path.join(SITE, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
+let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (!cond && extra ? ' ' + extra : '')); if (!cond) fails++; };
+const sleep = ms => new Promise(r => setTimeout(r, ms));
+async function waitFor(fn, ms) { const t0 = Date.now(); while (Date.now() - t0 < (ms || 15000)) { try { const v = await fn(); if (v) return v; } catch (e) {} await sleep(400); } return null; }
+
+// ---- seed: two advertisers, campaigns with every target shape ----
+const now = Date.now();
+const acct = (email, username, code) => ({ email, pass: null, sponsorRef: '', code, username, address: null, created: now - 5 * 86400000, lastSeen: now - 3600000, memberId: 0 });
+const A1 = 'qa-adv@example.com', A2 = 'qa-adv2@example.com';
+{ const db = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: 0, positions: {} };
+ for (const a of [acct(A1, 'qaadv', 'cqaadv1'), acct(A2, 'qaadvtwo', 'cqaadv2')]) { db.byEmail[a.email] = a; db.byCode[a.code] = a.email; }
+ fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(db)); }
+const camp = (id, owner, name, targetUrl, spent) => ({ id, owner, memberId: 0, type: 'banner', name, targetUrl, imageUrl: 'https://example.com/b.png', title: null, body: null,
+ budget: 1000, spent, accrued: 0, imps: 50, clicks: 0, batchImps: 0, width: 468, height: 60, status: 'paused', created: now - 86400000 });
+const T1 = 'https://adv.example/landing?utm_source=iap&x=a%2Cb&q=hello+world#top';
+const CAMPS = [camp(1, A1, 'QA landing', T1, 300), camp(2, A1, 'QA spin link', 'https://linkspin.app/r/abc12', 120),
+ camp(3, A1, 'QA has lsclk', 'https://adv.example/p?lsclk=keepme', 0), camp(4, A1, 'QA odd target', 'adv.example/no-scheme', 0), camp(5, A2, 'QA other', 'https://other.example/', 50)];
+fs.writeFileSync(path.join(DATA, 'campaigns.json'), JSON.stringify({ v: 1, nextId: 6, campaigns: CAMPS, burnsPending: [] }));
+
+// ---- mock LinkSpin ----
+const PX1 = 'px0123456789', PX2 = 'pxabcdef0123';
+const mock = { clicks: new Map(), badSig: 0, calls: [], down: false, goals: { [A1]: [{ px: PX1, name: 'subscriber', value: null, created: now - 86400000, conv: 6, convDays: 6, lastAt: now - 3600000, lastTest: null }, { px: PX2, name: 'sale', value: 19.95, created: now - 86400000, conv: 1, convDays: 1, lastAt: now - 7200000, lastTest: null }] } };
+const verify = (ts, sig, raw) => { if (!ts || !sig || Math.abs(Date.now() - Number(ts)) > 300000) return false; const want = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex'); return want.length === String(sig).length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(String(sig))); };
+const send = (res, code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); };
+function mockHandler(req, res) {
+ let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
+ if (mock.down) { res.writeHead(503); return res.end('down'); }
+ if (req.method !== 'POST') return send(res, 404, { error: 'not found' });
+ if (!verify(req.headers['x-ls-ts'], req.headers['x-ls-sig'], raw)) { mock.badSig++; return send(res, 401, { error: 'bad signature' }); }
+ const b = JSON.parse(raw || '{}');
+ if (req.url === '/api/partner/clicks') { for (const c of b.clicks || []) mock.clicks.set(c.id, c); return send(res, 200, { ok: true, n: (b.clicks || []).length }); }
+ if (req.url === '/api/partner/conv') {
+ mock.calls.push(b); const email = String(b.email || '');
+ const goals = mock.goals[email] || (mock.goals[email] = []);
+ if (b.op === 'summary') return send(res, 200, { ok: true, goals, byCampaign: email === A1 ? { 1: { clicks: 9, conv: { [PX1]: 4, [PX2]: 1 }, value: { [PX2]: 19.95 } }, 2: { clicks: 3, conv: {} } } : {}, methods: { url: 2, stored: 2, cookie: 1, soft: 1 }, host: 'linkspin.app' });
+ if (b.op === 'create') { const g = { px: 'px' + crypto.randomBytes(5).toString('hex'), name: b.name, value: b.value == null ? null : b.value, created: Date.now(), conv: 0, convDays: 0, lastAt: null, lastTest: null }; goals.push(g); return send(res, 200, { ok: true, goal: g }); }
+ if (b.op === 'remove') { const i = goals.findIndex(g => g.px === b.px); if (i < 0) return send(res, 404, { error: 'No such goal.' }); goals.splice(i, 1); return send(res, 200, { ok: true }); }
+ if (b.op === 'test') { const g = goals.find(x => x.px === b.px); if (!g) return send(res, 404, { error: 'No such goal.' }); g.lastTest = Date.now(); return send(res, 200, { ok: true, at: g.lastTest }); }
+ return send(res, 400, { error: 'unknown op' });
+ }
+ return send(res, 404, { error: 'not found' }); // registry sync and anything else: ignored
+ });
+}
+let mockSrv = http.createServer(mockHandler); await new Promise(r => mockSrv.listen(MPORT, '127.0.0.1', r));
+
+// ---- the local copy, minimal environment (no live secrets can ride along) ----
+const ENV = {};
+for (const k of ['PATH', 'Path', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'COMSPEC', 'windir']) if (process.env[k]) ENV[k] = process.env[k];
+Object.assign(ENV, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, DATABASE_URL: '', LS_SYNC_SECRET: SECRET, LS_URL: MOCK });
+const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, env: ENV, stdio: ['ignore', 'pipe', 'pipe'] });
+let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
+let browser = null;
+const cleanup = async () => { try { if (browser) await browser.close(); } catch (e) {} try { srv.kill(); } catch (e) {} try { mockSrv.close(); } catch (e) {} await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
+
+try {
+ const up = await waitFor(async () => (await fetch(B + '/api/config')).ok, 30000);
+ if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
+ const api = async (p, body, hdr) => { const r = await fetch(B + p, { method: body ? 'POST' : 'GET', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: body ? JSON.stringify(body) : undefined }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
+ const click = async (id, hdr) => { const r = await fetch(B + '/api/ads/click/' + id, { redirect: 'manual', headers: Object.assign({ 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148', Referer: 'https://instantadpay.com/ledger?secret=1' }, hdr || {}) }); return { status: r.status, loc: r.headers.get('location') }; };
+ async function signIn(email) {
+ const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000, fage: 5000 });
+ const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
+ return (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
+ }
+ const ID = /lsclk=(i[0-9a-f]{11})(?=$|[])/;
+
+ // 1. click ids on the redirect
+ const c1 = await click(1);
+ const id1 = (ID.exec(c1.loc || '') || [])[1];
+ ok(c1.status === 302 && !!id1, 'click -> 302 with lsclk=i+11 hex', c1.status + ' ' + c1.loc);
+ ok(c1.loc === 'https://adv.example/landing?utm_source=iap&x=a%2Cb&q=hello+world&lsclk=' + id1 + '#top', 'existing params kept byte for byte, lsclk before the #hash', c1.loc);
+ const c2 = await click(2); const id2 = (ID.exec(c2.loc || '') || [])[1];
+ ok(!!id2 && c2.loc === 'https://linkspin.app/r/abc12?lsclk=' + id2, 'a LinkSpin /r/ spin link gets lsclk', c2.loc);
+ const c3 = await click(3);
+ ok(c3.loc === 'https://adv.example/p?lsclk=keepme', 'an existing lsclk is never replaced', c3.loc);
+ const c4 = await click(4);
+ ok(c4.status === 302 && c4.loc === 'adv.example/no-scheme', 'an unparsable target redirects unchanged', c4.status + ' ' + c4.loc);
+ const c1b = await click(1); const id1b = (ID.exec(c1b.loc || '') || [])[1];
+ ok(id1b && id1b !== id1, 'every click gets its own id');
+
+ // 2. pushed to the mock, signed, with the contract fields
+ const got = await waitFor(() => mock.clicks.has(id1) && mock.clicks.has(id2) && mock.clicks.has(id1b), 15000);
+ ok(!!got, 'click rows pushed to LinkSpin /api/partner/clicks within ~3 s', [...mock.clicks.keys()].join(','));
+ ok(mock.badSig === 0, 'every push carried a valid HMAC signature', 'bad: ' + mock.badSig);
+ const r1 = mock.clicks.get(id1) || {};
+ ok(r1.camp === 1 && r1.cname === 'QA landing' && r1.type === 'banner' && r1.owner === A1, 'row: camp, cname, type, owner', JSON.stringify(r1));
+ ok(r1.spent === 300 && r1.self === 0 && r1.target === T1, 'row: spent 300, self 0, target', JSON.stringify(r1));
+ ok(/^s:[0-9a-f]{20}$/.test(r1.sk || '') && r1.dv === 'mobile' && r1.pl === 'instantadpay.com/ledger' && Math.abs(r1.ts - Date.now()) < 120000, 'row: soft key, device, placement (query dropped), ts', JSON.stringify(r1));
+ const ip = '127.0.0.1', ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148';
+ const sks = ['s:' + crypto.createHash('sha256').update(ip + '|' + ua).digest('hex').slice(0, 20), 's:' + crypto.createHash('sha256').update('::ffff:127.0.0.1|' + ua).digest('hex').slice(0, 20)];
+ ok(sks.includes(r1.sk), 'soft key = sha256(ip|ua) first 20 hex, no raw IP in the row', r1.sk);
+ ok(!JSON.stringify([...mock.clicks.values()]).includes('127.0.0.1'), 'no raw IP anywhere in the pushed rows');
+ ok(!mock.clicks.has('keepme') && [...mock.clicks.values()].filter(r => r.camp === 3).length === 1, 'the click on the lsclk target is still recorded (its own id), the URL untouched');
+
+ // 3. the owner's own click: still an id, flagged self, not counted as a click
+ const ck1 = await signIn(A1);
+ const before = (await api('/api/my/campaigns', null, { Cookie: ck1 })).j;
+ const clicksBefore = ((before && before.campaigns) || []).find(c => c.id === 1);
+ const own = await click(1, { Cookie: ck1 }); const idOwn = (ID.exec(own.loc || '') || [])[1];
+ ok(!!idOwn, 'own click still gets a click id (so the owner can test)', own.loc);
+ ok(!!(await waitFor(() => mock.clicks.get(idOwn), 10000)) && mock.clicks.get(idOwn).self === 1, 'own click pushed with self=1', JSON.stringify(mock.clicks.get(idOwn)));
+ const after = (await api('/api/my/campaigns', null, { Cookie: ck1 })).j;
+ const clicksAfter = ((after && after.campaigns) || []).find(c => c.id === 1);
+ ok(clicksBefore && clicksAfter && clicksAfter.clicks === clicksBefore.clicks && clicksBefore.clicks === 2, 'own click not counted (clicks stay 2)', JSON.stringify([clicksBefore && clicksBefore.clicks, clicksAfter && clicksAfter.clicks]));
+
+ // 4. proxies
+ const sum = await api('/api/my/conversions', null, { Cookie: ck1 });
+ ok(sum.j && sum.j.ok === true && sum.j.goals.length === 2 && sum.j.byCampaign['1'].conv[PX1] === 4, 'GET /api/my/conversions relays the LinkSpin summary', JSON.stringify(sum.j).slice(0, 200));
+ const lastSum = mock.calls.filter(c => c.op === 'summary').pop();
+ ok(lastSum && lastSum.email === A1 && lastSum.days === 30, 'summary asked for the signed-in email, 30 days', JSON.stringify(lastSum));
+ const nSum = mock.calls.filter(c => c.op === 'summary').length; await api('/api/my/conversions', null, { Cookie: ck1 });
+ ok(mock.calls.filter(c => c.op === 'summary').length === nSum, 'summary cached (second call within 60 s does not hit LinkSpin)');
+ ok((await api('/api/my/conversions')).status === 401, 'signed out: 401');
+ const bad = await api('/api/my/conversions/goal', { op: 'create', name: ' ' }, { Cookie: ck1 });
+ ok(bad.status === 400, 'create without a name refused locally');
+ const cr = await api('/api/my/conversions/goal', { op: 'create', name: 'Free Report', value: '7.5' }, { Cookie: ck1 });
+ ok(cr.j && cr.j.ok && cr.j.goal && /^px[0-9a-f]{10}$/.test(cr.j.goal.px) && cr.j.goal.name === 'free-report' && cr.j.goal.value === 7.5, 'create relays op create (name normalized, value number)', JSON.stringify(cr.j));
+ const ts = await api('/api/my/conversions/test', { px: cr.j && cr.j.goal && cr.j.goal.px }, { Cookie: ck1 });
+ ok(ts.j && ts.j.ok && ts.j.at, 'test relays op test', JSON.stringify(ts.j));
+ const rm = await api('/api/my/conversions/goal', { op: 'remove', px: cr.j && cr.j.goal && cr.j.goal.px }, { Cookie: ck1 });
+ ok(rm.j && rm.j.ok, 'remove relays op remove');
+ const rm2 = await api('/api/my/conversions/goal', { op: 'remove', px: 'px9999999999' }, { Cookie: ck1 });
+ ok(rm2.status === 400 && rm2.j && rm2.j.error === 'No such goal.', 'LinkSpin plain-words error passed through as 400', JSON.stringify(rm2));
+ ok(mock.calls.every(c => c.email === A1), 'every conv call carried only the signed-in email');
+
+ // 5. the Campaigns pane in a real browser
+ const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
+ const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
+ browser = await chromium.launch();
+ async function pane(cookie, shot) {
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } });
+ await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
+ const [k, v] = cookie.split(';')[0].split('='); await ctx.addCookies([{ name: k, value: v, url: B }]);
+ const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
+ await page.goto(B + '/my', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2500);
+ await page.evaluate(() => { document.querySelectorAll('.modal-back,.lgate,.iap-welcome').forEach(m => m.hidden = true); });
+ await page.click('.bo-menu [data-pane="campaigns"]'); await page.waitForTimeout(2500);
+ const st = await page.evaluate(() => ({
+ rows: document.querySelectorAll('#campList .camp-table tbody tr').length,
+ line1: (document.querySelector('[data-convcamp="1"]') || {}).textContent || '', line1Hidden: !!(document.querySelector('[data-convcamp="1"]') || {}).hidden,
+ line5Hidden: (document.querySelector('[data-convcamp="5"]') || { hidden: true }).hidden,
+ card: !document.getElementById('convCard').hidden, status: document.getElementById('convStatus').textContent,
+ goals: document.querySelectorAll('#convGoals tbody tr').length, landing: (document.getElementById('convLanding') || {}).value || '', img: (document.getElementById('convImg') || {}).value || '',
+ js: (document.getElementById('convJs') || {}).value || '', tip: document.getElementById('convCard').textContent }));
+ await page.screenshot({ path: path.join(OUT, shot), fullPage: true }).catch(() => {});
+ await ctx.close(); return { st, errs };
+ }
+ const p1 = await pane(ck1, 'convpixel-pane.png');
+ ok(p1.st.rows >= 4 && p1.st.card, 'Campaigns pane loads with the Conversion tracking card', JSON.stringify(p1.st).slice(0, 200));
+ ok(!p1.st.line1Hidden && /subscriber 4 \(75 credits each\)/.test(p1.st.line1) && /sale 1 \(300 credits each\)/.test(p1.st.line1), 'campaign row shows goals + cost per goal (300 / 4 = 75 credits)', p1.st.line1);
+ ok(!/\$/.test(p1.st.line1), 'cost per goal is in credits, never dollars');
+ ok(p1.st.goals === 2 && p1.st.landing === '', 'goal list + landing tag snippet', p1.st.landing);
+ ok(p1.st.img === '
' && p1.st.js === '', 'goal pixel image + JS snippets match the contract', p1.st.img + ' | ' + p1.st.js);
+ ok(/Thank You Page: custom page/.test(p1.st.tip) && /Thank-you page: custom URL/.test(p1.st.tip) && /24-hour match/.test(p1.st.tip), 'autoresponder advice + match legend present');
+ ok(/url 2, stored 2, cookie 1, soft 1/.test(p1.st.status), 'match methods line', p1.st.status);
+ ok(!p1.errs.length, 'no page errors', p1.errs.join(' | '));
+
+ // 6. LinkSpin down: the pane still loads, the panel says so, campaign rows omit the goal line; clicks are kept and pushed later
+ mock.down = true;
+ const ck2 = await signIn(A2);
+ const down = await api('/api/my/conversions', null, { Cookie: ck2 });
+ ok(down.j && down.j.ok === false && down.j.reason === 'down' && /did not answer/.test(down.j.error), 'proxy says LinkSpin is down in plain words', JSON.stringify(down.j));
+ const p2 = await pane(ck2, 'convpixel-down.png');
+ ok(p2.st.rows >= 1 && p2.st.card && /did not answer/.test(p2.st.status) && p2.st.line5Hidden, 'LinkSpin down: Campaigns pane still loads, no goal line, panel explains', JSON.stringify(p2.st).slice(0, 220));
+ ok(!p2.errs.length, 'no page errors while LinkSpin is down', p2.errs.join(' | '));
+ const cd = await click(5); const idDown = (ID.exec(cd.loc || '') || [])[1];
+ ok(!!idDown, 'clicks still get ids while LinkSpin is down');
+ await sleep(4000);
+ ok(!mock.clicks.has(idDown), 'nothing marked pushed while LinkSpin refuses');
+ mock.down = false;
+ ok(!!(await waitFor(() => mock.clicks.has(idDown), 30000)), 'row kept and pushed once LinkSpin is back (retry with backoff)');
+ const adm = await api('/api/admin/lssync', null, { Authorization: 'Bearer ' + ADMIN });
+ ok(adm.j && adm.j.conv && adm.j.conv.on === true && adm.j.conv.pushed >= 5, 'admin lssync view carries conv push stats', JSON.stringify(adm.j && adm.j.conv));
+} catch (e) { ok(false, 'run', e.stack); }
+finally {
+ await cleanup();
+ fs.writeFileSync(path.join(OUT, 'convpixel-server.log'), srvLog);
+ console.log(fails ? fails + ' FAILED' : 'all passed');
+ process.exit(fails ? 1 : 0);
+}
diff --git a/qa/run.sh b/qa/run.sh
index cb6a028..dcb7c6d 100644
--- a/qa/run.sh
+++ b/qa/run.sh
@@ -12,6 +12,7 @@
# bash qa/run.sh login-queue # prepaid login-ad line: JSON store end to end + the MySQL path's lease/guard logic against a fake SQL layer (no server, throwaway data)
# bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos)
# bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, throwaway data)
+# bash qa/run.sh convpixel # conversion pixel: lsclk click ids on /api/ads/click, signed push to a MOCK LinkSpin, own-click self flag, Campaigns > Conversion tracking + cost per goal, LinkSpin down (local copy, throwaway data)
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
set -u
@@ -54,6 +55,8 @@ elif [ "$MODE" = "sov-passes" ]; then
elif [ "$MODE" = "login-queue" ]; then
node qa/login-queue.cjs || status=1
node qa/login-queue-sql.cjs || status=1
+elif [ "$MODE" = "convpixel" ]; then
+ node qa/convpixel.test.mjs || status=1
elif [ "$MODE" = "override" ]; then
node qa/override.test.cjs || status=1
elif [ "$MODE" = "gamepass-games" ]; then