f6621a8e34
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>
109 lines
7.7 KiB
JavaScript
109 lines
7.7 KiB
JavaScript
// First-party retargeting (Marty 2026-10-08): audiences a member can target or exclude with their campaigns.
|
|
// - An audience is a list of visitors. Visitors are keyed by the ls.vid cookie (set by the pixel and by zone serves),
|
|
// with a soft fallback key (hash of IP + user agent, 24 h) for browsers that refuse the cross-site cookie.
|
|
// - Every member has one automatic audience, "My visitors": fed by views of their LinkSpin pages and by any zone they
|
|
// 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 } },
|
|
// 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');
|
|
|
|
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: {}, 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(); }
|
|
|
|
const norm = e => String(e || '').trim().toLowerCase();
|
|
const isId = id => /^la-[a-f0-9]{6}$/.test(String(id || ''));
|
|
const newId = () => { for (;;) { const id = 'la-' + crypto.randomBytes(3).toString('hex'); if (!load().audiences[id]) return id; } };
|
|
|
|
function list(owner) {
|
|
const o = norm(owner); if (!o) return [];
|
|
defaultFor(o);
|
|
return Object.values(load().audiences).filter(a => a.owner === o).sort((a, b) => (b.auto ? 1 : 0) - (a.auto ? 1 : 0) || a.created - b.created)
|
|
.map(a => Object.assign({}, a, sizes(a.id)));
|
|
}
|
|
function sizes(id) {
|
|
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; }
|
|
function nameOf(id) { const a = get(id); return a ? a.name : null; }
|
|
function defaultFor(owner) {
|
|
const o = norm(owner); if (!o) return null; const st = load();
|
|
let a = Object.values(st.audiences).find(x => x.owner === o && x.auto);
|
|
if (!a) { a = { id: newId(), owner: o, name: 'My visitors', auto: true, created: Date.now() }; st.audiences[a.id] = a; save(); }
|
|
return a.id;
|
|
}
|
|
function create(owner, name) {
|
|
const o = norm(owner); name = String(name || '').trim().replace(/\s+/g, ' ').slice(0, 40);
|
|
if (!name) return { error: 'Give the audience a name.' };
|
|
const mine = Object.values(load().audiences).filter(a => a.owner === o);
|
|
if (mine.length >= MAX_PER_OWNER) return { error: 'That is a lot of audiences. Remove one first.' };
|
|
if (mine.some(a => a.name.toLowerCase() === name.toLowerCase())) return { error: 'You already have an audience with that name.' };
|
|
const a = { id: newId(), owner: o, name, auto: false, created: Date.now() }; load().audiences[a.id] = a; save();
|
|
return { ok: true, audience: Object.assign({}, a, sizes(a.id)) };
|
|
}
|
|
function rename(owner, id, name) {
|
|
const a = get(id); if (!a || a.owner !== norm(owner)) return { error: 'No such audience.' };
|
|
name = String(name || '').trim().replace(/\s+/g, ' ').slice(0, 40); if (!name) return { error: 'Give the audience a name.' };
|
|
a.name = name; save(); return { ok: true, audience: Object.assign({}, a, sizes(a.id)) };
|
|
}
|
|
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]; delete load().ev[id]; save(); return { ok: true };
|
|
}
|
|
|
|
// ---- visitor keys
|
|
function softKey(req) {
|
|
const ua = String(req.headers['user-agent'] || ''); const ip = String(req.headers['x-forwarded-for'] || (req.socket && req.socket.remoteAddress) || '').split(',')[0].trim();
|
|
return 's:' + crypto.createHash('sha256').update(ip + '|' + ua).digest('hex').slice(0, 20);
|
|
}
|
|
function cookieVid(req) { const m = /(?:^|;\s*)ls\.vid=([a-f0-9]{16,32})/.exec(String(req.headers.cookie || '')); return m ? m[1] : null; }
|
|
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
|
|
// 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;
|
|
}
|
|
function has(id, vid, soft) {
|
|
const h = load().hits[id]; if (!h) return false; const now = Date.now();
|
|
if (vid && h[vid] && now - h[vid] <= KEEP_MS) return true;
|
|
if (soft && h[soft] && now - h[soft] <= SOFT_MS) return true;
|
|
return false;
|
|
}
|
|
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]; 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)
|
|
function matcher(req) { const vid = cookieVid(req), soft = softKey(req); return { vid, soft, audienceHas: id => has(id, vid, soft) }; }
|
|
|
|
// 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, cleanEvent, cookieVid, newVid, cookieHeader, softKey, matcher };
|