Page leads count as conversions again; pixel keeps the event name; cookieless pixel hits stop inflating audiences (Marty approved, 2026-10-22)

B2: the built-in page form posted an empty lsid (pt.js only filled .lsform, the pasted-form class), so page leads never
reached the rotator 'lead' conversion or the postback. The server now fills the hidden lsid at render from ?lsid or the
ls.click cookie, the lead POST falls back to the ls.click cookie when the form sends none, and pt.js fills both .ls-form
and .lsform as a fallback (cache tag pt.js?v=2). Pasted provider forms get no added field: some providers reject unknown
fields, so the lsid only rides along when the member's own form code has an lsid field.

B4: /p.gif now stores the pixel's e= event name (lowercase [a-z0-9_-]{1,32}) in a parallel ev map in audiences.json;
hits stay plain timestamps, so old rows count, match and prune as before. The audiences list shows counts by event
(events for cookie visitors, eventsSoft for 24 h soft keys).

B3: a pixel hit with no ls.vid cookie still offers the cookie but is counted under the 24 h IP + user agent key only,
not a fresh 30-day visitor id, so a cookie-blocking browser counts once.

Test: qa/lsid-pixel.test.mjs (bash qa/run.sh lsid), unit + local end to end on a throwaway data dir.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-22 16:09:40 -05:00
parent a5c2c38106
commit f6621a8e34
6 changed files with 205 additions and 17 deletions
+17 -11
View File
@@ -5,7 +5,8 @@
// run. Extra audiences come from the pixel tag (<script src=/p.js data-aud=la-xxxxxx>) pasted on any site.
// - Membership lasts 30 days from the last hit. Nothing personal is stored: hashes, timestamps, an optional event name.
// - Serving: ads.js asks opts.audienceHas(id) for each targeted campaign; the server builds that closure per request.
// Storage: DATA_DIR/audiences.json { v, audiences: { id: {id, owner, name, auto, created} }, hits: { id: { key: lastTs } } }
// Storage: DATA_DIR/audiences.json { v, audiences: { id: {id, owner, name, auto, created} }, hits: { id: { key: lastTs } },
// ev: { id: { key: lastEventName } } } (2026-10-22: the pixel's e= name, a parallel map so old hits rows stay as they are)
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
@@ -13,7 +14,7 @@ const crypto = require('crypto');
const DAY = 86400000, KEEP_MS = 30 * DAY, SOFT_MS = 24 * 3600000, MAX_PER_OWNER = 20;
let FILE = null, S = null, dirty = false, hitsSincePrune = 0;
function load() { if (S) return S; try { S = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { S = { v: 1, audiences: {}, hits: {} }; } S.audiences = S.audiences || {}; S.hits = S.hits || {}; return S; }
function load() { if (S) return S; try { S = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { S = { v: 1, audiences: {}, hits: {}, ev: {} }; } S.audiences = S.audiences || {}; S.hits = S.hits || {}; S.ev = S.ev || {}; return S; }
function save() { dirty = true; }
function flush() { if (!dirty || !S) return; dirty = false; try { fs.writeFileSync(FILE + '.tmp', JSON.stringify(S)); fs.renameSync(FILE + '.tmp', FILE); } catch (e) { console.error('audiences save', e.message); } }
function init(opts) { FILE = path.join(opts.dataDir, 'audiences.json'); load(); setInterval(flush, 5000).unref(); setInterval(prune, 3600000).unref(); }
@@ -29,9 +30,10 @@ function list(owner) {
.map(a => Object.assign({}, a, sizes(a.id)));
}
function sizes(id) {
const h = load().hits[id] || {}; const now = Date.now(); let s30 = 0, s7 = 0, soft = 0;
for (const k in h) { const t = h[k]; if (k[0] === 's' && k[1] === ':') { if (now - t <= SOFT_MS) soft++; continue; } if (now - t <= KEEP_MS) s30++; if (now - t <= 7 * DAY) s7++; }
return { size30: s30, size7: s7, soft };
const h = load().hits[id] || {}; const ev = S.ev[id] || {}; const now = Date.now(); let s30 = 0, s7 = 0, soft = 0; const events = {}, eventsSoft = {};
// events: last pixel event name per counted visitor, split like the sizes (cookie visitors 30 days, soft keys 24 h)
for (const k in h) { const t = h[k]; if (k[0] === 's' && k[1] === ':') { if (now - t <= SOFT_MS) { soft++; if (ev[k]) eventsSoft[ev[k]] = (eventsSoft[ev[k]] || 0) + 1; } continue; } if (now - t <= KEEP_MS) { s30++; if (ev[k]) events[ev[k]] = (events[ev[k]] || 0) + 1; } if (now - t <= 7 * DAY) s7++; }
return { size30: s30, size7: s7, soft, events, eventsSoft };
}
function owns(owner, id) { const a = load().audiences[String(id || '')]; return !!(a && a.owner === norm(owner)); }
function get(id) { return load().audiences[String(id || '')] || null; }
@@ -59,7 +61,7 @@ function rename(owner, id, name) {
function remove(owner, id) {
const a = get(id); if (!a || a.owner !== norm(owner)) return { error: 'No such audience.' };
if (a.auto) return { error: 'The automatic audience cannot be removed. Campaigns that use it will keep working.' };
delete load().audiences[id]; delete load().hits[id]; save(); return { ok: true };
delete load().audiences[id]; delete load().hits[id]; delete load().ev[id]; save(); return { ok: true };
}
// ---- visitor keys
@@ -72,10 +74,13 @@ function newVid() { return crypto.randomBytes(10).toString('hex'); }
function cookieHeader(vid, prod) { return 'ls.vid=' + vid + '; Path=/; Max-Age=31536000; ' + (prod ? 'SameSite=None; Secure' : 'SameSite=Lax'); }
// ---- hits + membership
function hit(id, vid, soft) {
// the pixel's optional event name: lowercase, [a-z0-9_-]{1,32}, anything else dropped
function cleanEvent(e) { const v = String(e == null ? '' : e).trim().toLowerCase(); return /^[a-z0-9_-]{1,32}$/.test(v) ? v : ''; }
function hit(id, vid, soft, event) {
const st = load(); if (!st.audiences[id]) return false;
const h = st.hits[id] = st.hits[id] || {}; const now = Date.now();
if (vid) h[vid] = now; if (soft) h[soft] = now;
const e = cleanEvent(event); if (e) { const ev = st.ev[id] = st.ev[id] || {}; if (vid) ev[vid] = e; if (soft) ev[soft] = e; }
save(); if (++hitsSincePrune > 2000) { hitsSincePrune = 0; prune(); }
return true;
}
@@ -88,10 +93,11 @@ function has(id, vid, soft) {
function prune() {
const st = load(); const now = Date.now(); let n = 0;
for (const id in st.hits) {
if (!st.audiences[id]) { delete st.hits[id]; continue; }
const h = st.hits[id];
for (const k in h) { const lim = (k[0] === 's' && k[1] === ':') ? SOFT_MS : KEEP_MS; if (now - h[k] > lim) { delete h[k]; n++; } }
if (!st.audiences[id]) { delete st.hits[id]; delete st.ev[id]; continue; }
const h = st.hits[id]; const ev = st.ev[id];
for (const k in h) { const lim = (k[0] === 's' && k[1] === ':') ? SOFT_MS : KEEP_MS; if (now - h[k] > lim) { delete h[k]; if (ev) delete ev[k]; n++; } }
}
for (const id in st.ev) { const h = st.hits[id], ev = st.ev[id]; if (!h) { delete st.ev[id]; continue; } for (const k in ev) if (!(k in h)) delete ev[k]; }
if (n) save(); flush(); return n;
}
// per-request closure for ads.js: opts.audienceHas(id)
@@ -99,4 +105,4 @@ function matcher(req) { const vid = cookieVid(req), soft = softKey(req); return
// admin Member content (2026-10-18): the audiences members made by hand (every member has an automatic one, not listed)
function adminAll() { return Object.values(load().audiences).filter(a => !a.auto).map(a => Object.assign({}, a, sizes(a.id))); }
module.exports = { init, adminAll, list, create, rename, remove, owns, get, nameOf, defaultFor, hit, has, prune, flush, isId, cookieVid, newVid, cookieHeader, softKey, matcher };
module.exports = { init, adminAll, list, create, rename, remove, owns, get, nameOf, defaultFor, hit, has, prune, flush, isId, cleanEvent, cookieVid, newVid, cookieHeader, softKey, matcher };
+1 -1
View File
@@ -56,7 +56,7 @@ function sideVisual(k, c) {
function formArea(page, opts) {
const c = page.content || {};
if (c.formEmbed) { const parsed = formrestyle.parse(c.formEmbed); if (parsed) return '<div class="formarea">' + formrestyle.html(parsed, (c.cta && c.cta.text) || 'Send me the details') + '</div>'; }
return '<div class="formarea"><form class="ls-form" method="post" action="' + esc(opts.leadUrl) + '"><input class="ls-in" type="text" name="name" placeholder="Your first name"><input class="ls-in" type="email" name="email" placeholder="Your best email" required><input type="text" name="website" tabindex="-1" autocomplete="off" style="position:absolute;left:-9999px" aria-hidden="true"><input type="hidden" name="lsid" value="">'
return '<div class="formarea"><form class="ls-form" method="post" action="' + esc(opts.leadUrl) + '"><input class="ls-in" type="text" name="name" placeholder="Your first name"><input class="ls-in" type="email" name="email" placeholder="Your best email" required><input type="text" name="website" tabindex="-1" autocomplete="off" style="position:absolute;left:-9999px" aria-hidden="true"><input type="hidden" name="lsid" value="' + esc(/^[a-z0-9]{6,20}$/i.test(String(opts.lsid || '')) ? opts.lsid : '') + '">'
+ '<button class="cta" type="submit">' + esc((c.cta && c.cta.text) || 'Send me the details') + '</button></form></div>';
}
+3 -1
View File
@@ -10,5 +10,7 @@
try { var u = new URL(a.href); for (var k in P) if (!u.searchParams.has(k)) u.searchParams.set(k, P[k]); a.href = u.toString(); } catch (e) {}
a.addEventListener('click', function () { try { navigator.sendBeacon('/api/p/' + slug + '/hit', new Blob([JSON.stringify({ k: 'cta' })], { type: 'application/json' })); } catch (e) {} });
});
var f = document.querySelector('.lsform input[name="lsid"]'); if (f && lsid) f.value = lsid;
// the built-in form (.ls-form) usually arrives with the lsid filled by the server; this is the fallback. A pasted
// provider form (.lsform) only gets it when the member's own form code carries an lsid field.
if (lsid) document.querySelectorAll('.ls-form input[name="lsid"], .lsform input[name="lsid"]').forEach(function (f) { if (!f.value) f.value = lsid; });
})();
+171
View File
@@ -0,0 +1,171 @@
// Page-builder lead conversions + audience pixel fixes (2026-10-22, Marty approved B2/B3/B4). Two parts:
// 1) unit: audiences.js on a throwaway data dir: event names stored (and kept off old rows), counted per audience,
// pruned with their hits; old {key: ts} rows still count and match.
// 2) end to end: boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB, no mail key, devCode
// sign-in, no curtain, no outbound). Spin link click -> member page (?lsid and cookie-only) -> built-in form ->
// lead stored WITH lsid -> rotator 'lead' conversion -> postback attempt logged. Then the pixel: N cookieless hits
// from one IP + UA count as one visitor, the e= name is stored.
// node qa/lsid-pixel.test.mjs (from the site dir; no internet needed)
// Env: PORT (default 8971)
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';
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 || 8971);
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));
// ---------- 1) unit: audiences.js ----------
{
const UD = fs.mkdtempSync(path.join(os.tmpdir(), 'aud-unit-'));
const now = Date.now();
// an old-shape file: hits values are plain timestamps, no ev map
fs.writeFileSync(path.join(UD, 'audiences.json'), JSON.stringify({ v: 1, audiences: { 'la-aaaaaa': { id: 'la-aaaaaa', owner: 'm@x.test', name: 'Old', auto: false, created: now - 1e6 } },
hits: { 'la-aaaaaa': { 'aaaaaaaaaaaaaaaaaaaa': now - 1000, 'bbbbbbbbbbbbbbbbbbbb': now - 31 * 86400000, 's:cccccccccccccccccccc': now - 1000 } } }));
const A = require(path.join(site, 'audiences.js'));
A.init({ dataDir: UD });
let s = A.list('m@x.test').find(a => a.id === 'la-aaaaaa');
check(s && s.size30 === 1 && s.soft === 1 && JSON.stringify(s.events) === '{}', 'old-shape rows still count (1 live vid, 1 soft, stale vid ignored)', JSON.stringify(s));
check(A.has('la-aaaaaa', 'aaaaaaaaaaaaaaaaaaaa', null) && !A.has('la-aaaaaa', 'bbbbbbbbbbbbbbbbbbbb', null), 'old-shape rows still match');
check(A.cleanEvent('Lead') === 'lead' && A.cleanEvent('sign_up-2') === 'sign_up-2' && A.cleanEvent('bad name') === '' && A.cleanEvent('<x>') === '' && A.cleanEvent('a'.repeat(33)) === '' && A.cleanEvent(null) === '', 'event names sanitized to [a-z0-9_-]{1,32}');
A.hit('la-aaaaaa', 'dddddddddddddddddddd', 's:eeeeeeeeeeeeeeeeeeee', 'lead');
A.hit('la-aaaaaa', 'aaaaaaaaaaaaaaaaaaaa', null, 'Purchase');
A.hit('la-aaaaaa', 'ffffffffffffffffffff', null, 'no good!');
s = A.list('m@x.test').find(a => a.id === 'la-aaaaaa');
check(s.size30 === 3 && s.soft === 2, 'new hits count alongside old rows', JSON.stringify(s));
check(s.events.lead === 1 && s.events.purchase === 1 && Object.keys(s.events).length === 2 && s.eventsSoft.lead === 1, 'events counted per audience (cookie visitors and soft keys apart), bad name dropped', JSON.stringify([s.events, s.eventsSoft]));
A.hit('la-aaaaaa', 'dddddddddddddddddddd', null, '');
s = A.list('m@x.test').find(a => a.id === 'la-aaaaaa');
check(s.events.lead === 1, 'a hit without an event keeps the last event name', JSON.stringify(s.events));
const pr = A.prune();
A.flush(); const disk = JSON.parse(fs.readFileSync(path.join(UD, 'audiences.json'), 'utf8'));
check(pr === 1 && !('bbbbbbbbbbbbbbbbbbbb' in disk.hits['la-aaaaaa']) && typeof disk.hits['la-aaaaaa'].dddddddddddddddddddd === 'number' && disk.ev['la-aaaaaa'].dddddddddddddddddddd === 'lead', 'prune drops the stale row; hits stay timestamps, events live in the ev map', JSON.stringify(disk.ev));
fs.rmSync(UD, { recursive: true, force: true });
}
// ---------- 2) end to end on a local server ----------
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'lsid-qa-'));
fs.mkdirSync(path.join(DATA, 'uploads'));
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'localtest-lp', ADMIN_EMAIL: 'admin@lp.test', SITE_HOST: 'linkspin.test' });
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', '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) LsidQA';
function req(method, p, o) {
o = o || {};
return new Promise((resolve, reject) => {
const headers = Object.assign({ 'User-Agent': UA }, o.headers || {});
if (o.cookie) headers.Cookie = o.cookie; if (o.ip) headers['X-Forwarded-For'] = o.ip;
let body = o.body; if (body && !Buffer.isBuffer(body)) { if (o.form) { body = Buffer.from(new URLSearchParams(body).toString()); headers['Content-Type'] = 'application/x-www-form-urlencoded'; } else { body = Buffer.from(JSON.stringify(body)); 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 readJson = f => JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8'));
const formLsid = html => { const m = /<form class="ls-form"[\s\S]*?name="lsid" value="([^"]*)"/.exec(html); return m ? m[1] : null; };
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');
// sign in the member (devCode, no mail key)
const email = 'pagemember@lp.test'; const ip = '10.9.' + crypto.randomInt(250) + '.' + crypto.randomInt(250);
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 } });
const cM = [].concat(v.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; ');
check(!!cM, 'member signed in on the local copy');
// a published squeeze page with the built-in form
const pc = await req('POST', '/api/my/pages', { cookie: cM, body: { type: 'squeeze', title: 'Lsid QA page', content: { headline: 'Get the guide', cta: { text: 'Send it', url: 'https://example.com/thanks' } } } });
check(pc.status === 200 && pc.json.page, 'page created', pc.text.slice(0, 160));
const pg = pc.json.page;
const pp = await req('POST', '/api/my/pages/' + pg.id, { cookie: cM, body: { status: 'published' } });
check(pp.status === 200, 'page published', pp.text.slice(0, 160));
// a spin link that points at the page, and a postback that listens for 'lead'
const rc = await req('POST', '/api/my/rotations', { cookie: cM, body: { name: 'Lsid QA spin' } });
check(rc.status === 200, 'spin link created', rc.text.slice(0, 160));
const rot = rc.json.rotation;
const rd = await req('POST', '/api/my/rotations/' + rot.id + '/dest', { cookie: cM, body: { url: 'https://linkspin.test/p/' + pg.slug, weight: 1 } });
check(rd.status === 200, 'destination added', rd.text.slice(0, 160));
const pb = await req('POST', '/api/my/postbacks', { cookie: cM, body: { name: 'QA tracker', url: 'https://tracker.qa.invalid/pb?cid={clickid}&e={event}&ls={lsid}', events: ['lead'] } });
check(pb.status === 200, 'postback created (an .invalid host, so nothing leaves this machine)', pb.text.slice(0, 160));
// visitor 1: clicks the spin link, lands on the page with ?lsid, submits the built-in form
const click = await req('GET', '/r/' + rot.code + '?clickid=QA123', { ip: '203.0.113.10' });
const loc = String(click.headers.location || ''); const lsid1 = (/[?&]lsid=([a-z0-9]+)/i.exec(loc) || [])[1] || '';
check(click.status === 302 && /^[a-z0-9]{6,20}$/i.test(lsid1), 'spin link redirects to the page with a click id', loc);
const view1 = await req('GET', '/p/' + pg.slug + '?lsid=' + lsid1, { ip: '203.0.113.10' });
check(view1.status === 200 && formLsid(view1.text) === lsid1, 'built-in form rendered with the click id filled in', 'value=' + formLsid(view1.text));
check(/\/assets\/pt\.js\?v=2/.test(view1.text), 'page loads pt.js with the bumped cache tag');
const ck1 = [].concat(view1.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; ');
check(/ls\.click=/.test(ck1), 'page visit sets the ls.click cookie');
const sub1 = await req('POST', '/p/' + pg.slug + '/lead', { ip: '203.0.113.10', cookie: ck1, form: true, body: { name: 'Pat', email: 'visitor1@lp.test', website: '', lsid: formLsid(view1.text) } });
check(sub1.status === 302, 'lead form submits', 'HTTP ' + sub1.status);
await sleep(300);
let leads = readJson('pages.json').leads; let L = leads.find(l => l.email === 'visitor1@lp.test');
check(L && L.lsid === lsid1, 'lead stored WITH the click id', JSON.stringify(L));
let conv = readJson('rotator.json').conv.filter(c => c.lsid === lsid1);
check(conv.length === 1 && conv[0].ev === 'lead', "rotator recorded the 'lead' conversion", JSON.stringify(conv));
// visitor 2: clicks, then comes back to the page WITHOUT ?lsid (cookie only); the server still fills the form
const click2 = await req('GET', '/r/' + rot.code, { ip: '203.0.113.11' });
const lsid2 = (/[?&]lsid=([a-z0-9]+)/i.exec(String(click2.headers.location || '')) || [])[1] || '';
const land2 = await req('GET', '/p/' + pg.slug + '?lsid=' + lsid2, { ip: '203.0.113.11' });
const ck2 = [].concat(land2.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; ');
const view2 = await req('GET', '/p/' + pg.slug, { ip: '203.0.113.11', cookie: ck2 });
check(formLsid(view2.text) === lsid2, 'cookie-only return visit: form still carries the click id', 'value=' + formLsid(view2.text));
// and a form that posts an empty lsid (an old cached page) falls back to the cookie
const sub2 = await req('POST', '/p/' + pg.slug + '/lead', { ip: '203.0.113.11', cookie: ck2, form: true, body: { email: 'visitor2@lp.test', website: '', lsid: '' } });
await sleep(300);
L = readJson('pages.json').leads.find(l => l.email === 'visitor2@lp.test');
check(sub2.status === 302 && L && L.lsid === lsid2, 'empty lsid in the post falls back to the ls.click cookie', JSON.stringify(L));
// a plain visitor with no click id: the form value stays empty, the lead is stored without one, no conversion
const view3 = await req('GET', '/p/' + pg.slug, { ip: '203.0.113.12' });
check(formLsid(view3.text) === '', 'no click id known: hidden field stays empty');
// the postback attempts land in the log (the .invalid host never resolves: logged as not delivered, plus one retry ~4 s)
let plog = []; for (let i = 0; i < 30; i++) { plog = readJson('postbacks.json').log.filter(l => l.event === 'lead'); if (plog.some(l => l.lsid === lsid1) && plog.some(l => l.lsid === lsid2)) break; await sleep(500); }
const p1 = plog.find(l => l.lsid === lsid1);
check(!!p1 && /cid=QA123/.test(p1.url) && /e=lead/.test(p1.url) && plog.some(l => l.lsid === lsid2), 'postback attempt logged for both leads, macros filled', p1 ? p1.url + ' | ' + p1.note : JSON.stringify(plog));
conv = readJson('rotator.json').conv; check(conv.filter(c => c.ev === 'lead').length === 2, 'exactly two lead conversions in total', String(conv.length));
// ---- the pixel: cookieless hits count once, the event name is stored
const aud = (/\/p\.gif\?a=(la-[a-f0-9]{6})/.exec(view1.text) || [])[1];
check(!!aud, "page carries the owner's audience pixel", aud);
const before = (await req('GET', '/api/my/audiences', { cookie: cM })).json;
const N = 6; let setCookie = 0;
for (let i = 0; i < N; i++) { const g = await req('GET', '/p.gif?a=' + aud + '&e=Signup&t=' + i, { ip: '198.51.100.7' }); if (/ls\.vid=/.test(String(g.headers['set-cookie'] || ''))) setCookie++; }
check(setCookie === N, 'cookieless pixel hits still offer the ls.vid cookie', setCookie + '/' + N);
const vid = 'abcdef0123456789abcd';
await req('GET', '/p.gif?a=' + aud + '&e=purchase', { ip: '198.51.100.8', cookie: 'ls.vid=' + vid });
await req('GET', '/p.gif?a=' + aud + '&e=bad%20name', { ip: '198.51.100.9', cookie: 'ls.vid=' + vid.replace('a', 'b') });
await sleep(6000); // audiences.json flushes every 5 s
const ad = readJson('audiences.json'); const h = ad.hits[aud] || {};
const vidKeys = Object.keys(h).filter(k => !k.startsWith('s:'));
check(vidKeys.length === 2 && vidKeys.includes(vid), 'N cookieless hits added no 30-day visitor ids (only the two cookie hits did)', JSON.stringify(vidKeys));
const softFrom7 = Object.keys(h).filter(k => k.startsWith('s:'));
const ev = (ad.ev || {})[aud] || {};
check(ev[vid] === 'purchase' && Object.values(ev).filter(x => x === 'signup').length === 1 && !Object.values(ev).includes('bad name'), 'event names stored per hit, sanitized', JSON.stringify(ev));
check(Object.values(h).every(t => typeof t === 'number'), 'hits values stay plain timestamps');
const list = (await req('GET', '/api/my/audiences', { cookie: cM })).json;
const A0 = (before && (before.audiences || before).find ? (before.audiences || before).find(a => a.id === aud) : null) || { soft: 0, size30: 0 };
const A1 = list && (list.audiences || list).find ? (list.audiences || list).find(a => a.id === aud) : null;
check(A1 && A1.size30 - A0.size30 === 2 && A1.soft - A0.soft === 3 && A1.events.purchase === 1 && !A1.events.signup && A1.eventsSoft.signup === 1 && A1.eventsSoft.purchase === 1, 'audiences API: the 6 cookieless hits count as one soft visitor (3 soft keys from 3 IPs), events counted', JSON.stringify({ before: A0, after: A1, soft: softFrom7.length }));
} 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);
}
+3
View File
@@ -6,6 +6,7 @@
# bash qa/run.sh all # public + member + earn
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard
# bash qa/run.sh lsid # page-builder lead -> rotator conversion + postback, audience pixel events and cookieless hits
# 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
@@ -34,6 +35,8 @@ elif [ "$MODE" = "member" ]; then
elif [ "$MODE" = "sponsorfollow" ]; then
node qa/sponsorfollow.test.cjs || status=1
node qa/carry-hold.test.cjs || status=1
elif [ "$MODE" = "lsid" ]; then
node qa/lsid-pixel.test.mjs || status=1
elif [ "$MODE" = "kb" ]; then
node qa/kb-retrieval.cjs || status=1
node qa/kb-chat.mjs || status=1
+10 -4
View File
@@ -1195,9 +1195,11 @@ const server = http.createServer(async (req, res) => {
}
// audience pixel: 1x1 gif, sets/refreshes the visitor cookie, records the hit (30-day membership)
if (p === '/p.gif' && req.method === 'GET') {
const a = String(u.searchParams.get('a') || ''); let vid = audiences.cookieVid(req); const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length) };
if (!vid) { vid = audiences.newVid(); h['Set-Cookie'] = audiences.cookieHeader(vid, IS_PROD); }
if (audiences.isId(a)) audiences.hit(a, vid, audiences.softKey(req));
const a = String(u.searchParams.get('a') || ''); const vid = audiences.cookieVid(req); const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length) };
// no cookie came in: offer one, but count this hit under the soft key only (2026-10-22). A browser that blocks the
// cookie would otherwise add a fresh 30-day visitor on every hit and inflate the audience size.
if (!vid) h['Set-Cookie'] = audiences.cookieHeader(audiences.newVid(), IS_PROD);
if (audiences.isId(a)) audiences.hit(a, vid, audiences.softKey(req), audiences.cleanEvent(u.searchParams.get('e')));
res.writeHead(200, h); return res.end(PIXEL_GIF);
}
if (p === '/p.js') { try { const body = fs.readFileSync(path.join(PUBLIC_DIR, 'p.js')); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(body); } catch (e) { res.writeHead(404); return res.end(); } }
@@ -1250,12 +1252,16 @@ const server = http.createServer(async (req, res) => {
const hdr = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin',
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src 'self' https: data:; form-action https: http:; base-uri 'none'; frame-ancestors *; connect-src 'self'" };
if (/^[a-z0-9]{6,20}$/i.test(lsid)) hdr['Set-Cookie'] = 'ls.click=' + lsid + '; Path=/; SameSite=Lax; Max-Age=2592000' + (IS_PROD ? '; Secure' : '');
res.writeHead(200, hdr); return res.end(pages.html(pg, { leadUrl: '/p/' + pg.slug + '/lead', trackSrc: '/assets/pt.js', footerLink: 'https://' + SITE_HOST + '/', footerText: 'Made with LinkSpin', pixel: 'https://' + SITE_HOST + '/p.gif?a=' + audiences.defaultFor(pg.owner) + '&e=page' }));
// the visitor's click id goes into the built-in form at render (2026-10-22): from ?lsid, else the ls.click cookie a
// spin-link visit left earlier, so a lead counts as the rotator's 'lead' conversion even when the script never runs
const formLsid = /^[a-z0-9]{6,20}$/i.test(lsid) ? lsid : (/^[a-z0-9]{6,20}$/i.test(String(parseCookies(req)['ls.click'] || '')) ? parseCookies(req)['ls.click'] : '');
res.writeHead(200, hdr); return res.end(pages.html(pg, { leadUrl: '/p/' + pg.slug + '/lead', lsid: formLsid, trackSrc: '/assets/pt.js?v=2', footerLink: 'https://' + SITE_HOST + '/', footerText: 'Made with LinkSpin', pixel: 'https://' + SITE_HOST + '/p.gif?a=' + audiences.defaultFor(pg.owner) + '&e=page' }));
}
pm = /^\/p\/([a-z0-9-]{3,60})\/lead$/i.exec(p);
if (pm && req.method === 'POST') {
const raw = await new Promise(r => { let d = ''; req.on('data', c => { d += c; if (d.length > 20000) req.destroy(); }); req.on('end', () => r(d)); });
const b = {}; try { const ct = String(req.headers['content-type'] || ''); if (/json/.test(ct)) Object.assign(b, JSON.parse(raw)); else for (const [k, v] of new URLSearchParams(raw)) b[k] = v; } catch (e) {}
if (!/^[a-z0-9]{6,20}$/i.test(String(b.lsid || ''))) { const lc = String(parseCookies(req)['ls.click'] || ''); if (/^[a-z0-9]{6,20}$/i.test(lc)) b.lsid = lc; } // form posted no click id: the cookie from the page visit
const r = await pages.lead(pm[1], b, req);
if (r.error) { res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('<!doctype html><title>Try again</title><p style="font-family:system-ui;padding:40px">' + r.error + ' <a href="javascript:history.back()">Go back</a></p>'); }
if (r.owner && r.lsid) { try { postbacks.bindClick(String(b.email || '').toLowerCase(), r.lsid); const hit = await rotator.convert(r.lsid, 'lead', {}); if (hit) postbacks.fire(hit.owner, 'lead', Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: r.lsid, code: hit.code, sourceId: hit.sourceId || '' })).catch(() => {}); } catch (e) {} }