diff --git a/domains.js b/domains.js new file mode 100644 index 0000000..cd1191c --- /dev/null +++ b/domains.js @@ -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 = '⚠️ LinkSpin · link domain ' + host + ' (' + (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 }; diff --git a/formrestyle.js b/formrestyle.js index 73f7711..cd55268 100644 --- a/formrestyle.js +++ b/formrestyle.js @@ -62,4 +62,43 @@ function html(parsed, defaultButton) { const inputs = parsed.fields.map(f => '').join('\n'); return [open, hidden, inputs, '', ''].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 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(//gi); if (!forms || !forms.length) return null; + const tag = forms[0].match(/]*>/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 }; diff --git a/pages.js b/pages.js index 44f3ab0..f382a1a 100644 --- a/pages.js +++ b/pages.js @@ -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//. +// and served at /u/pages//.. 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: } +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//., 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 }; diff --git a/public/admin.html b/public/admin.html index 3b45517..858a245 100644 --- a/public/admin.html +++ b/public/admin.html @@ -99,6 +99,7 @@ + @@ -294,6 +295,14 @@

+ - + diff --git a/public/reports.html b/public/reports.html index 9cf20e7..aee1af2 100644 --- a/public/reports.html +++ b/public/reports.html @@ -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}} @@ -36,9 +41,29 @@

Conversions

Joins, wallets and purchases matched to a click on one of your links, plus anything a partner reported by postback.
+ +
Pages
+
+
+

Page views by day

viewsleads
+
+
+
+

By page

PageViewsUniqueClicksLeads
Views exclude bots. Clicks are people who pressed the button on the page. Leads came in through the page's own form. Open Pages
+
+ +
Zones
+
+
+

Zone views by day

viewablenot seen
+
+
+
+

By zone

ZoneViewsViewableClicksCredits
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. Open Zones
+
- + diff --git a/server.js b/server.js index 9977d7e..dd508f5 100644 --- a/server.js +++ b/server.js @@ -42,6 +42,8 @@ const rotator = require('./rotator'); const health = require('./health'); // destination health checks + auto-pause (2026-10-10) 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/ (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) @@ -421,8 +423,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 }); @@ -1993,11 +1999,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//., 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.' }); @@ -2024,7 +2067,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.' }); diff --git a/zonereport.js b/zonereport.js new file mode 100644 index 0000000..bb8e1b2 --- /dev/null +++ b/zonereport.js @@ -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 };