Link-domain pool by channel + safety checks, hosted page images + provider allowlist, Reports pages and zones sections

Item 1 (domains.js): every short link domain in linkDomains gets a channel (email / messaging / social / reserve)
via the new linkDomainChannels site setting ("host:channel,..."; default order email, messaging, social, email,
reserve). Checks every 6 h + Admin > Link domains "Check now": Google Safe Browsing v4 when GSB_API_KEY is set
(unknown otherwise), URIBL + SURBL DNS lists (answer = listed, NXDOMAIN = clean, 127.0.0.1 or errors = unknown),
and a TelegramBot-UA reachability probe. Flagged or listed = BURNED: out of domains.live() (no new links or
pages on it, existing /r/ codes still resolve), admin told once via telegramAdminChatId or ADMIN_EMAIL.
State in DATA_DIR/domains.json. New: GET /api/my/link-hosts, GET+POST /api/admin/domains, admin pane.
/api/my/pages now hands out hosts from domains.live().

Item 2 (pages.js, formrestyle.js): POST /api/my/pages/upload (raw image body, multipart, or JSON base64) for
png/jpg/webp up to 2 MB, 50 per member, magic bytes checked, sharp re-encode when installed, stored under
DATA_DIR/uploads/pages/<owner-hash>/<id>.<ext>, served at /u/pages/... immutable for a year; delete via
POST /api/my/pages/images/<id> {remove}. Pages editor: Upload image button beside the image field + a strip of
the member's images. Provider allowlist (17 autoresponders, Sendy by /subscribe path) exposed as `providers`;
the editor says "Recognised: AWeber" or "Unknown provider: plain post to <host>" at paste time; pub() carries
formProvider. Unknown hosts still allowed when parse-or-refuse passes.

