First-party retargeting: audiences (automatic 'My visitors' fed by pages + zones, custom pixel audiences via /p.js + /p.gif, ls.vid cookie + 24 h soft key), include/exclude audience targeting on banner/text/login campaigns, zone tag sends credentials with CORS echo, audience-targeted campaigns never syndicate, Audiences panel on Zones and selector on Ads

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-08 16:42:02 -05:00
parent b379f4adda
commit 92c5b777da
11 changed files with 180 additions and 16 deletions
BIN
View File
Binary file not shown.
+100
View File
@@ -0,0 +1,100 @@
// 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 };
+1 -1
View File
@@ -89,6 +89,6 @@ function render(page, opts) {
body = hero + '<main>' + main + '</main>';
}
const foot = '<div class="foot">' + esc(c.disclaimer || 'Results depend on effort. Nothing here is a promise of income.') + (opts.footerLink ? ' · <a href="' + esc(opts.footerLink) + '">' + esc(opts.footerText || 'Made with LinkSpin') + '</a>' : '') + '</div>';
return head + body + foot + '<script src="' + esc(opts.trackSrc || '/assets/pt.js') + '" data-page="' + esc(page.slug) + '" defer></script></body></html>';
return head + body + foot + '<script src="' + esc(opts.trackSrc || '/assets/pt.js') + '" data-page="' + esc(page.slug) + '" defer></script>' + (opts.pixel ? '<img src="' + esc(opts.pixel) + '" alt="" width="1" height="1" style="position:absolute;left:-9999px;top:0" referrerpolicy="strict-origin-when-cross-origin">' : '') + '</body></html>';
}
module.exports = { render, PALETTE_NAMES, knobs, catalog: S.catalog };
+3 -1
View File
@@ -33,6 +33,8 @@
<label class="lbl">Budget, credits<input class="field mono" id="fBudget" type="number" min="10" step="1" value="50"></label>
<label class="lbl">Daily cap, credits (optional)<input class="field mono" id="fCap" type="number" min="10" step="1" placeholder="none"></label>
<label class="lbl">Show to<select class="field" id="fGeo"><option value="">Everyone</option><option value="1">Tier 1 countries</option><option value="1,2">Tier 1 and 2</option></select></label>
<label class="lbl">Audience<select class="field" id="fAud"><option value="">Everyone</option></select></label>
<label class="lbl" id="fAudModeRow" hidden>Audience rule<select class="field" id="fAudMode"><option value="include">Show only to them</option><option value="exclude">Never show to them</option></select></label>
</div>
<div style="display:grid;grid-template-columns:minmax(0,2fr) minmax(0,1fr);gap:12px;margin-top:12px" class="tgt">
<label class="lbl">Where the click goes<input class="field mono" id="fTarget" placeholder="https://"></label>
@@ -60,6 +62,6 @@
</div>
</div>
<script src="/assets/cr-shell.js?v=20261008c"></script>
<script src="/assets/ads-screen.js?v=20261008a"></script>
<script src="/assets/ads-screen.js?v=20261008b"></script>
</body>
</html>
+3 -1
View File
@@ -13,6 +13,7 @@
async function load() {
try { [D, EARN] = await Promise.all([CR.get('/api/my/campaigns'), CR.get('/api/my/earn')]); } catch (e) { CR.sub('could not load'); return; }
const cs = D.campaigns || []; const live = cs.filter(c => c.status === 'active');
{ const sel = $('fAud'); if (sel) { const keep = sel.value; sel.innerHTML = '<option value="">Everyone</option>' + (D.audiences || []).map(a => '<option value="' + a.id + '">' + esc(a.name) + ' (' + fmt(a.size30) + ')</option>').join(''); sel.value = keep; sel.onchange = () => { $('fAudModeRow').hidden = !sel.value; }; } }
const views = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0);
CR.sub(live.length + ' live · ' + fmt(D.availableCredits) + ' credits available');
const hours = new Array(24).fill(0); Object.values(D.hours || {}).forEach(a => (a || []).forEach((n, i) => { hours[i] += Number(n) || 0; })); // last 7 days by UTC hour, all campaigns
@@ -26,7 +27,7 @@
$('rateLine').textContent = 'Rates: ' + r.bannerCreditsPerBatch + ' credits per ' + r.bannerBatch + ' banner views, ' + r.textCreditsPerBatch + ' per ' + r.textBatch + ' text views, ' + r.loginCreditsPerDay + ' per day for the login spot. Viewing pays ' + EARN.claimCredits + ' credits for ' + EARN.target + ' timed views a day.';
const st = c => c.scheduled ? '<span class="tag">Scheduled</span>' : c.status === 'active' ? '<span class="tag ok">Live</span>' : c.status === 'paused' ? '<span class="tag warn">Paused</span>' : c.status === 'out' ? '<span class="tag warn">Out of credits</span>' : c.status === 'done' ? '<span class="tag">Ended</span>' : '<span class="tag">' + esc(c.status) + '</span>';
const cr = c => c.type === 'banner' ? (c.imageUrl ? '<img class="thumb" src="' + esc(c.imageUrl) + '" alt="">' : '') + '<span class="mono muted" style="font-size:11px">' + c.width + 'x' + c.height + '</span>' : c.type === 'text' ? '<b>' + esc(c.title) + '</b><br><span class="muted" style="font-size:12px">' + esc(c.body || '') + '</span>' : '<span class="muted">full page</span>';
$('rows').innerHTML = cs.length ? cs.map(c => '<div class="rw"><div><b>' + esc(c.name) + '</b> <span class="tag t">' + esc(c.type) + '</span><br><span class="mono muted" style="font-size:11px">#' + c.id + ' · ' + esc(host(c.targetUrl)) + (c.geo ? ' · tiers ' + esc(c.geo) : '') + (c.dailyCap ? ' · cap ' + c.dailyCap + '/day' : '') + '</span></div><div>' + cr(c) + '</div><div><span class="num">' + fmt(c.spent) + '</span><span class="muted"> / ' + fmt(c.budget) + '</span><div class="bar"><i style="width:' + Math.min(100, Math.round(100 * c.spent / Math.max(1, c.budget))) + '%"></i></div></div><span class="r num">' + fmt(c.imps) + (c.impsNas ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsNas) + ' network</span>' : '') + '</span><span class="r num">' + fmt(c.clicks) + '</span><span>' + st(c) + '</span><span style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap">'
$('rows').innerHTML = cs.length ? cs.map(c => '<div class="rw"><div><b>' + esc(c.name) + '</b> <span class="tag t">' + esc(c.type) + '</span>' + (c.audience ? ' <span class="tag plain" title="audience">' + esc((((D && D.audiences) || []).find(a => a.id === c.audience) || {}).name || 'audience') + (c.audienceMode === 'exclude' ? ' · excluded' : '') + '</span>' : '') + '<br><span class="mono muted" style="font-size:11px">#' + c.id + ' · ' + esc(host(c.targetUrl)) + (c.geo ? ' · tiers ' + esc(c.geo) : '') + (c.dailyCap ? ' · cap ' + c.dailyCap + '/day' : '') + '</span></div><div>' + cr(c) + '</div><div><span class="num">' + fmt(c.spent) + '</span><span class="muted"> / ' + fmt(c.budget) + '</span><div class="bar"><i style="width:' + Math.min(100, Math.round(100 * c.spent / Math.max(1, c.budget))) + '%"></i></div></div><span class="r num">' + fmt(c.imps) + (c.impsNas ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsNas) + ' network</span>' : '') + '</span><span class="r num">' + fmt(c.clicks) + '</span><span>' + st(c) + '</span><span style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap">'
+ (c.status === 'active' ? '<button class="btn sm" type="button" data-pause="' + c.id + '">Pause</button>' : c.status === 'paused' ? '<button class="btn sm" type="button" data-resume="' + c.id + '">Resume</button>' : '')
+ (['active', 'paused', 'out'].includes(c.status) ? '<button class="btn sm" type="button" data-top="' + c.id + '">Top up</button>' : '') + '</span></div>').join('')
: '<div class="rw"><span class="muted">No ads yet. Launch one: a banner, a text ad or the login spot.</span></div>';
@@ -90,6 +91,7 @@
$('fGo').addEventListener('click', async () => {
const body = { type: TYPE, name: $('fName').value, targetUrl: $('fTarget').value.trim(), budget: Number($('fBudget').value), geo: $('fGeo').value };
if (TYPE !== 'login' && $('fCap').value) body.dailyCap = Number($('fCap').value);
if ($('fAud') && $('fAud').value) { body.audience = $('fAud').value; body.audienceMode = $('fAudMode').value; }
if (TYPE === 'banner') { body.size = $('fSize').value; body.imageUrl = $('fImage').value.trim(); }
if (TYPE === 'text') { body.title = $('fTitle').value; body.body = $('fBody').value; }
$('fGo').disabled = true;
+17 -1
View File
@@ -26,5 +26,21 @@
const v = await dialog({ title: 'Add a zone', text: 'One zone per spot on a page. Paid ads only serve on the site you name here; anywhere else the tag shows the house banner.', fields: [{ k: 'name', label: 'Name', placeholder: 'My blog · sidebar', max: 60 }, { k: 'site', label: 'Site it lives on (required)', placeholder: 'myblog.com', max: 80 }, { k: 'size', label: 'Size: ' + (SIZES.join(', ') || '728x90, 468x60, 300x250, 160x600, 320x50'), value: '728x90', mono: true }], ok: 'Create' });
if (!v) return; try { const r = await api('/api/my/zones', v); SEL = r.zone.id; toast('Zone created. Copy the tag.'); load(); } catch (e) { toast(e.message, true); }
});
CR.requireSession(load);
// ---- audiences (first-party retargeting)
const ptag = a => '<script async src="https://' + HOST + '/p.js" data-aud="' + a.id + '"></script>';
async function loadAudiences() {
let r; try { r = await CR.get('/api/my/audiences'); } catch (e) { return; }
const A = r.audiences || []; HOST = r.host || HOST;
$('audList').innerHTML = A.map(a => '<div style="padding:8px 0;border-top:1px solid var(--line)"><div style="display:flex;justify-content:space-between;gap:8px;align-items:center"><b>' + esc(a.name) + '</b>'
+ '<span class="mono muted" style="font-size:11px">' + fmt(a.size30) + ' in 30 d · ' + fmt(a.size7) + ' in 7 d' + (a.soft ? ' · ' + fmt(a.soft) + ' without cookie (24 h)' : '') + '</span></div>'
+ (a.auto ? '<div class="muted" style="font-size:11.5px">Automatic: your pages and your zones feed it. You can also paste its pixel elsewhere.</div>' : '')
+ '<div class="code" style="display:block;font-size:10.5px;line-height:1.5;word-break:break-all;margin:6px 0">' + esc(ptag(a)) + '</div>'
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn sm" type="button" data-copy="' + a.id + '">Copy pixel</button>'
+ (a.auto ? '' : '<button class="btn sm ghost" type="button" data-ren="' + a.id + '">Rename</button><button class="btn sm ghost danger" type="button" data-del="' + a.id + '">Remove</button>') + '</div></div>').join('');
$('audList').querySelectorAll('[data-copy]').forEach(b => b.addEventListener('click', () => CR.copy(ptag(A.find(a => a.id === b.dataset.copy)))));
$('audList').querySelectorAll('[data-ren]').forEach(b => b.addEventListener('click', async () => { const a = A.find(x => x.id === b.dataset.ren); const v = await dialog({ title: 'Rename audience', fields: [{ k: 'name', label: 'Name', value: a.name }], ok: 'Save' }); if (!v) return; try { await api('/api/my/audiences', { id: a.id, name: v.name }); toast('Renamed'); loadAudiences(); } catch (e) { toast(e.message, true); } }));
$('audList').querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async () => { const a = A.find(x => x.id === b.dataset.del); if (!await dialog({ title: 'Remove ' + a.name + '?', text: 'Its visitor list is deleted. Campaigns that used it stop matching anyone.', ok: 'Remove', danger: true })) return; try { await api('/api/my/audiences', { id: a.id, remove: true }); toast('Removed'); loadAudiences(); } catch (e) { toast(e.message, true); } }));
}
$('audNew').addEventListener('click', async () => { const v = await dialog({ title: 'New audience', text: 'Name it after where the pixel will go, like "Blog readers" or "Checkout page".', fields: [{ k: 'name', label: 'Name', placeholder: 'Blog readers' }], ok: 'Create' }); if (!v) return; try { await api('/api/my/audiences', { name: v.name }); toast('Created. Paste its pixel on the site.'); loadAudiences(); } catch (e) { toast(e.message, true); } });
CR.requireSession(() => { load(); loadAudiences(); });
})();
+13
View File
@@ -0,0 +1,13 @@
/* LinkSpin audience pixel. One line on any page you control:
<script async src="https://linkspin.app/p.js" data-aud="la-xxxxxx"></script>
Adds the visitor to that audience for 30 days so your LinkSpin campaigns can target (or exclude) them. Optional
data-ev="lead" names the event. It stores a random visitor id cookie on linkspin.app and nothing else. */
(function () {
var s = document.currentScript; if (!s) return;
var a = s.getAttribute('data-aud') || ''; if (!/^la-[a-f0-9]{6}$/.test(a)) return;
var base = (s.src || '').replace(/\/p\.js.*$/, '');
var e = s.getAttribute('data-ev') || '';
var q = 'a=' + encodeURIComponent(a) + (e ? '&e=' + encodeURIComponent(e.slice(0, 24)) : '')
+ '&u=' + encodeURIComponent(String(location.href).slice(0, 300)) + '&r=' + encodeURIComponent(String(document.referrer).slice(0, 200)) + '&t=' + Date.now();
var img = new Image(1, 1); img.alt = ''; img.referrerPolicy = 'strict-origin-when-cross-origin'; img.src = base + '/p.gif?' + q;
})();
+1 -1
View File
@@ -7,7 +7,7 @@
var base = (s.src || '').replace(/\/z\.js.*$/, '');
var box = document.createElement('div'); box.style.cssText = 'display:inline-block;line-height:0;max-width:100%'; s.parentNode.insertBefore(box, s);
function load() {
var r = new XMLHttpRequest(); r.open('GET', base + '/api/zone/serve?z=' + encodeURIComponent(zone), true);
var r = new XMLHttpRequest(); r.open('GET', base + '/api/zone/serve?z=' + encodeURIComponent(zone), true); r.withCredentials = true;
r.onload = function () {
if (r.status !== 200) return; var ad; try { ad = JSON.parse(r.responseText).ad; } catch (e) { return; } if (!ad || (!ad.img && !ad.frame)) return;
var el;
+2 -1
View File
@@ -25,12 +25,13 @@
<div class="tbl zl"><div class="hd"><span>Zone</span><span>Size</span><span class="r">Views</span><span class="r">Viewable</span><span class="r">Credits</span><span>Quality</span><span></span></div><div id="rows"></div><div class="ft" id="foot"></div></div>
<div style="display:grid;gap:16px;align-content:start">
<div class="panel" id="tagPanel" hidden><h2 id="tagTitle">Embed tag</h2><div class="code" id="tagCode" style="display:block;font-size:11px;line-height:1.6;word-break:break-all"></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn sm" type="button" id="tagCopy">Copy tag</button><button class="btn sm" type="button" id="tagCheck">Check it is live</button></div><div class="muted" id="tagNote">Paste it where the banner should appear. It sizes itself.</div></div>
<div class="panel" id="audPanel"><h2>Audiences</h2><div class="ink2">Your own retargeting. Every visitor to your LinkSpin pages and your zones lands in <b>My visitors</b> for 30 days, no setup. For any other site you control, paste an audience pixel. Then, on any banner or text campaign, choose "show only to" or "never show to" an audience.</div><div id="audList" class="ink2">loading</div><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn sm" type="button" id="audNew">+ New audience</button></div><div class="muted" style="font-size:11.5px">Counts are visitors seen in the last 30 days. The match uses a LinkSpin cookie, with a 24-hour fallback where a browser blocks cross-site cookies, so Safari and Firefox visitors on other sites match less often. Nothing personal is stored.</div></div>
<div class="panel"><h2>What runs here</h2><div class="ink2">Three tiers, in order: a LinkSpin member campaign (the same pool the ad viewer serves), then a Network Ad Space ad for 728x90 and 468x60 zones, then a LinkSpin house banner. Your site carries the whole network, not just LinkSpin.</div><div class="muted" id="rateNote"></div></div>
</div>
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261008c"></script>
<script src="/assets/zones-screen.js?v=20261008a"></script>
<script src="/assets/zones-screen.js?v=20261008b"></script>
</body>
</html>
+37 -10
View File
@@ -42,7 +42,8 @@ const rotator = require('./rotator');
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29)
const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/<slug> (2026-09-29)
const zones = require('./zones'); // ad zones on members' own sites (2026-09-29)
const nas = require('./nas'); // only asked whether syndication is on (the status strip)
const nas = require('./nas');
const audiences = require('./audiences'); // first-party retargeting (2026-10-08) // only asked whether syndication is on (the status strip)
const MEMBER_AD_TYPES = ['banner', 'text', 'login']; // the formats LinkSpin members can buy (video, visits, featured, solo stay off) // the rotator: rotations, weighted destinations, /r/<code>
const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15)
const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15)
@@ -202,6 +203,9 @@ const codeGlobal = { minute: 0, n: 0 };
const codeAlert = { last: 0, trips: 0, ips: new Set() };
function clientIp(req) { return String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim() || 'unknown'; }
// the viewer's country and tier for ad targeting (null tier = unknown: never matches a restricted campaign)
// CORS for the zone tag: echo the calling origin and allow credentials, so the browser may send the ls.vid cookie
function corsCreds(req) { const o = String(req.headers.origin || ''); return o ? { 'Access-Control-Allow-Origin': o, 'Access-Control-Allow-Credentials': 'true', 'Vary': 'Origin' } : { 'Access-Control-Allow-Origin': '*' }; }
const PIXEL_GIF = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');
function viewerGeo(req) { const cc = geo.countryOf(clientIp(req)); return { cc, tier: geo.tierOf(cc, siteConfig()) }; }
function codeChallenge(rec) {
const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5);
@@ -407,6 +411,7 @@ async function boot() {
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator });
zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST });
pages.init({ dataDir: DATA_DIR, ownHosts, openrouterKey: () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } });
audiences.init({ dataDir: DATA_DIR });
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } });
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL });
@@ -888,7 +893,7 @@ const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://x');
const p = u.pathname;
// zone endpoints run on other people's sites and show only ad creatives, so they pass the curtain
const zonePath = p === '/z.js' || p === '/z/nas' || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-');
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-');
if (!zonePath && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
// -- the rotator redirect: one hop, recorded, on any host (LinkSpin)
@@ -901,15 +906,26 @@ const server = http.createServer(async (req, res) => {
// -- ad zones on members' sites: the tag, the ad, the viewable beacon, the click. Any origin may call these.
if (p === '/z.js') { const zf = path.join(PUBLIC_DIR, 'z.js'); try { const body = fs.readFileSync(zf); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); return res.end(body); } catch (e) {} }
if (p === '/api/zone/serve' && req.method === 'GET') {
const ad = await zones.serve(u.searchParams.get('z'), req, viewerGeo(req));
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'Access-Control-Allow-Origin': '*' }); return res.end(JSON.stringify({ ad }));
const am = audiences.matcher(req); // ls.vid cookie (when the browser sends it cross-site) + soft key
const ad = await zones.serve(u.searchParams.get('z'), req, Object.assign(viewerGeo(req), am));
const h = Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, corsCreds(req));
if (!am.vid) h['Set-Cookie'] = audiences.cookieHeader(audiences.newVid(), IS_PROD);
res.writeHead(200, h); return res.end(JSON.stringify({ ad }));
}
// 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));
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(); } }
if (p === '/z/nas' && req.method === 'GET') { // the frame a Network Ad Space fallback renders in
const html = zones.nasFrame(String(u.searchParams.get('s') || ''));
if (!html) { res.writeHead(404); return res.end(); }
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src https://www.networkadspace.com https://networkadspace.com 'unsafe-inline'; img-src https: http: data:; style-src 'unsafe-inline'; frame-src https: http:; frame-ancestors *; base-uri 'none'", 'Referrer-Policy': 'no-referrer' }); return res.end(html);
}
if (p === '/api/zone/seen' && (req.method === 'GET' || req.method === 'POST')) { await zones.seen(u.searchParams.get('i'), req); res.writeHead(204, { 'Access-Control-Allow-Origin': '*' }); return res.end(); }
if (p === '/api/zone/seen' && (req.method === 'GET' || req.method === 'POST')) { await zones.seen(u.searchParams.get('i'), req); res.writeHead(204, corsCreds(req)); return res.end(); }
{ const zm = /^\/api\/zone\/click\/([a-f0-9]{12})$/.exec(p); if (zm && req.method === 'GET') { const target = await zones.click(zm[1]); res.writeHead(302, { Location: target || '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); } }
{ const wm = /^\/welcome\/([a-f0-9]{48})$/.exec(p); if (wm && (req.method === 'GET' || req.method === 'POST')) { // one-time tester sign-in link
const t = inviteTokens.get(wm[1]);
@@ -936,7 +952,7 @@ 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 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' }));
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' }));
}
pm = /^\/p\/([a-z0-9-]{3,60})\/lead$/i.exec(p);
if (pm && req.method === 'POST') {
@@ -2103,7 +2119,7 @@ const server = http.createServer(async (req, res) => {
if (status.views >= status.target || status.claimed) return json(res, 200, { ad: null, status });
const type = String(u.searchParams.get('type') || 'banner');
// members never see (or earn from) their own campaigns in the viewer
const ad = await ads.serve(type === 'text' ? 'text' : 'banner', Object.assign({ excludeEmail: s.email }, viewerGeo(req)));
const ad = await ads.serve(type === 'text' ? 'text' : 'banner', Object.assign({ excludeEmail: s.email }, viewerGeo(req), audiences.matcher(req)));
if (!ad) return json(res, 200, { ad: null, status });
const token = crypto.randomBytes(16).toString('hex');
// the viewer tab frames the advertiser's REAL url (no click counted for a paid view)
@@ -2710,7 +2726,7 @@ const server = http.createServer(async (req, res) => {
// -- ad engine (spec §8b v1: banners, text, login ads)
if (p === '/api/ads/slot' && req.method === 'GET') {
const t = String(u.searchParams.get('type') || 'banner');
const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req)));
const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req), audiences.matcher(req)));
// login ads: the member clicks "Open Ad" (a real, counted click into a
// new tab) while the countdown runs on our interstitial page
if (ad && t === 'login') ad.dwell = ads.rates().loginDwellSeconds || 10;
@@ -2724,6 +2740,16 @@ const server = http.createServer(async (req, res) => {
res.writeHead(302, baseHeaders({ Location: target }));
return res.end();
}
if (p === '/api/my/audiences' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, { audiences: audiences.list(s.email), host: SITE_HOST });
}
if (p === '/api/my/audiences' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = b.remove ? audiences.remove(s.email, b.id) : b.id ? audiences.rename(s.email, b.id, b.name) : audiences.create(s.email, b.name);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/campaigns' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
@@ -2731,7 +2757,7 @@ const server = http.createServer(async (req, res) => {
// welcome credits used to unlock only through the classic dashboard; the Control Room Ads screen grants them the same way (2026-09-29)
let gauntletPending = false;
if (!(await ads.welcomeGranted(s.email))) { const tour = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl); if (!tour.length) await ads.grantWelcome(s.email); else gauntletPending = true; }
const out = { campaigns: await ads.listCampaigns(s.email), rates: ads.rates(), bannerSizes: ads.bannerSizes(), gauntletPending };
const out = { campaigns: await ads.listCampaigns(s.email), rates: ads.rates(), bannerSizes: ads.bannerSizes(), gauntletPending, audiences: audiences.list(s.email) };
out.clickSources = await coach.clickSources(out.campaigns.map(c => c.id));
out.hours = await ads.hoursFor(out.campaigns.map(c => c.id)); // on-site views per UTC hour, last 7 days
out.geo = await ads.geoFor(out.campaigns.map(c => c.id)); // on-site serves per viewer country
@@ -2752,7 +2778,8 @@ const server = http.createServer(async (req, res) => {
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const memberId = await auth.refreshMemberId(s); // 0 is fine: earned credits fund banner/text
const b = await readBody(req);
if (!MEMBER_AD_TYPES.includes(String(b.type || ''))) return json(res, 400, { error: 'LinkSpin runs banner, text and login ads.' }); // Marty 2026-09-29: the three formats members buy
if (!MEMBER_AD_TYPES.includes(String(b.type || ''))) return json(res, 400, { error: 'LinkSpin runs banner, text and login ads.' });
if (b.audience && !audiences.owns(s.email, b.audience)) return json(res, 400, { error: 'That audience is not one of yours.' }); // Marty 2026-09-29: the three formats members buy
if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { // banner/text surf views frame the target; login/video/solo/featured open in a new tab or play in our own player
const fc = await frameCheck(b.targetUrl);
if (!fc.ok) return json(res, 400, { error: fc.reason });
+3
View File
@@ -7,6 +7,7 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const audiences = require('./audiences');
let DATA_DIR = null, ads = null, siteHost = 'linkspin.app';
const SIZES = { '728x90': [728, 90], '468x60': [468, 60], '300x250': [300, 250], '336x280': [336, 280], '250x250': [250, 250], '125x125': [125, 125], '160x600': [160, 600], '120x600': [120, 600], '320x50': [320, 50] }; // + 336x280 / 250x250 / 125x125 / 120x600 (Marty 2026-10-07)
// neutral file names on purpose: EasyList blocks any URL with an IAB size token like '-728x90.' (Marty's own blocker hid
@@ -72,6 +73,8 @@ async function serve(zoneId, req, geoOpts) {
// origin lock: paid inventory (campaigns, network ads) only on the declared site; anywhere else, or with no referrer,
// the tag shows the house banner and nothing is earned. An admin pause does the same.
const off = !onDeclaredSite(z, siteHostOf(req)); const paidOk = !vis.bot && !off && !z.adminPaused;
// retargeting: a real view on the declared site puts the visitor in the zone owner's automatic audience (30 days)
if (!off && !vis.bot && geoOpts && (geoOpts.vid || geoOpts.soft)) { try { audiences.hit(audiences.defaultFor(z.owner), geoOpts.vid, geoOpts.soft); } catch (e) {} }
// waterfall: 1) a LinkSpin member campaign 2) a Network Ad Space ad (NAS serves 728x90 and 468x60) 3) the LinkSpin house banner
let ad = null; if (paidOk) { try { ad = await ads.serve('banner', Object.assign({ width: w, height: h, excludeEmail: z.owner }, geoOpts || {})); } catch (e) { ad = null; } }
const nas = !ad && paidOk && s.nasOn && NAS_SIZES.has(z.size);