92c5b777da
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
101 lines
6.4 KiB
JavaScript
101 lines
6.4 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 } } }
|
|
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: {} }; } S.audiences = S.audiences || {}; S.hits = S.hits || {}; 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 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 };
|
|
}
|
|
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]; 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
|
|
function hit(id, vid, soft) {
|
|
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;
|
|
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]; 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 (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) }; }
|
|
|
|
module.exports = { init, list, create, rename, remove, owns, get, nameOf, defaultFor, hit, has, prune, flush, isId, cookieVid, newVid, cookieHeader, softKey, matcher };
|