Item 3 (zonereport.js, pages.summary): /api/my/reports returns {spins, pages, zones} (spins still spread at the
top level) for the chosen days; Pages and Zones sections on /reports with 30-day bars, totals, per-item tables,
phone width checked. Zone numbers are a read-only view over zones.json (zones.js untouched).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-10 11:28:47 -05:00
parent 0938e89fbe
commit 0a30b1da60
11 changed files with 441 additions and 19 deletions
+103
View File
@@ -0,0 +1,103 @@
// LinkSpin link-domain pool (2026-10-10): the short link domains in siteConfig().linkDomains, each assigned to a
// CHANNEL (email / messaging / social / reserve) so a domain that burns on one channel never takes the others with
// it, plus safety checks every six hours (Google Safe Browsing when GSB_API_KEY is set, URIBL + SURBL DNS lists, a
// Telegram-like reachability probe). A domain flagged by GSB or listed by URIBL/SURBL is BURNED: it drops out of
// live() (no new links or pages are handed out on it; existing /r/ codes keep resolving) and the admin is told once.
// State: DATA_DIR/domains.json. Channel map: siteConfig().linkDomainChannels ("host:channel,host:channel" or an
// object); unset = first domain email, second messaging, third social, fourth email, fifth reserve.
'use strict';
const fs = require('fs');
const path = require('path');
const https = require('https');
const dns = require('dns').promises;
let DATA_DIR = null, siteConfig = () => ({}), saveSite = () => {}, notify = () => {}, gsbKey = () => '';
const CHANNELS = ['email', 'messaging', 'social', 'reserve'];
const LABEL = { email: 'Email', messaging: 'Messaging', social: 'Social', reserve: 'Reserve' };
const NOTE = { email: 'Email and safelist mailings', messaging: 'Telegram, WhatsApp and SMS', social: 'X, Facebook, forums and comments', reserve: 'Held back, never handed out' };
const DEFAULT_ORDER = ['email', 'messaging', 'social', 'email', 'reserve'];
const CHECK_EVERY = 6 * 60 * 60 * 1000;
const J = { db: null, FILE: () => path.join(DATA_DIR, 'domains.json'),
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, domains: {} }; } if (!this.db.domains) this.db.domains = {}; },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db, null, 1)); } catch (e) {} } };
let timer = null;
function init(opts) {
DATA_DIR = opts.dataDir; siteConfig = opts.siteConfig || siteConfig; saveSite = opts.saveSite || saveSite; notify = opts.notify || notify;
gsbKey = opts.gsbKey || (() => String(process.env.GSB_API_KEY || '').trim());
J.load();
if (opts.schedule !== false) { setTimeout(() => checkAll().catch(() => {}), 2 * 60 * 1000); timer = setInterval(() => checkAll().catch(() => {}), CHECK_EVERY); if (timer.unref) timer.unref(); }
}
const norm = h => String(h || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '').replace(/^www\./, '');
// the configured domains, www stripped and deduped, in the order Marty listed them
function configured() { const seen = new Set(); const out = []; for (const raw of String(siteConfig().linkDomains || '').split(',')) { const h = norm(raw); if (h && !seen.has(h)) { seen.add(h); out.push(h); } } return out; }
function channelMap() {
const raw = siteConfig().linkDomainChannels; const map = {};
if (raw && typeof raw === 'object') { for (const [k, v] of Object.entries(raw)) if (CHANNELS.includes(v)) map[norm(k)] = v; }
else for (const part of String(raw || '').split(',')) { const [k, v] = part.split(':').map(x => String(x || '').trim().toLowerCase()); if (k && CHANNELS.includes(v)) map[norm(k)] = v; }
return map;
}
function channelOf(host, idx, map) { map = map || channelMap(); return map[host] || DEFAULT_ORDER[idx] || 'reserve'; }
function stateOf(host) { return J.db.domains[host] || { checkedAt: 0, gsb: 'unknown', uribl: 'unknown', surbl: 'unknown', reach: 'unknown', burned: false, burnedAt: 0, reason: '' }; }
// every configured domain with its channel and last check
function all() { const map = channelMap(); return configured().map((host, i) => Object.assign({ host, channel: channelOf(host, i, map), label: LABEL[channelOf(host, i, map)], note: NOTE[channelOf(host, i, map)] }, stateOf(host))); }
// the domains that may be handed out: not burned, not reserve (opts.includeReserve keeps reserve ones)
function live(opts) { return all().filter(d => !d.burned && ((opts && opts.includeReserve) || d.channel !== 'reserve')).map(d => d.host); }
// for the member Links screen: live hosts with the channel they are meant for
function hosts() { return all().filter(d => !d.burned && d.channel !== 'reserve').map(d => ({ host: d.host, channel: d.channel, label: d.label, note: d.note })); }
function isBurned(host) { return !!stateOf(norm(host)).burned; }
function setChannel(host, channel) {
host = norm(host); if (!configured().includes(host)) return { error: 'That domain is not in linkDomains.' };
if (!CHANNELS.includes(channel)) return { error: 'Channel must be one of ' + CHANNELS.join(', ') + '.' };
const map = channelMap(); const list = configured(); for (let i = 0; i < list.length; i++) if (!map[list[i]]) map[list[i]] = channelOf(list[i], i, map);
map[host] = channel;
saveSite({ linkDomainChannels: list.map(h => h + ':' + map[h]).join(',') });
return { ok: true, domains: all() };
}
// -- checks
function gsbLookup(host) {
const key = gsbKey(); if (!key) return Promise.resolve('unknown');
return new Promise(resolve => {
const body = JSON.stringify({ client: { clientId: 'linkspin', clientVersion: '1.0' }, threatInfo: { threatTypes: ['MALWARE', 'SOCIAL_ENGINEERING', 'UNWANTED_SOFTWARE'], platformTypes: ['ANY_PLATFORM'], threatEntryTypes: ['URL'], threatEntries: [{ url: 'https://' + host + '/' }, { url: 'http://' + host + '/' }] } });
const rq = https.request({ hostname: 'safebrowsing.googleapis.com', path: '/v4/threatMatches:find?key=' + encodeURIComponent(key), method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 10000 }, res => {
let d = ''; res.on('data', c => d += c); res.on('end', () => { if (res.statusCode !== 200) return resolve('unknown'); try { const j = JSON.parse(d || '{}'); resolve(Array.isArray(j.matches) && j.matches.length ? 'flagged' : 'clean'); } catch (e) { resolve('unknown'); } });
});
rq.on('timeout', () => { rq.destroy(); resolve('unknown'); }); rq.on('error', () => resolve('unknown')); rq.end(body);
});
}
// an answer means listed, NXDOMAIN means clean, anything else is unknown. 127.0.0.1 is the lists' "query refused /
// public resolver blocked" code, not a listing, so it is unknown too.
async function dnsList(host, zone) {
try { const a = await dns.resolve4(host + '.' + zone); if (!a.length) return 'clean'; if (a.every(ip => ip === '127.0.0.1')) return 'unknown'; return 'listed'; }
catch (e) { return (e && (e.code === 'ENOTFOUND' || e.code === 'ENODATA')) ? 'clean' : 'unknown'; }
}
// did the domain answer a Telegram-like fetch of its front door (preview bots must be able to reach it)
function reach(host) {
return new Promise(resolve => {
const rq = https.get({ hostname: host, path: '/', headers: { 'User-Agent': 'TelegramBot (like TwitterBot)', Accept: 'text/html,*/*' }, timeout: 8000 }, res => { res.resume(); resolve('ok:' + res.statusCode); });
rq.on('timeout', () => { rq.destroy(); resolve('unknown'); }); rq.on('error', () => resolve('unknown'));
});
}
async function check(host) {
host = norm(host); if (!configured().includes(host)) return { error: 'That domain is not in linkDomains.' };
const [gsb, uribl, surbl, rch] = await Promise.all([gsbLookup(host), dnsList(host, 'multi.uribl.com'), dnsList(host, 'multi.surbl.org'), reach(host)]);
const prev = stateOf(host); const reasons = [];
if (gsb === 'flagged') reasons.push('Google Safe Browsing flagged it'); if (uribl === 'listed') reasons.push('listed on URIBL'); if (surbl === 'listed') reasons.push('listed on SURBL');
const burnedNow = reasons.length > 0;
const rec = Object.assign({}, prev, { checkedAt: Date.now(), gsb, uribl, surbl, reach: rch });
// a burned domain stays burned when the lists come clean again: lists flap, and putting it back is an admin decision (clear())
if (burnedNow) { rec.reason = reasons.join(', '); if (!prev.burned) { rec.burned = true; rec.burnedAt = Date.now(); rec.notified = false; } }
J.db.domains[host] = rec; J.save();
if (rec.burned && !rec.notified) {
rec.notified = true; J.save();
const list = all(); const alive = list.filter(d => !d.burned && d.channel !== 'reserve').map(d => d.host);
const ch = list.find(d => d.host === host); const text = '⚠️ <b>LinkSpin</b> · link domain <b>' + host + '</b> (' + (ch ? ch.label : '') + ' channel) is BURNED: ' + rec.reason + '. It is out of the pool for new links and pages; existing /r/ links still resolve. Live domains now: ' + (alive.join(', ') || 'none') + '. Admin > Link domains to review or clear.';
try { await notify(text, host, rec); } catch (e) {}
}
return { ok: true, domain: Object.assign({ host }, rec) };
}
async function checkAll() { const out = []; for (const h of configured()) { try { out.push(await check(h)); } catch (e) { out.push({ host: h, error: e.message }); } } return out; }
// admin override: a list came clean again or the flag was a mistake; the domain goes back into the pool
function clear(host) { host = norm(host); const rec = stateOf(host); rec.burned = false; rec.burnedAt = 0; rec.reason = ''; rec.notified = false; J.db.domains[host] = rec; J.save(); return { ok: true, domains: all() }; }
// admin can also pull a domain by hand (a complaint, a flap elsewhere) without waiting for a list
function burn(host, why) { host = norm(host); if (!configured().includes(host)) return { error: 'That domain is not in linkDomains.' }; const rec = stateOf(host); rec.burned = true; rec.burnedAt = Date.now(); rec.reason = String(why || 'pulled by admin').slice(0, 200); rec.notified = true; J.db.domains[host] = rec; J.save(); return { ok: true, domains: all() }; }
module.exports = { init, CHANNELS, LABEL, NOTE, all, live, hosts, isBurned, setChannel, check, checkAll, clear, burn, configured };
+40 -1
View File
@@ -62,4 +62,43 @@ function html(parsed, defaultButton) {
const inputs = parsed.fields.map(f => '<input class="lsin" type="' + f.type + '" name="' + escAttr(f.name) + '" placeholder="' + escAttr(f.placeholder) + '"' + (f.value ? ' value="' + escAttr(f.value) + '"' : '') + (f.required || f.type === 'email' ? ' required' : '') + '>').join('\n');
return [open, hidden, inputs, '<button type="submit" class="cta">' + escAttr((parsed.buttonText || '').trim() || defaultButton) + '</button>', '</form>'].join('\n');
}
module.exports = { EMBED_MAX_CHARS, problem, parse, html };
// -- known autoresponder providers (2026-10-10): the allowlist is about CLARITY, not blocking. A recognised action host
// gets "Recognised: AWeber"; anything else is kept as a plain post to <host> with a note that we cannot vouch for it.
// Hosts match the action host or any subdomain of it; `path` (a regex source) narrows by action path, e.g. Sendy on any host.
const PROVIDERS = [
{ name: 'AWeber', hosts: ['aweber.com'] },
{ name: 'GetResponse', hosts: ['getresponse.com', 'getresponse.net', 'gr8.com'] },
{ name: 'Mailchimp', hosts: ['list-manage.com', 'mailchimp.com'] },
{ name: 'Kit (ConvertKit)', hosts: ['convertkit.com', 'kit.com', 'ck.page'] },
{ name: 'ActiveCampaign', hosts: ['activehosted.com', 'activecampaign.com'] },
{ name: 'MailerLite', hosts: ['mailerlite.com', 'mailerlite.io'] },
{ name: 'SendFox', hosts: ['sendfox.com'] },
{ name: 'systeme.io', hosts: ['systeme.io'] },
{ name: 'Drip', hosts: ['getdrip.com'] },
{ name: 'Sendy', hosts: [], path: '(^|/)subscribe/?$' },
{ name: 'Brevo', hosts: ['sibforms.com', 'brevo.com', 'sendinblue.com'] },
{ name: 'Constant Contact', hosts: ['constantcontact.com', 'constantcontactpages.com'] },
{ name: 'Klaviyo', hosts: ['klaviyo.com'] },
{ name: 'Moosend', hosts: ['moosend.com'] },
{ name: 'Benchmark Email', hosts: ['benchmarkemail.com'] },
{ name: 'beehiiv', hosts: ['beehiiv.com'] },
{ name: 'Substack', hosts: ['substack.com'] }
];
function actionOf(embed) {
const forms = String(embed || '').match(/<form\b[\s\S]*?<\/form>/gi); if (!forms || !forms.length) return null;
const tag = forms[0].match(/<form\b[^>]*>/i); const a = tag ? attr(tag[0], 'action') : null;
if (!a || !/^https?:\/\//i.test(a)) return null;
try { return new URL(a); } catch (e) { return null; }
}
// { host, known, name, label, note } for a pasted form, or null when there is no usable action
function provider(embed) {
const u = actionOf(embed); if (!u) return null;
const host = u.hostname.toLowerCase().replace(/^www\./, '');
for (const pr of PROVIDERS) {
const hostHit = pr.hosts.some(h => host === h || host.endsWith('.' + h));
const pathHit = pr.path ? new RegExp(pr.path, 'i').test(u.pathname) : false;
if ((pr.hosts.length && hostHit) || (!pr.hosts.length && pathHit)) return { host, known: true, name: pr.name, label: 'Recognised: ' + pr.name, note: 'Submissions go to ' + host + '.' };
}
return { host, known: false, name: '', label: 'Unknown provider', note: 'The form is kept as a plain post to ' + host + '; we cannot vouch for it.' };
}
module.exports = { EMBED_MAX_CHARS, PROVIDERS, problem, parse, html, provider };
+87 -5
View File
@@ -13,11 +13,11 @@ const render = require('./pagerender');
const style = require('./pagestyle');
const formrestyle = require('./formrestyle');
let DATA_DIR = null, ownHosts = () => [], keyFn = () => '';
let DATA_DIR = null, ownHosts = () => [], keyFn = () => '', imageBase = () => '';
const J = { db: null, FILE: () => path.join(DATA_DIR, 'pages.json'),
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, pages: [], leads: [], views: [] }; } for (const k of ['pages', 'leads', 'views']) if (!Array.isArray(this.db[k])) this.db[k] = []; },
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, pages: [], leads: [], views: [], images: [] }; } for (const k of ['pages', 'leads', 'views', 'images']) if (!Array.isArray(this.db[k])) this.db[k] = []; },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } };
function init(opts) { DATA_DIR = opts.dataDir; ownHosts = opts.ownHosts || (() => []); keyFn = opts.openrouterKey || (() => ''); J.load(); }
function init(opts) { DATA_DIR = opts.dataDir; ownHosts = opts.ownHosts || (() => []); keyFn = opts.openrouterKey || (() => ''); imageBase = opts.imageBase || (() => ''); J.load(); }
const norm = e => String(e || '').trim().toLowerCase();
const TYPES = ['bridge', 'review', 'squeeze'];
const cleanUrl = u => { const s = String(u || '').trim(); return /^https?:\/\/[^\s"'<>]+$/i.test(s) && s.length <= 700 ? s : ''; };
@@ -28,7 +28,8 @@ const strs = (arr, n, len) => (Array.isArray(arr) ? arr : String(arr || '').spli
function pub(p) {
const views = J.db.views.filter(v => v.p === p.id); const leads = J.db.leads.filter(l => l.p === p.id).length;
return { id: p.id, slug: p.slug, type: p.type, title: p.title, status: p.status, design: p.design, content: p.content, scan: p.scan || null, angle: p.angle || '', created: p.created, updated: p.updated, views: views.length, uniques: new Set(views.map(v => v.v)).size, clicks: views.filter(v => v.k === 'cta').length, leads };
return { id: p.id, slug: p.slug, type: p.type, title: p.title, status: p.status, design: p.design, content: p.content, scan: p.scan || null, angle: p.angle || '', created: p.created, updated: p.updated, views: views.length, uniques: new Set(views.map(v => v.v)).size, clicks: views.filter(v => v.k === 'cta').length, leads,
formProvider: p.type === 'squeeze' && p.content && p.content.formEmbed ? formrestyle.provider(p.content.formEmbed) : null };
}
async function list(owner) { return J.db.pages.filter(p => p.owner === norm(owner)).sort((a, b) => b.updated - a.updated).map(pub); }
async function get(owner, id) { const p = J.db.pages.find(p => p.id === String(id) && p.owner === norm(owner)); return p ? pub(p) : null; }
@@ -171,4 +172,85 @@ async function write(owner, id, body) {
return { ok: true, page: pub(p), by };
}
function totals() { return { pages: J.db.pages.length, published: J.db.pages.filter(p => p.status === 'published').length, leads: J.db.leads.length }; }
module.exports = { init, TYPES, list, get, bySlug, create, update, html, view, lead, leads, csv, scan, write, totals };
// -- Reports (2026-10-10): the member's page views, uniques, clicks-through and leads for the last N days, by Central day and by page
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
async function summary(owner, days) {
const mine = J.db.pages.filter(p => p.owner === norm(owner)); const ids = new Set(mine.map(p => p.id));
const since = Date.now() - (Number(days) || 30) * 86400000;
const views = J.db.views.filter(v => ids.has(v.p) && v.ts >= since); const leads = J.db.leads.filter(l => l.owner === norm(owner) && l.ts >= since);
const shows = views.filter(v => v.k !== 'cta'), clicks = views.filter(v => v.k === 'cta');
const dayMap = {}; const dayOf = k => dayMap[k] = dayMap[k] || { day: k, views: 0, u: new Set(), clicks: 0, leads: 0 };
for (const v of shows) { const d = dayOf(ctDay(v.ts)); d.views++; d.u.add(v.v); } for (const v of clicks) dayOf(ctDay(v.ts)).clicks++; for (const l of leads) dayOf(ctDay(l.ts)).leads++;
const byDay = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1).map(d => ({ day: d.day, views: d.views, u: d.u.size, clicks: d.clicks, leads: d.leads }));
const byPage = mine.map(p => { const vs = shows.filter(v => v.p === p.id); return { id: p.id, title: p.title, slug: p.slug, type: p.type, status: p.status, views: vs.length, uniques: new Set(vs.map(v => v.v)).size, clicks: clicks.filter(v => v.p === p.id).length, leads: leads.filter(l => l.p === p.id).length }; }).sort((a, b) => b.views - a.views);
return { pages: mine.length, live: mine.filter(p => p.status === 'published').length, views: shows.length, uniques: new Set(shows.map(v => v.v)).size, clicks: clicks.length, leads: leads.length, byDay, byPage };
}
// -- hosted images (2026-10-10): png/jpg/webp up to 2 MB, 50 per member, stored under DATA_DIR/uploads/pages/<owner-hash>/<id>.<ext>
// and served at /u/pages/<owner-hash>/<id>.<ext>. Re-encoded with sharp when that module is installed (it is not a
// dependency today), otherwise magic bytes + size are checked and the file is stored as it came.
const IMG_MAX = 50, IMG_BYTES = 2 * 1024 * 1024;
const IMG_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' };
const ownerHash = o => crypto.createHash('sha256').update(norm(o)).digest('hex').slice(0, 16);
const imgDir = o => path.join(DATA_DIR, 'uploads', 'pages', ownerHash(o));
let sharp = null; try { sharp = require('sharp'); } catch (e) { sharp = null; }
function sniff(buf) {
if (buf.length > 16 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return 'image/png';
if (buf.length > 16 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'image/jpeg';
if (buf.length > 16 && buf.slice(0, 4).toString() === 'RIFF' && buf.slice(8, 12).toString() === 'WEBP') return 'image/webp';
return null;
}
// the request body as { buf, ct }: a raw image body, multipart/form-data (first file part), or JSON { data: <base64 or data: URL> }
function readUpload(req) {
return new Promise((resolve) => {
const ct = String(req.headers['content-type'] || '').toLowerCase(); const chunks = []; let n = 0; let done = false;
const fail = msg => { if (!done) { done = true; resolve({ error: msg }); } };
req.on('data', c => { n += c.length; if (n > IMG_BYTES * 1.4 + 4096) { req.destroy(); return fail('That image is over 2 MB. Make it smaller and try again.'); } chunks.push(c); });
req.on('error', () => fail('Upload interrupted.'));
req.on('end', () => {
if (done) return; done = true; const raw = Buffer.concat(chunks);
try {
if (ct.startsWith('multipart/form-data')) {
const bm = /boundary=("?)([^";]+)\1/i.exec(ct); if (!bm) return resolve({ error: 'Bad multipart body.' });
const boundary = Buffer.from('--' + bm[2]); let pos = raw.indexOf(boundary);
while (pos !== -1) {
const hs = pos + boundary.length + 2; const he = raw.indexOf('\r\n\r\n', hs); if (he === -1) break;
const head = raw.slice(hs, he).toString('latin1'); const next = raw.indexOf(boundary, he + 4); if (next === -1) break;
const body = raw.slice(he + 4, next - 2); // strip the CRLF before the next boundary
if (/filename=/i.test(head)) { const cm = /content-type:\s*([^\r\n;]+)/i.exec(head); return resolve({ buf: body, ct: cm ? cm[1].trim().toLowerCase() : (sniff(body) || '') }); }
pos = next;
}
return resolve({ error: 'No file in the upload.' });
}
if (ct.startsWith('application/json')) {
const j = JSON.parse(raw.toString('utf8') || '{}'); let data = String(j.data || j.image || ''); let mime = String(j.type || '').toLowerCase();
const dm = /^data:([a-z0-9.+\/-]+);base64,/i.exec(data); if (dm) { mime = dm[1].toLowerCase(); data = data.slice(dm[0].length); }
const buf = Buffer.from(data.replace(/\s+/g, ''), 'base64'); return resolve({ buf, ct: mime || sniff(buf) || '' });
}
return resolve({ buf: raw, ct: ct.split(';')[0].trim() });
} catch (e) { resolve({ error: 'Could not read the upload.' }); }
});
});
}
async function uploadImage(owner, buf, ct) {
if (!buf || !buf.length) return { error: 'No image data arrived.' };
if (buf.length > IMG_BYTES) return { error: 'That image is over 2 MB. Make it smaller and try again.' };
const real = sniff(buf); if (!real || !IMG_EXT[real]) return { error: 'Use a PNG, JPG or WebP image.' };
if (ct && IMG_EXT[ct] && ct !== real) return { error: 'That file does not look like a real ' + IMG_EXT[ct].toUpperCase() + '.' };
if (J.db.images.filter(i => i.owner === norm(owner)).length >= IMG_MAX) return { error: 'You have ' + IMG_MAX + ' images already. Delete one first.' };
let out = buf, mime = real;
if (sharp) { try { const img = sharp(buf, { failOn: 'error' }).rotate().resize({ width: 2000, height: 2000, fit: 'inside', withoutEnlargement: true }); out = mime === 'image/png' ? await img.png({ compressionLevel: 9 }).toBuffer() : mime === 'image/webp' ? await img.webp({ quality: 85 }).toBuffer() : await img.jpeg({ quality: 85, mozjpeg: true }).toBuffer(); } catch (e) { return { error: 'That image could not be read.' }; } }
const id = crypto.randomBytes(6).toString('hex'); const ext = IMG_EXT[mime]; const dir = imgDir(owner);
fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, id + '.' + ext), out);
const rec = { id, owner: norm(owner), h: ownerHash(owner), ext, mime, size: out.length, ts: Date.now() };
J.db.images.push(rec); J.save(); return { ok: true, image: pubImage(rec) };
}
function pubImage(i) { return { id: i.id, url: imageBase() + '/u/pages/' + i.h + '/' + i.id + '.' + i.ext, path: '/u/pages/' + i.h + '/' + i.id + '.' + i.ext, size: i.size, ts: i.ts, type: i.mime }; }
async function images(owner) { return J.db.images.filter(i => i.owner === norm(owner)).sort((a, b) => b.ts - a.ts).map(pubImage); }
async function removeImage(owner, id) {
const i = J.db.images.find(x => x.id === String(id) && x.owner === norm(owner)); if (!i) return { error: 'No such image.' };
try { fs.unlinkSync(path.join(imgDir(owner), i.id + '.' + i.ext)); } catch (e) {}
J.db.images = J.db.images.filter(x => x !== i); J.save(); return { ok: true, images: await images(owner) };
}
// the file behind /u/pages/<hash>/<id>.<ext>, only when the index knows it (never a raw directory read)
function imageFile(hash, id, ext) { const i = J.db.images.find(x => x.h === String(hash) && x.id === String(id) && x.ext === String(ext)); return i ? { file: path.join(DATA_DIR, 'uploads', 'pages', i.h, i.id + '.' + i.ext), mime: i.mime } : null; }
module.exports = { init, TYPES, list, get, bySlug, create, update, html, view, lead, leads, csv, scan, write, totals, summary, readUpload, uploadImage, images, removeImage, imageFile, IMG_MAX, IMG_BYTES, providers: () => formrestyle.PROVIDERS, provider: formrestyle.provider };
+10 -1
View File
@@ -99,6 +99,7 @@
<button data-pane="reports" type="button"><svg viewBox="0 0 24 24"><path d="M12 3l9 16H3z"/><path d="M12 10v4M12 17v.5"/></svg>Reports<span class="pill" id="repBadge" hidden></span></button>
<button data-pane="traffic" type="button"><svg viewBox="0 0 24 24"><path d="M3 17l6-6 4 4 8-8"/><path d="M14 7h7v7"/></svg>Traffic</button>
<button data-pane="zones" type="button"><svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18M8 15h8"/></svg>Zones</button>
<button data-pane="domains" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>Link domains</button>
<button data-pane="blog" type="button"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg>Blog</button>
<button data-pane="releases" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h7"/><circle cx="18" cy="17" r="3"/></svg>Releases</button>
<button data-pane="pnl" type="button"><svg viewBox="0 0 24 24"><path d="M4 19V5M4 19h16"/><path d="M8 15l3-4 3 2 5-6"/></svg>P&amp;L</button>
@@ -294,6 +295,14 @@
<p style="margin:0 0 6px;display:flex;gap:8px;align-items:center"><input class="tfilter small" data-for="znTable" placeholder="Filter zones" style="max-width:260px"><span class="tfilter-count muted small"></span></p><div class="tablewrap"><table class="adm-table" id="znTable"></table></div>
</div>
</div>
<div class="pane" id="pane-domains" hidden>
<div class="card">
<div class="card-head"><h3>Link domains</h3><span class="sub" id="dmSub"></span></div>
<p class="muted small" style="margin:0 0 10px" id="dmRules">Every short link domain belongs to one channel so a burn on one channel never takes the others down: email (mailings and safelists), messaging (Telegram, WhatsApp, SMS), social (X, Facebook, forums) or reserve (held back, never handed out). Checks run every six hours: Google Safe Browsing (needs GSB_API_KEY on the server), URIBL and SURBL lists, and a Telegram-style reachability probe. A flagged or listed domain is burned: no new links or pages go on it, existing /r/ links still resolve, and you are told once.</p>
<p style="margin:0 0 8px;display:flex;gap:8px;align-items:center;flex-wrap:wrap"><button class="btn small" id="dmCheckAll" type="button">Check all now</button><span class="muted small" id="dmGsb"></span></p>
<div class="tablewrap"><table class="adm-table" id="dmTable"></table></div>
</div>
</div>
<div class="pane" id="pane-traffic" hidden>
<div class="card">
<div class="card-head"><h3>Where visitors come from</h3><span class="sub" id="trfSub"></span></div>
@@ -495,6 +504,6 @@
</div>
<script src="/assets/common.js?v=20261009a"></script>
<script src="/assets/admin.js?v=20260929a"></script>
<script src="/assets/admin.js?v=20261010a"></script>
</body>
</html>
+24 -2
View File
@@ -44,8 +44,8 @@
});
// ── panes ──
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', reports: 'Reports', zones: 'Zones', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', settings: 'Settings' };
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, reports: loadReports, zones: loadZones, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, settings: loadSettings };
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', reports: 'Reports', zones: 'Zones', domains: 'Link domains', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', settings: 'Settings' };
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, reports: loadReports, zones: loadZones, domains: loadDomains, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, settings: loadSettings };
function setPane(name) {
if (!TITLES[name]) name = 'overview';
document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; });
@@ -488,6 +488,28 @@
try { await api('/api/admin/zones/' + b.dataset.znpause, pausing ? { paused: true, note: 'Paused ' + new Date().toLocaleDateString() } : { paused: false, note: '' }, 'POST'); loadZones(); } catch (e) { IAP.status(e.message, 'bad'); }
}));
}
// ── link domains: channel per domain, last safety check, burned flag; check now / clear / pull (2026-10-10) ──
async function loadDomains() {
const d = await api('/api/admin/domains');
const list = d.domains || []; const live = list.filter(x => !x.burned && x.channel !== 'reserve').length, burned = list.filter(x => x.burned).length;
$('dmSub').textContent = list.length + ' domain' + (list.length === 1 ? '' : 's') + ' · ' + live + ' live · ' + burned + ' burned';
$('dmGsb').textContent = d.gsb ? 'Google Safe Browsing: on' : 'Google Safe Browsing: off (set GSB_API_KEY on the server to turn it on)';
const ago = t => t ? new Date(t).toLocaleString() : 'never';
const mark = v => v === 'clean' ? '<span style="color:var(--ok,#2e9b5a)">clean</span>' : v === 'flagged' || v === 'listed' ? '<b style="color:var(--bad)">' + v + '</b>' : /^ok:/.test(v || '') ? '<span style="color:var(--ok,#2e9b5a)">answered ' + esc(v.slice(3)) + '</span>' : '<span class="muted">unknown</span>';
$('dmTable').innerHTML = '<tr><th>Domain</th><th>Channel</th><th>Safe Browsing</th><th>URIBL</th><th>SURBL</th><th>Reach</th><th>Status</th><th>Last check</th><th></th></tr>'
+ (list.length ? list.map(x => '<tr' + (x.burned ? ' style="background:rgba(192,57,43,.08)"' : '') + '><td><b>' + esc(x.host) + '</b></td>'
+ '<td><select data-dmch="' + esc(x.host) + '">' + (d.channels || []).map(c => '<option value="' + c + '"' + (c === x.channel ? ' selected' : '') + '>' + esc(d.labels[c] || c) + '</option>').join('') + '</select><br><span class="muted small">' + esc(d.notes[x.channel] || '') + '</span></td>'
+ '<td>' + mark(x.gsb) + '</td><td>' + mark(x.uribl) + '</td><td>' + mark(x.surbl) + '</td><td>' + mark(x.reach) + '</td>'
+ '<td>' + (x.burned ? '<b style="color:var(--bad)">BURNED</b><br><span class="muted small">' + esc(x.reason || '') + (x.burnedAt ? ' · ' + ago(x.burnedAt) : '') + '</span>' : x.channel === 'reserve' ? '<span class="muted">held in reserve</span>' : '<span style="color:var(--ok,#2e9b5a)">live</span>') + '</td>'
+ '<td>' + ago(x.checkedAt) + '</td>'
+ '<td class="act" style="white-space:nowrap"><button type="button" class="btn small ghost" data-dmcheck="' + esc(x.host) + '">Check now</button> ' + (x.burned ? '<button type="button" class="btn small sec" data-dmclear="' + esc(x.host) + '">Clear burn</button>' : '<button type="button" class="btn small sec" data-dmburn="' + esc(x.host) + '">Pull</button>') + '</td></tr>').join('')
: '<tr><td colspan="9" class="muted">No link domains yet. Add them to the linkDomains site setting (comma list) first.</td></tr>');
document.querySelectorAll('[data-dmch]').forEach(sel => sel.addEventListener('change', async () => { try { await api('/api/admin/domains', { action: 'channel', domain: sel.dataset.dmch, channel: sel.value }); IAP.status('Channel saved: ' + sel.dataset.dmch + ' is now ' + sel.value + '.', 'ok'); loadDomains(); } catch (e) { IAP.status(e.message, 'bad'); } }));
document.querySelectorAll('[data-dmcheck]').forEach(b => b.addEventListener('click', busy(b, async () => { const r = await api('/api/admin/domains', { action: 'check', domain: b.dataset.dmcheck }); const x = r.domain || {}; IAP.status(b.dataset.dmcheck + ': Safe Browsing ' + x.gsb + ', URIBL ' + x.uribl + ', SURBL ' + x.surbl + ', reach ' + x.reach + (x.burned ? ' · BURNED' : ''), x.burned ? 'bad' : 'ok'); loadDomains(); })));
document.querySelectorAll('[data-dmclear]').forEach(b => b.addEventListener('click', busy(b, async () => { await api('/api/admin/domains', { action: 'clear', domain: b.dataset.dmclear }); IAP.status(b.dataset.dmclear + ' is back in the pool.', 'ok'); loadDomains(); })));
document.querySelectorAll('[data-dmburn]').forEach(b => b.addEventListener('click', busy(b, async () => { await api('/api/admin/domains', { action: 'burn', domain: b.dataset.dmburn, reason: 'pulled by admin ' + new Date().toLocaleDateString() }); IAP.status(b.dataset.dmburn + ' pulled from the pool.', 'ok'); loadDomains(); })));
}
$('dmCheckAll').addEventListener('click', busy($('dmCheckAll'), async () => { IAP.status('Checking every domain…', 'ok'); const r = await api('/api/admin/domains', { action: 'check' }); const bad = (r.domains || []).filter(x => x.burned).length; IAP.status('Checked ' + (r.results || []).length + ' domains' + (bad ? ', ' + bad + ' burned' : ', none burned') + '.', bad ? 'bad' : 'ok'); loadDomains(); }));
// ── traffic: referring domains / sources, landing pages, angles, by day ──
let trfDays = 30;
document.querySelectorAll('#trfRange [data-days]').forEach(b => b.addEventListener('click', () => { trfDays = Number(b.dataset.days); document.querySelectorAll('#trfRange [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadTraffic().catch(e => IAP.status(e.message, 'bad')); }));
+45 -3
View File
@@ -2,12 +2,48 @@
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
let PAGES = [], SEL = null, SCAN = null, TYPE = 'bridge', HOSTS = [], BASE = '';
let STYLES = { palettes: [], designs: [], layouts: [], niches: [] };
let STYLES = { palettes: [], designs: [], layouts: [], niches: [] }, PROVIDERS = [], IMAGES = [], IMG_MAX = 50, IMG_BYTES = 2 * 1024 * 1024;
// which autoresponder a pasted form posts to (same list the server keeps in formrestyle.js, handed over as `providers`)
function providerOf(embed) {
const f = /<form\b[^>]*>/i.exec(String(embed || '')); if (!f) return null;
const am = /\baction\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i.exec(f[0]); const action = am ? (am[1] || am[2] || am[3]) : '';
if (!/^https?:\/\//i.test(action)) return null;
let u; try { u = new URL(action); } catch (e) { return null; }
const host = u.hostname.toLowerCase().replace(/^www\./, '');
for (const pr of PROVIDERS) { const hostHit = (pr.hosts || []).some(h => host === h || host.endsWith('.' + h)); const pathHit = pr.path ? new RegExp(pr.path, 'i').test(u.pathname) : false; if ((pr.hosts && pr.hosts.length && hostHit) || (!(pr.hosts && pr.hosts.length) && pathHit)) return { host, known: true, name: pr.name }; }
return { host, known: false, name: '' };
}
function providerNote(embed) {
const el = $('providerNote'); if (!el) return; const src = String(embed || '').trim();
if (!src) { el.hidden = true; el.innerHTML = ''; return; }
const pr = providerOf(src); el.hidden = false;
if (!pr) { el.innerHTML = '<span class="warn">No https:// form action found yet.</span> Paste the whole &lt;form&gt; block your provider gives you.'; return; }
el.innerHTML = pr.known ? '<span class="ok"><span class="dot"></span>Recognised: ' + esc(pr.name) + '</span> <span class="muted">Submissions go to ' + esc(pr.host) + '.</span>'
: '<span class="warn"><span class="dot"></span>Unknown provider</span> <span class="muted">The form is kept as a plain post to <b>' + esc(pr.host) + '</b>; we cannot vouch for it. It still has to pass the form check when you save.</span>';
}
// the member's hosted images: a strip of thumbnails under the image field, click to use, x to delete
function drawImages() {
const box = $('imgStrip'); if (!box) return;
box.innerHTML = (IMAGES.length ? IMAGES.map(i => '<span class="im" data-url="' + esc(i.url) + '" title="Use this image"><img src="' + esc(i.url) + '" alt="" loading="lazy"><button type="button" class="x" data-del="' + i.id + '" title="Delete this image">&times;</button></span>').join('') : '<span class="muted" style="font-size:11px">No uploads yet. PNG, JPG or WebP up to 2 MB, ' + IMG_MAX + ' per account.</span>')
+ (IMAGES.length ? '<span class="muted mono" style="font-size:11px;align-self:center">' + IMAGES.length + '/' + IMG_MAX + '</span>' : '');
box.querySelectorAll('.im').forEach(s => s.addEventListener('click', e => { if (e.target.closest('[data-del]')) return; const f = $('f-image'); if (f) { f.value = s.dataset.url; f.dispatchEvent(new Event('input')); toast('Image URL filled in. Save to keep it.'); } }));
box.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async e => { e.stopPropagation(); if (!await dialog({ title: 'Delete this image?', text: 'Pages that still point at it will show no image.', ok: 'Delete', danger: true })) return; try { const r = await api('/api/my/pages/images/' + b.dataset.del, { remove: true }); IMAGES = r.images || []; drawImages(); } catch (er) { toast(er.message, true); } }));
}
async function uploadFile(file) {
if (!file) return; if (!/^image\/(png|jpeg|webp)$/.test(file.type)) return toast('Use a PNG, JPG or WebP image.', true);
if (file.size > IMG_BYTES) return toast('That image is over 2 MB. Make it smaller and try again.', true);
const btn = $('imgUpload'); if (btn) { btn.disabled = true; btn.textContent = 'Uploading…'; }
try {
const r = await (await fetch('/api/my/pages/upload', { method: 'POST', headers: { 'Content-Type': file.type }, body: file })).json(); if (r.error) throw new Error(r.error);
IMAGES.unshift(r.image); drawImages(); const f = $('f-image'); if (f) { f.value = r.image.url; f.dispatchEvent(new Event('input')); } toast('Uploaded. Save to keep it on the page.');
} catch (e) { toast(e.message, true); }
if (btn) { btn.disabled = false; btn.textContent = 'Upload image'; }
}
CR.mount({ active: 'pages', title: 'Pages', sub: 'loading', actions: '<button class="btn pri" type="button" id="newBtn">+ New page</button>' });
const pageUrl = p => (BASE || ('https://' + (HOSTS[0] || location.host) + '/p/')) + p.slug;
async function load(keepSel) {
let r; try { r = await CR.get('/api/my/pages'); } catch (e) { CR.sub('could not load'); return; }
PAGES = r.pages || []; HOSTS = r.hosts || []; BASE = r.pageBase || ''; if (r.styles) STYLES = r.styles;
PAGES = r.pages || []; HOSTS = r.hosts || []; BASE = r.pageBase || ''; if (r.styles) STYLES = r.styles; PROVIDERS = r.providers || []; IMAGES = r.images || []; if (r.imageMax) IMG_MAX = r.imageMax; if (r.imageBytes) IMG_BYTES = r.imageBytes;
const pubd = PAGES.filter(p => p.status === 'published').length;
CR.sub(PAGES.length + ' page' + (PAGES.length === 1 ? '' : 's') + ' · ' + pubd + ' live');
const views = PAGES.reduce((n, p) => n + p.views, 0), leads = PAGES.reduce((n, p) => n + p.leads, 0), clicks = PAGES.reduce((n, p) => n + p.clicks, 0);
@@ -45,7 +81,13 @@
$('edPublish').textContent = p.status === 'published' ? 'Unpublish' : 'Publish'; $('edPreview').href = '/p/' + p.slug + '?preview=1';
$('edUrl').hidden = p.status !== 'published'; $('edUrl').textContent = pageUrl(p);
const c = p.content || {}; const v = k => k === 'ctaText' ? (c.cta && c.cta.text) || '' : k === 'ctaUrl' ? (c.cta && c.cta.url) || '' : Array.isArray(c[k]) ? c[k].join('\n') : (c[k] == null ? '' : c[k]);
$('edFields').innerHTML = F[p.type].map(([k, label, ta]) => '<label class="lbl">' + esc(label) + (ta ? '<textarea class="field" id="f-' + k + '">' + esc(v(k)) + '</textarea>' : '<input class="field' + (/Url|image/i.test(k) ? ' mono' : '') + '" id="f-' + k + '" value="' + esc(v(k)) + '">') + '</label>').join('');
$('edFields').innerHTML = F[p.type].map(([k, label, ta]) => '<label class="lbl">' + esc(label) + (ta ? '<textarea class="field" id="f-' + k + '">' + esc(v(k)) + '</textarea>' : '<input class="field' + (/Url|image/i.test(k) ? ' mono' : '') + '" id="f-' + k + '" value="' + esc(v(k)) + '">') + '</label>'
// hosted images: an Upload button beside the image field (this image is the hero on bridge/review and the card image on squeeze) + the member's strip
+ (k === 'image' ? '<div class="imgrow"><button class="btn sm" type="button" id="imgUpload">Upload image</button><input type="file" id="imgFile" accept="image/png,image/jpeg,image/webp" hidden><span class="muted" style="font-size:11px">PNG, JPG or WebP up to 2 MB. Uploading fills the URL above.</span></div><div class="imgstrip" id="imgStrip"></div>' : '')
// pasted provider forms: say at paste time which autoresponder the form posts to
+ (k === 'formEmbed' ? '<div class="muted" id="providerNote" style="font-size:12px" hidden></div>' : '')).join('');
if ($('imgUpload')) { $('imgUpload').addEventListener('click', () => $('imgFile').click()); $('imgFile').addEventListener('change', () => { uploadFile($('imgFile').files[0]); $('imgFile').value = ''; }); drawImages(); }
if ($('f-formEmbed')) { const fe = $('f-formEmbed'); const upd = () => providerNote(fe.value); fe.addEventListener('input', upd); fe.addEventListener('paste', () => setTimeout(upd, 0)); upd(); }
// the Look panel: niche preset, design, colours, layout. Each change saves at once and the gallery/preview refresh.
const d = p.design || {}; const setLook = async patch => { try { await api('/api/my/pages/' + p.id, patch); load(true); } catch (e) { toast(e.message, true); } };
const ns = $('niche'); ns.innerHTML = '<option value="">None (set it yourself)</option>' + STYLES.niches.map(n => '<option value="' + n.key + '"' + (d.niche === n.key ? ' selected' : '') + '>' + esc(n.label) + ' \u00b7 ' + esc(n.blurb) + '</option>').join(''); ns.onchange = () => setLook({ niche: ns.value });
+21
View File
@@ -32,6 +32,27 @@
const best = (s.hours || []).map((n, i) => [n, i]).sort((a, b) => b[0] - a[0]).slice(0, 3).filter(x => x[0]).map(x => x[1] + ':00');
$('hourNote').textContent = best.length ? 'Busiest hours (UTC): ' + best.join(', ') + '. Hour rules per link come next.' : 'No clicks yet.';
$('convRows').innerHTML = kv(s.conversions || [], 0);
// -- Pages and Zones (2026-10-10): one bar per Central day in the range (empty days are zero), totals, per-item table
const dayBars = (barsId, axisId, rows, f, g, empty) => {
const map = {}; (rows || []).forEach(r => { map[r.day] = r; });
const ser = keys.map(k => ({ day: k, a: map[k] ? f(map[k]) : 0, b: map[k] ? g(map[k]) : 0 }));
const max = Math.max(1, ...ser.map(x => Math.max(x.a, x.b))); const any = ser.some(x => x.a || x.b);
const el = $(barsId); el.style.gridTemplateColumns = 'repeat(' + keys.length + ',minmax(0,1fr))'; el.classList.add('stack');
el.innerHTML = ser.map(x => '<i class="' + (x.a ? '' : 'dim') + '" style="height:' + Math.round(x.a / max * 100) + '%" title="' + x.day + ' · ' + x.a + ' / ' + x.b + '">' + (x.b ? '<b style="height:' + Math.round(x.b / x.a * 100 || 0) + '%"></b>' : '') + '</i>').join('');
$(axisId).innerHTML = any ? '<span>' + keys[0] + '</span><span>' + keys[Math.floor(keys.length / 2)] + '</span><span>' + keys[keys.length - 1] + '</span>' : '<span class="muted">' + empty + '</span>';
};
const mini = rows => rows.map(([k, v]) => '<div class="m"><span class="k">' + esc(k) + '</span><span class="v">' + v + '</span></div>').join('');
const pg = s.pages || { byDay: [], byPage: [] };
// bar = views, inner bar = leads (leads as a share of that day's views; a day with leads but no views still shows)
dayBars('pgBars', 'pgAxis', pg.byDay, d => Math.max(d.views, d.leads), d => d.leads, 'no page views yet');
$('pgBars').querySelectorAll('i b').forEach(b => { b.style.background = 'var(--sig)'; });
$('pgTiles').innerHTML = mini([['Views', fmt(pg.views)], ['Unique', fmt(pg.uniques)], ['Clicks through', fmt(pg.clicks)], ['Leads', fmt(pg.leads)]]);
$('pgRows').innerHTML = (pg.byPage || []).length ? pg.byPage.map(x => '<div class="rw"><a href="/pages" style="text-decoration:none;color:var(--ink)"><b>' + esc(x.title) + '</b><br><span class="mono muted" style="font-size:11px">' + esc(x.type) + ' · ' + (x.status === 'published' ? '<span class="ok">live</span>' : 'draft') + '</span></a><span class="r num">' + fmt(x.views) + '</span><span class="r num">' + fmt(x.uniques) + '</span><span class="r num">' + fmt(x.clicks) + '</span><span class="r num">' + fmt(x.leads) + '</span></div>').join('') : '<div class="rw"><span class="muted">No pages yet. <a href="/pages">Make one</a>.</span></div>';
const zn = s.zones || { byDay: [], byZone: [] };
// bar = all views, lighter inner share = the ones that were NOT viewable
dayBars('znBars', 'znAxis', zn.byDay, d => d.views, d => d.views - d.viewable, 'no zone views yet');
$('znTiles').innerHTML = mini([['Views', fmt(zn.views)], ['Viewable', fmt(zn.viewable) + (zn.views ? ' <small class="muted" style="font-size:11px">' + Math.round(zn.viewable / zn.views * 100) + '%</small>' : '')], ['Clicks', fmt(zn.clicks)], ['Credits earned', fmt(zn.credits)]]);
$('znRows').innerHTML = (zn.byZone || []).length ? zn.byZone.map(x => '<div class="rw"><a href="/zones" style="text-decoration:none;color:var(--ink)"><b>' + esc(x.name) + '</b><br><span class="mono muted" style="font-size:11px">' + esc(x.site) + ' · ' + esc(x.size) + (x.paused ? ' · <span class="warn">paused</span>' : x.active ? '' : ' · off') + '</span></a><span class="r num">' + fmt(x.views) + '</span><span class="r num">' + fmt(x.viewable) + (x.viewablePct != null ? ' <span class="muted" style="font-size:10px">' + x.viewablePct + '%</span>' : '') + '</span><span class="r num">' + fmt(x.clicks) + '</span><span class="r num">' + fmt(x.credits) + '</span></div>').join('') : '<div class="rw"><span class="muted">No zones yet. <a href="/zones">Add one</a>.</span></div>';
}
CR.requireSession(load);
})();
+4 -1
View File
@@ -26,6 +26,9 @@
.ed{display:grid;gap:10px} .ed textarea{min-height:90px;resize:vertical}
.pal{display:flex;gap:6px} .pal button{width:28px;height:28px;border-radius:50%;border:2px solid transparent;cursor:pointer} .pal button.on{border-color:var(--ink)}
.leads .rw{grid-template-columns:minmax(0,1.4fr) minmax(0,1fr) 110px}
.imgrow{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:-4px 0 0}
.imgstrip{display:flex;gap:6px;flex-wrap:wrap;align-items:flex-start;min-height:12px}.imgstrip .im{position:relative;width:64px;height:48px;border:1px solid var(--line);border-radius:7px;overflow:hidden;cursor:pointer;background:var(--panel-2);display:block}.imgstrip .im img{width:100%;height:100%;object-fit:cover;display:block}.imgstrip .im:hover{border-color:var(--accent)}
.imgstrip .x{position:absolute;top:2px;right:2px;width:18px;height:18px;border-radius:50%;border:0;background:rgba(0,0,0,.65);color:#fff;font:700 13px/18px var(--body);padding:0;cursor:pointer}.imgstrip .x:hover{background:var(--bad,#c0392b)}
@media (max-width:900px){.ws{grid-template-columns:1fr}.side{border-left:0;border-top:1px solid var(--line)}.body{padding:12px 16px}.types{grid-template-columns:1fr}}
</style>
</head>
@@ -70,6 +73,6 @@
</div>
</div>
<script src="/assets/cr-shell.js?v=20261008c"></script>
<script src="/assets/pages-screen.js?v=20261008b"></script>
<script src="/assets/pages-screen.js?v=20261010a"></script>
</body>
</html>
+27 -2
View File
@@ -14,7 +14,12 @@
.kv{display:grid;grid-template-columns:minmax(0,1fr) 60px 70px;gap:8px;font-size:12px;align-items:center}
.range{display:flex;border:1px solid var(--line-strong);border-radius:var(--r);overflow:hidden;background:var(--panel-2)} .range button{background:transparent;border:0;color:var(--muted);font-family:var(--mono);font-size:12px;padding:5px 10px;cursor:pointer} .range button.on{background:var(--ink);color:#fff}
.top .hd,.top .rw{grid-template-columns:minmax(0,1fr) 80px 80px 80px}
@media (max-width:900px){.two,.grid2{grid-template-columns:1fr}.body{padding:12px 16px}}
.sect{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
.ph{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px}.legend{display:flex;gap:14px;font-size:11px;color:var(--ink-2)}.legend i{display:inline-block;width:10px;height:10px;vertical-align:middle;margin-right:5px}
.bars.stack i{position:relative}.bars.stack i b{position:absolute;left:0;right:0;bottom:0;display:block;background:var(--line);border-radius:2px 2px 0 0}.bars i.ghost{background:var(--line)}
.mini{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;margin-top:10px}.mini .m{background:var(--panel-2);border:1px solid var(--line);border-radius:6px;padding:8px 10px;display:grid;gap:2px}.mini .m .k{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}.mini .m .v{font-family:var(--display);font-weight:700;font-size:20px;color:var(--ink);font-variant-numeric:tabular-nums}
.pages .hd,.pages .rw,.zones .hd,.zones .rw{grid-template-columns:minmax(0,1fr) 60px 60px 60px 60px;gap:8px}
@media (max-width:900px){.two,.grid2,.sect{grid-template-columns:1fr}.body{padding:12px 16px}.mini{grid-template-columns:repeat(2,minmax(0,1fr))}.pages .hd,.pages .rw,.zones .hd,.zones .rw{grid-template-columns:minmax(0,1fr) 48px 48px 48px 48px;gap:6px;padding:10px 12px;font-size:12px}}
</style>
</head>
<body>
@@ -36,9 +41,29 @@
<div class="panel"><h2>Conversions</h2><div class="kv" id="convRows"></div><div class="muted">Joins, wallets and purchases matched to a click on one of your links, plus anything a partner reported by postback.</div></div>
</div>
</div>
<!-- Pages: views, uniques, clicks through and leads on the member's bridge / review / squeeze pages (2026-10-10) -->
<div class="sec">Pages</div>
<div class="two sect">
<div class="panel">
<div class="ph"><h2>Page views by day</h2><div class="legend"><span><i style="background:var(--accent)"></i>views</span><span><i style="background:var(--sig)"></i>leads</span></div></div>
<div class="bars" id="pgBars" style="height:150px"></div><div class="axis" id="pgAxis"></div>
<div class="mini" id="pgTiles"></div>
</div>
<div class="panel"><h2>By page</h2><div class="tbl pages"><div class="hd"><span>Page</span><span class="r">Views</span><span class="r">Unique</span><span class="r">Clicks</span><span class="r">Leads</span></div><div id="pgRows"></div></div><div class="muted" style="margin-top:8px">Views exclude bots. Clicks are people who pressed the button on the page. Leads came in through the page's own form. <a href="/pages">Open Pages</a></div></div>
</div>
<!-- Zones: ad-slot impressions on the member's own sites and the credits they earned (2026-10-10) -->
<div class="sec">Zones</div>
<div class="two sect">
<div class="panel">
<div class="ph"><h2>Zone views by day</h2><div class="legend"><span><i style="background:var(--accent)"></i>viewable</span><span><i style="background:var(--line)"></i>not seen</span></div></div>
<div class="bars" id="znBars" style="height:150px"></div><div class="axis" id="znAxis"></div>
<div class="mini" id="znTiles"></div>
</div>
<div class="panel"><h2>By zone</h2><div class="tbl zones"><div class="hd"><span>Zone</span><span class="r">Views</span><span class="r">Viewable</span><span class="r">Clicks</span><span class="r">Credits</span></div><div id="znRows"></div></div><div class="muted" style="margin-top:8px">A view counts when the tag loads; viewable means at least half the banner was on screen for a second. Credits are the zone's all-time earnings. <a href="/zones">Open Zones</a></div></div>
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20261008c"></script>
<script src="/assets/reports.js?v=20260929c"></script>
<script src="/assets/reports.js?v=20261010a"></script>
</body>
</html>
+49 -4
View File
@@ -41,6 +41,8 @@ const carry = require('./carry'); // sponsor carry-over: engine acti
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 domains = require('./domains'); // link-domain pool by channel + six-hourly safety checks; burned domains leave the pool (2026-10-10)
const zonereport = require('./zonereport'); // read-only zone numbers for member Reports (2026-10-10)
const zones = require('./zones'); // ad zones on members' own sites (2026-09-29)
const nas = require('./nas');
const audiences = require('./audiences'); // first-party retargeting (2026-10-08) // only asked whether syndication is on (the status strip)
@@ -416,8 +418,12 @@ async function boot() {
setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
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 ''; } } });
pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, 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 });
// link-domain pool: channels live in site.json (linkDomainChannels), check state in domains.json; a burn alerts the admin once
domains.init({ dataDir: DATA_DIR, siteConfig, saveSite: patch => fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(siteConfig(), patch), null, 2)),
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) await telegramSend(sc.telegramAdminChatId, text); else if (ADMIN_EMAIL && mailer.hasKey()) await mailer.send(ADMIN_EMAIL, 'LinkSpin: link domain burned', text.replace(/<[^>]+>/g, '')); } });
zonereport.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 });
@@ -1983,11 +1989,48 @@ const server = http.createServer(async (req, res) => {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
const r = await zones.adminSet(m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r);
}
// -- hosted page images: /u/pages/<owner-hash>/<id>.<ext>, only files the pages index knows, a year of cache (2026-10-10)
m = /^\/u\/pages\/([a-f0-9]{16})\/([a-f0-9]{12})\.(png|jpg|webp)$/.exec(p);
if (m && (req.method === 'GET' || req.method === 'HEAD')) {
const f = pages.imageFile(m[1], m[2], m[3]); if (!f) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
return fs.readFile(f.file, (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } res.writeHead(200, { 'Content-Type': f.mime, 'Content-Length': String(data.length), 'Cache-Control': 'public, max-age=31536000, immutable', 'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'inline', 'Access-Control-Allow-Origin': '*' }); res.end(req.method === 'HEAD' ? '' : data); });
}
// -- the link-domain pool for the member Links screen: live (not burned, not reserve) hosts with their channel
if (p === '/api/my/link-hosts' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const hs = domains.hosts(); return json(res, 200, { hosts: hs.length ? hs : [{ host: SITE_HOST, channel: 'email', label: 'Email', note: 'The app host (no link domains are live)' }], channels: domains.CHANNELS }, { 'Cache-Control': 'no-store' });
}
if (p === '/api/my/pages' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const hosts = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(x => x && !x.startsWith('www.'));
const hosts = domains.live(); // burned or reserve domains are never handed out for new pages
const ph = pagesHost(); const pageBase = ph ? 'https://' + ph + '/' : 'https://' + (hosts[0] || SITE_HOST) + '/p/';
return json(res, 200, { pages: await pages.list(s.email), hosts: ph ? [ph] : (hosts.length ? hosts : [SITE_HOST]), pageBase, types: pages.TYPES, styles: require('./pagestyle').catalog() }, { 'Cache-Control': 'no-store' });
return json(res, 200, { pages: await pages.list(s.email), hosts: ph ? [ph] : (hosts.length ? hosts : [SITE_HOST]), pageBase, types: pages.TYPES, styles: require('./pagestyle').catalog(), providers: pages.providers(), images: await pages.images(s.email), imageMax: pages.IMG_MAX, imageBytes: pages.IMG_BYTES }, { 'Cache-Control': 'no-store' });
}
if (p === '/api/my/pages/upload' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const up = await pages.readUpload(req); if (up.error) return json(res, 400, up);
const r = await pages.uploadImage(s.email, up.buf, up.ct); return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/pages\/images\/([a-f0-9]{12})$/.exec(p);
if (m && 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); if (!b.remove) return json(res, 400, { error: 'Nothing to do.' });
const r = await pages.removeImage(s.email, m[1]); return json(res, r.error ? 400 : 200, r);
}
// -- admin: the link-domain pool (channel per domain, last safety check, burned flag, check now / clear / pull)
if (p === '/api/admin/domains' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
return json(res, 200, { domains: domains.all(), channels: domains.CHANNELS, labels: domains.LABEL, notes: domains.NOTE, gsb: !!String(process.env.GSB_API_KEY || '').trim() }, { 'Cache-Control': 'no-store' });
}
if (p === '/api/admin/domains' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
const b = await readBody(req); let r;
if (b.action === 'check') r = b.domain ? await domains.check(b.domain) : { ok: true, results: await domains.checkAll() };
else if (b.action === 'channel') r = domains.setChannel(b.domain, b.channel);
else if (b.action === 'clear') r = domains.clear(b.domain);
else if (b.action === 'burn') r = domains.burn(b.domain, b.reason);
else r = { error: 'Unknown action.' };
return json(res, r.error ? 400 : 200, Object.assign(r, { domains: domains.all() }));
}
if (p === '/api/my/pages' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
@@ -2014,7 +2057,9 @@ const server = http.createServer(async (req, res) => {
if (p === '/api/my/reports' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const days = Math.max(1, Math.min(365, Number(u.searchParams.get('days')) || 30));
return json(res, 200, await rotator.summary(s.email, days), { 'Cache-Control': 'no-store' });
// spins (the rotator summary, spread at the top level so older report screens keep working) + pages + zones (2026-10-10)
const [spins, pg, zn] = await Promise.all([rotator.summary(s.email, days), pages.summary(s.email, days), zonereport.summary(s.email, days)]);
return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, days: spins.days, range: days }), { 'Cache-Control': 'no-store' });
}
if (p === '/api/my/postbacks' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
+31
View File
@@ -0,0 +1,31 @@
// Zone numbers for the member Reports screen (2026-10-10). A READ-ONLY view over DATA_DIR/zones.json (the store
// zones.js owns): views, viewable views, clicks and credits for the member's zones over the chosen days, by Central
// day and by zone. Counting mirrors zones.statusOf / pubZone: bots excluded, `ok` = viewable, `k` = clicked.
// Credits per zone are the lifetime meter zones.js keeps (z.credits); there is no dated credit log in the store yet.
// Parsed on demand with a short cache so a 300k-impression file is not re-read on every click of the range picker.
// Move this into zones.js as zones.summary(owner, days) when that file is free.
'use strict';
const fs = require('fs');
const path = require('path');
let DATA_DIR = null; let cache = { at: 0, mtime: 0, db: null };
const DAY = 86400000, TTL = 30 * 1000;
function init(opts) { DATA_DIR = opts.dataDir; }
function load() {
const file = path.join(DATA_DIR, 'zones.json'); let mtime = 0; try { mtime = fs.statSync(file).mtimeMs; } catch (e) { return { zones: [], imps: [] }; }
if (cache.db && cache.mtime === mtime && Date.now() - cache.at < TTL) return cache.db;
let db; try { db = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { db = {}; }
db = { zones: Array.isArray(db.zones) ? db.zones : [], imps: Array.isArray(db.imps) ? db.imps : [] };
cache = { at: Date.now(), mtime, db }; return db;
}
const norm = e => String(e || '').trim().toLowerCase();
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
async function summary(owner, days) {
const db = load(); const mine = db.zones.filter(z => z.owner === norm(owner)); const ids = new Set(mine.map(z => z.id));
const since = Date.now() - (Number(days) || 30) * DAY;
const imps = db.imps.filter(i => ids.has(i.z) && i.ts >= since && !i.bot);
const dayMap = {}; for (const i of imps) { const d = dayMap[ctDay(i.ts)] = dayMap[ctDay(i.ts)] || { day: ctDay(i.ts), views: 0, viewable: 0, clicks: 0 }; d.views++; if (i.ok) d.viewable++; if (i.k) d.clicks++; }
const byDay = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1);
const byZone = mine.map(z => { const zi = imps.filter(i => i.z === z.id); const seen = zi.filter(i => i.ok).length; return { id: z.id, name: z.name, site: z.site, size: z.size, active: !!z.active, paused: !!z.adminPaused, views: zi.length, viewable: seen, viewablePct: zi.length ? Math.round(seen / zi.length * 100) : null, clicks: zi.filter(i => i.k).length, paid: zi.filter(i => i.ok && !i.house && !i.off).length, credits: z.credits || 0 }; }).sort((a, b) => b.views - a.views);
return { zones: mine.length, views: imps.length, viewable: imps.filter(i => i.ok).length, clicks: imps.filter(i => i.k).length, paid: imps.filter(i => i.ok && !i.house && !i.off).length, credits: mine.reduce((n, z) => n + (z.credits || 0), 0), byDay, byZone };
}
module.exports = { init, summary };