Files
linkspin/qa/convpixel.test.mjs
martbost 98e3ed36d8 Conversion tracking fixes (Marty approved 2026-10-26): own clicks are tests on every click type, Banner Spin straight-to-page clicks carry lsclk
1. Own clicks: a goal owner's own click on ANY click type (LinkSpin/InstantAdPay ads, spin links, Banner Spins) is kept as a test, never counted, never fires a goal postback. Own = ad click flagged self for that owner, a spin-link / Banner Spin click marked at click time (signed in as the owner, or from an owner soft key: markOwnClick in server.js), or the clicking or converting browser's soft key is one the owner signs in from. auth.onSeen notes LinkSpin session soft keys (throttled, kept 31 days in convtrack.json S.own); /api/partner/clicks takes owners [{owner, sk, ts}] from InstantAdPay before the clicks, so IAP members' own browsers are known too. Linked positions share the owner's email. X-LS-Result adds ;self. partnerSummary returns selfTests for the IAP card. Conversions screen copy: test with Send a test conversion and the &test=1 page check, own clicks never count (conversions.js ?v=20261026a).
3. Banner Spin: a click whose target is a direct page (not a /r/ spin link) gets ?lsclk=<k click id> when the owner tracks goals (string insert like lsconv.withClickId: params kept, before #hash, an existing lsclk never replaced). convtrack.lookup resolves k ids through bannerspin.clickById; conversions record k:'bspin' with the Banner Spin, banner, page and source; report By Banner Spin, CSV site 'Banner Spin', postback ctx with its sub ids.
Guides: /conversion-tracking (Banner Spin straight to a page now counted, own clicks on every type are tests, By Banner Spin), /refuel tile. Chatbot CANNED + FACTS, KNOWLEDGE_DATE 2026-10-26.
QA: convpixel 77/77 (new: owner soft keys, own ad/spin/Banner Spin/IAP clicks as tests, stranger still counts, own-browser conversion, withClickId, Banner Spin lsclk + By Banner Spin + spin-link banner untouched, selfTests in the IAP summary, no postback for own clicks); lsid 31/31; fuel all pass (engine.js / engine-room.js / kit.js untouched, byte-identical with InstantAdPay); bannerspin 75/75; member walk 0 bugs; public 0 bugs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 06:19:54 -05:00

324 lines
33 KiB
JavaScript

// Conversion pixel (2026-10-23, Marty approved). Three parts, all on throwaway data (no production data, no real members):
// 1) unit: convtrack.js on a temp dir: 30-day window, per-IP rate limit, owner check, InstantAdPay click import rules.
// 2) end to end on a local server.js (JSON store, no DB, no mail key, devCode sign-in, test LS_SYNC_SECRET, seeded
// campaigns.json): ad click -> click id on the target -> goal pixel counts once with method url / stored / cookie /
// soft; dedupe; owner mismatch refused; spin link reached through an ad inherits the ad; cost per goal; goal postback
// attempted (an .invalid host, nothing leaves the machine); InstantAdPay clicks + summary over the signed partner call;
// self click kept as a test; test conversion; CSV. 2026-10-26: own clicks are tests on every click type (owner soft
// key from a session, signed-in clicks on spin links and Banner Spins, a goal finished in the owner's browser, InstantAdPay
// owners pushed with the clicks); Banner Spin straight to a page carries lsclk and reports By Banner Spin.
// 3) browser (Playwright, if present): the landing tag on another origin keeps the id, fills a hidden lsclk field and
// decorates same-site links; the script goal pixel on the thank-you page counts with method 'stored', also framed.
// node qa/convpixel.test.mjs (from the site dir; no internet needed) Env: PORT (default 8973), PW
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import crypto from 'node:crypto';
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
const require = createRequire(import.meta.url);
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const PORT = Number(process.env.PORT || 8973), PORT2 = PORT + 1;
const SECRET = 'qa-secret-' + crypto.randomBytes(16).toString('hex');
const results = []; let failed = 0;
const check = (ok, what, detail) => { results.push((ok ? 'PASS ' : 'FAIL ') + what + (detail ? ' :: ' + detail : '')); if (!ok) failed++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const DAY = 86400000;
// ---------- 1) unit ----------
{
const UD = fs.mkdtempSync(path.join(os.tmpdir(), 'cv-unit-'));
const C = require(path.join(site, 'convtrack.js'));
C.init({ dataDir: UD, noTimers: true, rotator: null });
const fake = (ip, ua) => ({ headers: { 'user-agent': ua || 'UnitUA', 'x-forwarded-for': ip }, socket: {} });
const g = C.createGoal('own@u.test', { name: 'Sale', value: '12.5' });
check(g.ok && /^px[a-f0-9]{10}$/.test(g.goal.px) && g.goal.name === 'sale' && g.goal.value === 12.5, 'goal created: pixel id, name lowercased, value kept', JSON.stringify(g));
check(!!C.createGoal('own@u.test', { name: 'sale' }).error && !!C.createGoal('own@u.test', { name: 'bad name!' }).error, 'duplicate and bad goal names refused');
const px = g.goal.px;
const id = C.recordAdClick({ id: 7, owner: 'own@u.test', name: 'Unit ad', type: 'banner', targetUrl: 'https://x.test/' }, fake('192.0.2.1'), { country: 'US' });
check(/^a[a-f0-9]{11}$/.test(id), 'LinkSpin ad click id format a + 11 hex', id);
// 30-day window: age the click to 31 days
C.lookup(id).ad.ts = Date.now() - 31 * DAY;
let r = C.record({ px, c: id, m: 'url' }, fake('192.0.2.50'), {});
check(r.result === 'nomatch', 'a click older than 30 days does not count', JSON.stringify(r));
C.lookup(id).ad.ts = Date.now() - 29 * DAY;
r = C.record({ px, c: id, m: 'url' }, fake('192.0.2.50'), {});
check(r.result === 'counted' && r.method === 'url', 'the same click at 29 days counts', JSON.stringify(r.result));
check(C.record({ px, c: id, m: 'url' }, fake('192.0.2.50'), {}).result === 'dup', 'counted once per click');
// owner check: someone else's click never counts for this pixel
const other = C.recordAdClick({ id: 8, owner: 'else@u.test', name: 'Other', type: 'banner', targetUrl: 'https://y.test/' }, fake('192.0.2.2'), {});
check(C.record({ px, c: other, m: 'url' }, fake('192.0.2.51'), {}).result === 'refused', "someone else's click is refused");
// InstantAdPay import rules
const now = Date.now();
const n = C.importClicks([{ id: 'i0123456789a', camp: 5, owner: 'Own@U.test', ts: now, sk: 's:' + 'a'.repeat(20), spent: 90 }, { id: 'bad', owner: 'x@y.z', ts: now }, { id: 'i0123456789b', camp: 5, owner: 'own@u.test', ts: now - 40 * DAY }]);
check(n === 1 && C.lookup('i0123456789a') && C.lookup('i0123456789a').owners[0] === 'own@u.test', 'IAP clicks import: good row in (owner lowercased), bad id and >30-day rows dropped', String(n));
check(C.importClicks([{ id: 'i0123456789a', camp: 5, owner: 'own@u.test', ts: now, spent: 120 }]) === 1 && Object.keys(C.lookup('i0123456789a') ? { a: 1 } : {}).length === 1, 'the same IAP click sent twice is an upsert, not a second click');
// per-IP rate limit (20 a minute)
let limited = 0; for (let i = 0; i < 25; i++) if (C.record({ px, c: 'nosuchclick1' }, fake('192.0.2.99'), {}).result === 'limited') limited++;
check(limited === 5, 'per-visitor rate limit: 20 a minute, the rest refused', limited + ' limited');
check(C.record({ px: 'px0000000000', c: id }, fake('192.0.2.98'), {}).result === 'unknown', 'unknown pixel id ignored');
// fix 1 (2026-10-26): own clicks are tests on every click type. The owner is seen signed in from 192.0.2.7 + OwnerUA.
const ownReq = fake('192.0.2.7', 'OwnerUA');
check(C.noteSession('Own@U.test', ownReq) && C.isOwnerSk('own@u.test', C.softKey(ownReq)) && !C.isOwnerSk('else@u.test', C.softKey(ownReq)), 'owner soft key noted from a session (email lowercased), not shared with another owner');
const idOwnSk = C.recordAdClick({ id: 7, owner: 'own@u.test', name: 'Unit ad', type: 'banner', targetUrl: 'https://x.test/' }, ownReq, {});
check(C.lookup(idOwnSk).ad.self === 1, "an ad click from the owner's browser is flagged self even when not signed in");
r = C.record({ px, c: idOwnSk, m: 'url' }, fake('192.0.2.60'), {});
check(r.result === 'counted' && r.conv.self === 1, 'its conversion is kept as a test (self)', JSON.stringify(r.result));
const idStr = C.recordAdClick({ id: 7, owner: 'own@u.test', name: 'Unit ad', type: 'banner', targetUrl: 'https://x.test/' }, fake('192.0.2.61', 'StrangerUA'), {});
r = C.record({ px, c: idStr, m: 'url' }, ownReq, {});
check(r.result === 'counted' && r.conv.self === 1, "a stranger's click converted from the owner's own browser is a test too", JSON.stringify(r.result));
const idStr2 = C.recordAdClick({ id: 7, owner: 'own@u.test', name: 'Unit ad', type: 'banner', targetUrl: 'https://x.test/' }, fake('192.0.2.62', 'StrangerUA'), {});
r = C.record({ px, c: idStr2, m: 'url' }, fake('192.0.2.63', 'StrangerUA'), {});
check(r.result === 'counted' && !r.conv.self, "a stranger's click and conversion still count", JSON.stringify(r.conv && r.conv.self));
const skI = 's:' + 'b'.repeat(20);
check(C.importOwners([{ owner: 'Own@U.test', sk: skI, ts: Date.now() }, { owner: 'x@y.z', sk: 'nope' }]) === 1 && C.isOwnerSk('own@u.test', skI), 'InstantAdPay owner soft keys import (bad rows dropped)');
C.importClicks([{ id: 'i0123456789c', camp: 5, owner: 'own@u.test', ts: Date.now(), sk: skI, self: 0 }]);
check(C.lookup('i0123456789c').ad.self === 1, "an InstantAdPay click from the owner's InstantAdPay browser imports as self");
check(C.markSelfClick('abcdef0123', 'own@u.test', ownReq, '') && C.markSelfClick('abcdef0124', 'own@u.test', fake('192.0.2.64', 'Other'), 'OWN@u.test') && !C.markSelfClick('abcdef0125', 'own@u.test', fake('192.0.2.65', 'Other'), 'else@u.test'), 'spin / Banner Spin clicks marked self by owner soft key or owner session, not by someone else');
// withClickId: the string insert lsconv uses
check(C.withClickId('https://a.test/p?utm=x&q=a%2Cb#top', 'k0123456789a') === 'https://a.test/p?utm=x&q=a%2Cb&lsclk=k0123456789a#top' && C.withClickId('https://a.test/p?lsclk=keep', 'k0123456789a') === 'https://a.test/p?lsclk=keep'
&& C.withClickId('https://a.test', 'k0123456789a') === 'https://a.test?lsclk=k0123456789a' && C.withClickId('not a url', 'k0123456789a') === 'not a url', 'withClickId: params kept byte for byte, before the #hash, an lsclk never replaced, bad URL unchanged');
fs.rmSync(UD, { recursive: true, force: true });
}
// ---------- 2) end to end ----------
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'cv-qa-'));
fs.mkdirSync(path.join(DATA, 'uploads'));
const A = 'convmember@lp.test', B = 'someoneelse@lp.test';
const camp = (id, owner, name, targetUrl, spent) => ({ id, owner, memberId: 0, type: 'banner', name, targetUrl, imageUrl: 'https://img.qa.invalid/b.png', title: null, body: null, width: 728, height: 90, budget: 1000, spent, accrued: 0, imps: 0, clicks: 0, batchImps: 0, status: 'active', created: Date.now() });
fs.writeFileSync(path.join(DATA, 'campaigns.json'), JSON.stringify({ v: 1, nextId: 4, burnsPending: [], campaigns: [
camp(1, A, 'QA banner', 'https://landing.qa.test/page?x=1', 300), camp(2, B, 'Other banner', 'https://other.qa.test/', 50), camp(3, A, 'QA to spin', 'https://landing.qa.test/spin-placeholder', 40)] }));
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'localtest-cv', ADMIN_EMAIL: 'admin@cv.test', SITE_HOST: 'linkspin.test', LS_SYNC_SECRET: SECRET, IAP_URL: 'http://127.0.0.1:9/' });
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_API_KEY', 'OPENROUTER_API_KEY']) delete env[k];
const logFile = path.join(DATA, 'server.log'); const log = fs.createWriteStream(logFile);
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'pipe', 'pipe'] });
srv.stdout.pipe(log); srv.stderr.pipe(log);
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ConvQA';
function req(method, p, o) {
o = o || {};
return new Promise((resolve, reject) => {
const headers = Object.assign({ 'User-Agent': o.ua || UA }, o.headers || {});
if (o.cookie) headers.Cookie = o.cookie; if (o.ip) headers['X-Forwarded-For'] = o.ip;
let body = o.raw != null ? Buffer.from(o.raw) : o.body; if (body && !Buffer.isBuffer(body)) { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; } else if (body) headers['Content-Type'] = headers['Content-Type'] || 'application/json';
if (body) headers['Content-Length'] = body.length;
const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, text: buf.toString(), json: j }); }); });
r.on('error', reject); if (body) r.write(body); r.end();
});
}
const signed = (p, obj, secret) => { const raw = JSON.stringify(obj); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', secret || SECRET).update(ts + '\n' + raw).digest('hex'); return req('POST', p, { raw, headers: { 'X-LS-Ts': ts, 'X-LS-Sig': sig, 'Content-Type': 'application/json' } }); };
const softKey = (ip, ua) => 's:' + crypto.createHash('sha256').update(ip + '|' + ua).digest('hex').slice(0, 20);
const res = r => String(r.headers['x-ls-result'] || '');
const lsclkOf = loc => (/[?&]lsclk=([a-z0-9]+)/i.exec(String(loc || '')) || [])[1] || '';
let browserPart = null;
async function signIn(email, ip) {
const st = await req('POST', '/api/auth/email/start', { ip, body: { email, fts: Date.now() - 8000, hp_field_x9: '', pick: null } });
if (!st.json || !st.json.devCode) throw new Error('no devCode: ' + st.text.slice(0, 200));
const v = await req('POST', '/api/auth/email/verify', { ip, body: { email, code: st.json.devCode } });
return [].concat(v.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; ');
}
try {
let up = false; for (let i = 0; i < 60; i++) { try { const r = await req('GET', '/api/config'); if (r.status === 200) { up = true; break; } } catch (e) {} await sleep(500); }
if (!up) throw new Error('server did not come up');
const cA = await signIn(A, '10.77.0.1');
check(!!cA, 'member signed in on the local copy');
const g1 = await req('POST', '/api/my/conversions/goals', { cookie: cA, body: { name: 'subscriber', value: '5' } });
check(g1.status === 200 && g1.json.goal && /^px[a-f0-9]{10}$/.test(g1.json.goal.px), 'goal "subscriber" created in the Control Room API', g1.text.slice(0, 160));
const PX = g1.json.goal.px;
const pb = await req('POST', '/api/my/postbacks', { cookie: cA, body: { name: 'QA goal tracker', url: 'https://tracker.qa.invalid/pb?cid={clickid}&e={event}&ls={lsid}&v={payout}', events: ['goal'] } });
check(pb.status === 200, "postback listening to 'goal' created (an .invalid host)", pb.text.slice(0, 160));
// method url: an ad click, then the pixel with the id from the thank-you page's address
const k1 = await req('GET', '/api/ads/click/1', { ip: '203.0.113.21' });
const id1 = lsclkOf(k1.headers.location);
check(k1.status === 302 && /^a[a-f0-9]{11}$/.test(id1) && /[?&]x=1/.test(k1.headers.location) && /^https:\/\/landing\.qa\.test\/page\?/.test(k1.headers.location), 'ad click: 302 to the target with lsclk added and its own params kept', k1.headers.location);
check(/ls\.clk=/.test(String(k1.headers['set-cookie'] || '')), 'ad click sets the ls.clk cookie');
let r = await req('GET', '/cv.gif?px=' + PX + '&goal=subscriber&c=' + id1 + '&m=url', { ip: '198.18.0.1', headers: { Referer: 'https://landing.qa.test/thanks' } });
check(r.status === 200 && r.headers['content-type'] === 'image/gif' && res(r) === 'counted;url', "goal pixel from the member's own domain counts with method 'url'", res(r));
r = await req('GET', '/cv.gif?px=' + PX + '&goal=subscriber&c=' + id1 + '&m=url', { ip: '198.18.0.1' });
check(res(r) === 'dup;url', 'the same click and goal again: not counted twice', res(r));
// method stored
const id2 = lsclkOf((await req('GET', '/api/ads/click/1', { ip: '203.0.113.22' })).headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + id2 + '&m=stored', { ip: '198.18.0.2' });
check(res(r) === 'counted;stored', "id the landing tag kept counts with method 'stored'", res(r));
// method cookie: no id on the pixel, LinkSpin's own cookie carries it
const id3 = lsclkOf((await req('GET', '/api/ads/click/1', { ip: '203.0.113.23' })).headers.location);
r = await req('GET', '/cv.gif?px=' + PX, { ip: '198.18.0.3', cookie: 'ls.clk=' + id3 });
check(res(r) === 'counted;cookie', "no id on the page, LinkSpin cookie: method 'cookie'", res(r));
// method soft: same IP + browser within 24 h, nothing else
const ip4 = '203.0.113.24', ua4 = 'Mozilla/5.0 SoftMatch QA';
const id4 = lsclkOf((await req('GET', '/api/ads/click/1', { ip: ip4, ua: ua4 })).headers.location);
r = await req('GET', '/cv.gif?px=' + PX, { ip: ip4, ua: 'Mozilla/5.0 Different browser' });
check(res(r) === 'nomatch', 'a different browser on that network does not match', res(r));
r = await req('GET', '/cv.gif?px=' + PX, { ip: ip4, ua: ua4 });
check(res(r) === 'counted;soft' && !!id4, "same IP + browser within 24 h: method 'soft'", res(r));
// owner mismatch: B's ad click, A's pixel
const idB = lsclkOf((await req('GET', '/api/ads/click/2', { ip: '203.0.113.25' })).headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + idB + '&m=url', { ip: '198.18.0.5' });
check(res(r) === 'refused', "a click on someone else's ad is refused by this pixel", res(r));
r = await req('GET', '/cv.gif?px=px0123456789&c=' + id1, { ip: '198.18.0.6' });
check(res(r) === 'unknown' && r.status === 200, 'unknown pixel id: still a gif, nothing recorded', res(r));
// a spin link reached through an ad: the rotator passes a click id on and the conversion credits both
const rc = await req('POST', '/api/my/rotations', { cookie: cA, body: { name: 'Conv QA spin' } });
const rot = rc.json.rotation;
await req('POST', '/api/my/rotations/' + rot.id + '/dest', { cookie: cA, body: { url: 'https://landing.qa.test/lp?y=2', weight: 1 } });
const id5 = lsclkOf((await req('GET', '/api/ads/click/3', { ip: '203.0.113.26' })).headers.location);
const sp = await req('GET', '/r/' + rot.code + '?lsclk=' + id5, { ip: '203.0.113.26' });
const sid = lsclkOf(sp.headers.location);
check(sp.status === 302 && /^[a-f0-9]{10}$/.test(sid) && sid !== id5 && /[?&]y=2/.test(sp.headers.location), 'spin link reached through an ad: destination gets the spin click id (lsclk), its params kept', sp.headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + sid + '&m=stored', { ip: '198.18.0.7' });
check(res(r) === 'counted;stored', 'conversion on the spin click counts', res(r));
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + id5 + '&m=url', { ip: '198.18.0.8' });
check(res(r) === 'dup;url', 'the ad click behind it is the same click: not counted again', res(r));
const spPlain = await req('GET', '/r/' + rot.code, { ip: '203.0.113.27' });
check(/^[a-f0-9]{10}$/.test(lsclkOf(spPlain.headers.location)), 'an owner with a goal: plain spin-link clicks carry lsclk too');
// InstantAdPay: signed click push, then a conversion on it, then the summary
const ipI = '203.0.113.30';
const bad = await signed('/api/partner/clicks', { clicks: [] }, 'wrong-secret-wrong-secret-wrong-secret');
check(bad.status === 401, 'partner call with a bad signature refused', String(bad.status));
const iid = 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11);
const pc = await signed('/api/partner/clicks', { clicks: [{ id: iid, camp: 77, cname: 'IAP QA banner', type: 'banner', owner: A, ts: Date.now(), sk: softKey(ipI, UA), c: 'US', dv: 'desktop', pl: 'instantadpay.com/my', target: 'https://landing.qa.test/iap', spent: 200, self: 0 }] });
check(pc.status === 200 && pc.json.n === 1, 'IAP ad click pushed over the signed partner call', pc.text.slice(0, 120));
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + iid + '&m=url', { ip: '198.18.0.9' });
check(res(r) === 'counted;url', 'conversion on an InstantAdPay ad click counts', res(r));
const sum = await signed('/api/partner/conv', { op: 'summary', email: A, days: 30 });
const bc = sum.json && sum.json.byCampaign && sum.json.byCampaign['77'];
check(sum.status === 200 && bc && bc.clicks === 1 && bc.conv[PX] === 1 && (sum.json.goals || []).some(g => g.px === PX), 'IAP summary: goals + campaign 77 shows 1 click, 1 subscriber', JSON.stringify(bc));
const gI = await signed('/api/partner/conv', { op: 'create', email: A, name: 'sale', value: 20 });
check(gI.status === 200 && gI.json.goal && gI.json.goal.name === 'sale', 'IAP can add a goal to the member (LinkSpin holds it)', gI.text.slice(0, 120));
const tI = await signed('/api/partner/conv', { op: 'test', email: A, px: gI.json.goal.px });
const tX = await signed('/api/partner/conv', { op: 'test', email: B, px: gI.json.goal.px });
check(tI.status === 200 && tI.json.ok && tX.status === 400, "IAP test conversion works for the owner, refused for someone else's goal", tX.text.slice(0, 80));
// a test conversion through the real pixel, and the advertiser's own click
r = await req('GET', '/cv.gif?px=' + PX + '&test=1', { ip: '198.18.0.10' });
check(res(r) === 'test', 'test conversion received', res(r));
const own = await req('GET', '/api/ads/click/1', { ip: '10.77.0.1', cookie: cA });
const idSelf = lsclkOf(own.headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + idSelf + '&m=url', { ip: '198.18.0.11' });
check(res(r) === 'counted;url;self', "advertiser's own click still gets an id and is recorded (as a test)", res(r));
// fix 1: the owner's own SPIN LINK click (from the browser they signed in with, no cookie on the link domain) is a test
const ownSpin = await req('GET', '/r/' + rot.code, { ip: '10.77.0.1' });
const idOwnSpin = lsclkOf(ownSpin.headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + idOwnSpin + '&m=url', { ip: '198.18.0.12' });
check(/^[a-f0-9]{10}$/.test(idOwnSpin) && res(r) === 'counted;url;self', "owner's own spin-link click (owner soft key): its conversion is a test, not counted", res(r));
const ownSpin2 = await req('GET', '/r/' + rot.code, { ip: '10.77.0.99', cookie: cA }); // signed in on this host, another network
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + lsclkOf(ownSpin2.headers.location) + '&m=url', { ip: '198.18.0.13' });
check(res(r) === 'counted;url;self', "owner's own spin-link click while signed in: a test", res(r));
// a stranger's spin click converted from the owner's own browser: a test too
const strangerSpin = await req('GET', '/r/' + rot.code, { ip: '203.0.113.28' });
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + lsclkOf(strangerSpin.headers.location) + '&m=url', { ip: '10.77.0.1' });
check(res(r) === 'counted;url;self', "a goal finished in the owner's own browser is a test", res(r));
// fix 3: Banner Spin straight to a page carries lsclk; a stranger's goal counts under By Banner Spin, the owner's own is a test
const AUTH = { Authorization: 'Bearer localtest-cv' };
const gr = await req('POST', '/api/admin/bannerspins', { headers: AUTH, body: { email: A, grant: 'starter' } });
const bsc = await req('POST', '/api/my/bannerspins', { cookie: cA, body: { name: 'Conv QA banners', size: '468x60', fallback: 'https://landing.qa.test/fallback' } });
const BS = bsc.json && bsc.json.spin;
const bb1 = BS && await req('POST', '/api/my/bannerspins/' + BS.id + '/banner', { cookie: cA, body: { image: 'https://img.qa.invalid/b1.png', target: 'https://landing.qa.test/bs?utm_source=bs&q=a%2Cb#form', label: 'Direct', weight: 10 } });
check(gr.status === 200 && BS && BS.code && bb1 && bb1.status === 200, 'Banner Spin set up for the member (starter grant, one banner straight to a page)', [gr.status, bsc.text.slice(0, 120), bb1 && bb1.text.slice(0, 120)].join(' | '));
const bid = bb1 && bb1.json && ((bb1.json.banner && bb1.json.banner.id) || (bb1.json.spin && bb1.json.spin.banners && bb1.json.spin.banners.slice(-1)[0].id)) || 1;
const bk = await req('GET', '/c/' + BS.code + '?x=' + bid, { ip: '203.0.113.50' });
const idBs = lsclkOf(bk.headers.location);
check(bk.status === 302 && /^k[a-f0-9]{11}$/.test(idBs) && bk.headers.location === 'https://landing.qa.test/bs?utm_source=bs&q=a%2Cb&lsclk=' + idBs + '#form', 'Banner Spin click straight to a page: lsclk added, params kept byte for byte, before the #hash', bk.headers.location);
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + idBs + '&m=stored', { ip: '198.18.0.14' });
check(res(r) === 'counted;stored', 'a goal on the Banner Spin click counts', res(r));
const tagBs = await req('GET', '/t.gif?px=' + PX + '&c=' + idBs, { ip: '198.18.0.15' });
check(res(tagBs) === 'stored', 'the landing tag accepts the Banner Spin click id', res(tagBs));
const bkOwn = await req('GET', '/c/' + BS.code + '?x=' + bid, { ip: '10.77.0.1' });
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + lsclkOf(bkOwn.headers.location) + '&m=url', { ip: '198.18.0.16' });
check(res(r) === 'counted;url;self', "owner's own Banner Spin click: a test, not counted", res(r));
const bb2 = await req('POST', '/api/my/bannerspins/' + BS.id + '/banner', { cookie: cA, body: { image: 'https://img.qa.invalid/b2.png', link: rot.id, label: 'Via spin', weight: 10 } });
const bid2 = bb2.json && ((bb2.json.banner && bb2.json.banner.id) || (bb2.json.spin && bb2.json.spin.banners.slice(-1)[0].id));
const bkSpin = await req('GET', '/c/' + BS.code + '?x=' + bid2, { ip: '203.0.113.51' });
check(bkSpin.status === 302 && /\/r\/[a-z0-9]+$/.test(bkSpin.headers.location || ''), 'a banner pointed at a spin link gets no lsclk of its own (the spin link adds one)', bkSpin.headers.location);
const bkB = await req('GET', '/api/admin/bannerspins', { headers: AUTH });
check(bkB.status === 200, 'admin Banner Spin list still answers');
// the report: counts, methods, cost per goal (campaign 1: 300 credits spent / 4 subscribers = 75)
const rep = (await req('GET', '/api/my/conversions?days=30', { cookie: cA })).json;
const G = rep.byGoal.find(x => x.goal === 'subscriber');
const c1 = G.campaigns.find(c => c.key === 'ls:1'), c3 = G.campaigns.find(c => c.key === 'ls:3'), cI = G.campaigns.find(c => c.key === 'iap:77');
check(G.n === 7, 'report: 7 subscribers counted (4 on campaign 1, 1 via spin link, 1 IAP, 1 Banner Spin); every own click left out (ad, spin link x3, Banner Spin)', 'n=' + G.n);
check(G.banners && G.banners.length === 1 && G.banners[0].code === BS.code && G.banners[0].n === 1, 'by Banner Spin: the straight-to-page banner shows its one goal', JSON.stringify(G.banners));
check(!G.links.some(x => x.n > 1), 'own spin-link clicks are not in the spin-link counts', JSON.stringify(G.links));
check(c1 && c1.n === 4 && c1.spent === 300 && c1.costPer === 75 && c1.clicks === 4, 'cost per goal: 300 credits / 4 = 75 credits, 4 clicks counted (own click left out)', JSON.stringify(c1));
check(c3 && c3.n === 1 && cI && cI.n === 1 && cI.costPer === 200 && cI.site === 'InstantAdPay', 'spin conversion credited to the ad campaign; IAP campaign shows its own cost per goal from the pushed spend', JSON.stringify([c3, cI]));
check(G.links.length === 1 && G.links[0].code === rot.code && G.links[0].n === 1, 'by spin link', JSON.stringify(G.links));
check(G.methods.url === 2 && G.methods.stored === 3 && G.methods.cookie === 1 && G.methods.soft === 1 && rep.selfTests === 5, 'match-method breakdown url 2 / stored 3 / cookie 1 / soft 1, five own-click tests apart (ad, spin x3, Banner Spin)', JSON.stringify([G.methods, rep.selfTests]));
check(G.dests.some(d => d.k === 'landing.qa.test/lp') && G.sources.length > 0, 'by destination page and traffic source', JSON.stringify([G.dests, G.sources]).slice(0, 200));
check(rep.goals.find(g => g.px === PX).lastTest > 0 && rep.goals.find(g => g.px === PX).conv === 7, 'goal row shows the last test and the 30-day count');
const sumSelf = await signed('/api/partner/conv', { op: 'summary', email: A, days: 30 });
check(sumSelf.json && sumSelf.json.selfTests === 5, 'IAP summary carries the own-click test count (selfTests) for the card', JSON.stringify(sumSelf.json && sumSelf.json.selfTests));
const ownI = 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11), skOwnI = 's:' + crypto.randomBytes(10).toString('hex');
const pcOwn = await signed('/api/partner/clicks', { owners: [{ owner: A, sk: skOwnI, ts: Date.now() }], clicks: [{ id: ownI, camp: 77, cname: 'IAP QA banner', type: 'banner', owner: A, ts: Date.now(), sk: skOwnI, self: 0, spent: 200 }] });
r = await req('GET', '/cv.gif?px=' + PX + '&c=' + ownI + '&m=url', { ip: '198.18.0.17' });
check(pcOwn.json && pcOwn.json.owners === 1 && res(r) === 'counted;url;self', "an InstantAdPay click from the owner's InstantAdPay browser (owners pushed with the clicks) is a test", JSON.stringify(pcOwn.json) + ' ' + res(r));
const csv = await req('GET', '/api/my/conversions.csv?days=30', { cookie: cA });
check(csv.status === 200 && /text\/csv/.test(csv.headers['content-type']) && csv.text.trim().split('\n').length === 8 && /,Banner Spin,/.test(csv.text), 'CSV export: header + 7 rows, one from a Banner Spin', String(csv.text.split('\n').length));
const csvB = await req('GET', '/api/my/conversions.csv?days=30', { cookie: await signIn(B, '10.77.0.2') });
check(csvB.text.trim().split('\n').length === 1, "another member's CSV has none of these rows");
// the goal postback was attempted with event = goal name
let plog = []; for (let i = 0; i < 30; i++) { await sleep(500); try { plog = JSON.parse(fs.readFileSync(path.join(DATA, 'postbacks.json'), 'utf8')).log.filter(l => l.event === 'subscriber'); } catch (e) {} if (plog.length >= 7) break; }
check(plog.length >= 7 && plog.every(l => /e=subscriber/.test(l.url)) && plog.some(l => l.lsid === id1), "goal postback fired for the counted conversions, {event} = the goal's name", plog.length + ' attempts ' + (plog[0] ? plog[0].url : ''));
check(!plog.some(l => l.lsid === idSelf), "no postback for the advertiser's own click");
check(!plog.some(l => l.lsid === idOwnSpin || l.lsid === lsclkOf(bkOwn.headers.location)) && plog.some(l => l.lsid === idBs), 'no postback for own spin-link / Banner Spin clicks; the Banner Spin goal fired one');
const tjs = await req('GET', '/t.js'), cjs = await req('GET', '/cv.js');
let parses = true; try { new Function(tjs.text); new Function(cjs.text); } catch (e) { parses = false; }
check(tjs.status === 200 && /javascript/.test(tjs.headers['content-type']) && cjs.status === 200 && parses, 'the landing tag and script pixel are served and parse');
// ---------- 3) browser: landing tag + script pixel on another origin, also framed ----------
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
if (fs.existsSync(PW + '/index.js')) {
const LS = 'http://127.0.0.1:' + PORT;
const pagesSrv = http.createServer((q, s) => {
const u = new URL(q.url, 'http://x');
const html = u.pathname === '/lp' ? '<!doctype html><title>lp</title><form id="f" action="/thanks"><input type="hidden" name="lsclk" value=""><input name="email" value="a@b.c"></form><a id="in" href="/thanks?step=2">Next</a><a id="out" href="https://elsewhere.qa.invalid/">Out</a><script async src="' + LS + '/t.js?px=' + PX + '"></script>'
: u.pathname === '/thanks' ? '<!doctype html><title>thanks</title><p>Thanks</p><script async src="' + LS + '/cv.js?px=' + PX + '&goal=subscriber"></script>'
: u.pathname === '/frame' ? '<!doctype html><title>frame</title><iframe id="fr" src="http://localhost:' + PORT2 + '/lp?lsclk=' + u.searchParams.get('id') + '" width="600" height="400"></iframe>' : '';
s.writeHead(html ? 200 : 404, { 'Content-Type': 'text/html' }); s.end(html);
}).listen(PORT2);
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
const browser = await chromium.launch();
try {
const ctx = await browser.newContext(); const page = await ctx.newPage();
const results2 = [];
page.on('response', rr => { if (/\/cv\.gif\?/.test(rr.url())) results2.push(rr.headers()['x-ls-result'] || ''); });
const idW = lsclkOf((await req('GET', '/api/ads/click/1', { ip: '203.0.113.40' })).headers.location);
await page.goto('http://localhost:' + PORT2 + '/lp?lsclk=' + idW); await page.waitForTimeout(800);
const stored = await page.evaluate(() => { try { return JSON.parse(localStorage.getItem('ls_clk')).id; } catch (e) { return null; } });
const hid = await page.evaluate(() => document.querySelector('input[name=lsclk]').value);
await page.evaluate(() => { document.addEventListener('click', e => e.preventDefault()); document.getElementById('in').dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); });
const inHref = await page.evaluate(() => document.getElementById('in').href), outHref = await page.evaluate(() => document.getElementById('out').href);
check(stored === idW && hid === idW, 'landing tag on another origin keeps the id (localStorage) and fills the hidden lsclk field', stored + ' / ' + hid);
check(/lsclk=/.test(inHref) && !/lsclk=/.test(outHref), 'same-site links get lsclk, links to other sites are left alone', inHref + ' | ' + outHref);
await page.goto('http://localhost:' + PORT2 + '/thanks'); await page.waitForTimeout(1200);
check(results2.includes('counted;stored'), "script goal pixel on the thank-you page (no id in its address) counts with method 'stored'", JSON.stringify(results2));
// framed (a traffic exchange): the member's page inside another site's frame
const idF = lsclkOf((await req('GET', '/api/ads/click/1', { ip: '203.0.113.41' })).headers.location);
const ctx2 = await browser.newContext(); const p2 = await ctx2.newPage(); const res3 = [];
p2.on('response', rr => { if (/\/cv\.gif\?/.test(rr.url())) res3.push(rr.headers()['x-ls-result'] || ''); });
const errs = []; p2.on('pageerror', e => errs.push(String(e)));
await p2.goto('http://127.0.0.1:' + PORT2 + '/frame?id=' + idF); await p2.waitForTimeout(1000);
const fr = p2.frames().find(f => /\/lp/.test(f.url()));
await fr.evaluate(() => { location.href = '/thanks'; }); await p2.waitForTimeout(1500);
check(res3.includes('counted;stored') && !errs.length, 'framed in another site: the tag keeps the id and the thank-you pixel counts, no page errors', JSON.stringify(res3) + ' ' + errs.join('; '));
// a broken LinkSpin host never breaks the member's page
const p3 = await ctx.newPage(); const errs3 = []; p3.on('pageerror', e => errs3.push(String(e)));
await p3.setContent('<p id="ok">fine</p><script async src="http://127.0.0.1:1/t.js?px=' + PX + '"></script><script async src="http://127.0.0.1:1/cv.js?px=' + PX + '"></script>'); await p3.waitForTimeout(500);
check(!errs3.length && await p3.evaluate(() => document.getElementById('ok').textContent) === 'fine', "unreachable tag host: the member's page still works, no errors");
} finally { await browser.close(); pagesSrv.close(); }
browserPart = true;
} else { results.push('SKIP browser part (no Playwright at ' + PW + ')'); }
} catch (e) {
check(false, 'run', e && e.stack || String(e));
} finally {
srv.kill(); await sleep(500);
const fails = results.filter(r => r.startsWith('FAIL'));
console.log(results.join('\n'));
console.log('\n' + (results.length - fails.length) + ' passed, ' + fails.length + ' failed' + (fails.length ? ' (server log: ' + logFile + ')' : ''));
if (!fails.length) try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
process.exit(failed ? 1 : 0);
}