Files
linkspin/pages.js
T

175 lines
19 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LinkSpin Pages (2026-09-29): member pages (bridge, review, squeeze) built from a scan of the destination plus a
// one-line angle, rendered by pagerender.js, served at /p/<slug> on the app host and every link domain. Leads from
// our own capture form belong to the member (their list, exportable). Provider forms go through parse-or-refuse.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const https = require('https');
const http = require('http');
const dns = require('dns').promises;
const net = require('net');
const render = require('./pagerender');
const style = require('./pagestyle');
const formrestyle = require('./formrestyle');
let DATA_DIR = null, ownHosts = () => [], keyFn = () => '';
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] = []; },
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(); }
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 : ''; };
// people type bare domains ("cryptoteambuild.com"): give them the scheme before judging the address (Marty 2026-10-07)
const withScheme = u => { const s = String(u || '').trim(); return s && !/^[a-z][a-z0-9+.-]*:\/\//i.test(s) && /^[^\s\/]+\.[^\s]+/.test(s) ? 'https://' + s : s; };
const slugify = t => (String(t || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'page') + '-' + crypto.randomBytes(3).toString('hex');
const strs = (arr, n, len) => (Array.isArray(arr) ? arr : String(arr || '').split('\n')).map(x => String(x).trim()).filter(Boolean).slice(0, n).map(x => x.slice(0, len));
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 };
}
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; }
function bySlug(slug) { return J.db.pages.find(p => p.slug === String(slug || '').toLowerCase()) || null; }
function sanitizeContent(c, type) {
c = c || {}; const out = {};
out.eyebrow = String(c.eyebrow || '').slice(0, 80); out.headline = String(c.headline || '').slice(0, 160); out.sub = String(c.sub || '').slice(0, 300);
out.body = String(c.body || '').slice(0, 8000); out.bullets = strs(c.bullets, 8, 160);
out.cta = { text: String(c.cta && c.cta.text || '').slice(0, 60), url: cleanUrl(c.cta && c.cta.url) };
out.image = cleanUrl(c.image); out.imageAlt = String(c.imageAlt || '').slice(0, 120);
out.privacy = String(c.privacy || '').slice(0, 200); out.disclaimer = String(c.disclaimer || '').slice(0, 300);
out.price = String(c.price || '').slice(0, 24); // optional '$17' chip on the split visual
if (type === 'review') { out.rating = Math.max(0, Math.min(5, Number(c.rating) || 0)); out.pros = strs(c.pros, 6, 140); out.cons = strs(c.cons, 6, 140); out.verdict = String(c.verdict || '').slice(0, 400); }
if (type === 'bridge') { out.bonus = String(c.bonus || '').slice(0, 2000); out.bonusTitle = String(c.bonusTitle || '').slice(0, 100); }
if (type === 'squeeze') { out.formEmbed = String(c.formEmbed || '').slice(0, formrestyle.EMBED_MAX_CHARS); }
return out;
}
// the three knobs + niche; a niche preset sets design + palette unless the body overrides them (a preset is a start, not a lock)
function designFrom(body, cur) {
cur = cur || {}; const niche = body.niche != null ? style.nicheKey(body.niche) : (cur.niche || ''); const preset = niche ? style.NICHES[niche] : null;
const palette = body.palette != null ? style.paletteKey(body.palette) : (body.niche != null && preset ? preset.palette : style.paletteKey(cur.palette));
const design = body.design != null ? style.designKey(body.design) : (body.niche != null && preset ? preset.design : style.designKey(cur.design));
const layout = body.layout != null ? style.layoutKey(body.layout) : style.layoutKey(cur.layout || (body.niche != null && preset ? 'split' : 'stack'));
const hero = body.niche != null && body.niche !== cur.niche ? 0 : style.heroIndex(niche, body.hero != null ? body.hero : cur.hero);
return { palette, design, layout, niche, hero };
}
async function create(owner, body) {
if (J.db.pages.filter(p => p.owner === norm(owner)).length >= 200) return { error: 'That is a lot of pages. Remove some first.' };
const type = TYPES.includes(body.type) ? body.type : 'bridge';
const title = String(body.title || (body.content && body.content.headline) || 'Untitled page').trim().slice(0, 100);
const content = sanitizeContent(body.content, type);
if (type === 'squeeze' && content.formEmbed) { const why = formrestyle.problem(content.formEmbed); if (why) return { error: why }; }
const p = { id: crypto.randomBytes(5).toString('hex'), owner: norm(owner), slug: slugify(title), type, title, status: 'draft', design: designFrom(body, null), content, scan: body.scan && typeof body.scan === 'object' ? { url: cleanUrl(body.scan.url), title: String(body.scan.title || '').slice(0, 200), description: String(body.scan.description || '').slice(0, 300), h1: String(body.scan.h1 || '').slice(0, 200), image: cleanUrl(body.scan.image), headings: strs(body.scan.headings, 8, 120), bullets: strs(body.scan.bullets, 8, 140) } : null, angle: String(body.angle || '').slice(0, 160), created: Date.now(), updated: Date.now() };
J.db.pages.push(p); J.save(); return { ok: true, page: pub(p) };
}
async function update(owner, id, body) {
const p = J.db.pages.find(p => p.id === String(id) && p.owner === norm(owner)); if (!p) return { error: 'No such page.' };
if (body.remove) { J.db.pages = J.db.pages.filter(x => x !== p); J.save(); return { ok: true, removed: true }; }
if (body.title != null) p.title = String(body.title).trim().slice(0, 100) || p.title;
if (body.type != null && TYPES.includes(body.type)) p.type = body.type;
if (body.palette != null || body.design != null || body.layout != null || body.niche != null || body.hero != null) p.design = designFrom(body, p.design || {});
if (body.angle != null) p.angle = String(body.angle).slice(0, 160);
if (body.content != null) { const c = sanitizeContent(Object.assign({}, p.content, body.content), p.type); if (p.type === 'squeeze' && c.formEmbed) { const why = formrestyle.problem(c.formEmbed); if (why) return { error: why }; } p.content = c; }
if (body.status != null) { if (body.status === 'published') { if (!p.content.headline) return { error: 'Give the page a headline before publishing.' }; if (p.type !== 'squeeze' && !p.content.cta.url) return { error: 'Add the button link (where the page sends people) before publishing.' }; p.status = 'published'; } else p.status = 'draft'; }
p.updated = Date.now(); J.save(); return { ok: true, page: pub(p) };
}
// -- serving
function html(p, opts) { return render.render(p, opts); }
function view(p, req, kind) {
const ua = String(req.headers['user-agent'] || ''); const bot = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i.test(ua) || !ua;
const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
const v = crypto.createHash('sha256').update(new Date().toISOString().slice(0, 10) + '|' + ip + '|' + ua).digest('hex').slice(0, 16);
if (!bot) { J.db.views.push({ p: p.id, ts: Date.now(), v, k: kind || 'view' }); if (J.db.views.length > 200000) J.db.views = J.db.views.slice(-150000); J.save(); }
}
// -- leads (our own capture form): the member's list
async function lead(slug, body, req) {
const p = bySlug(slug); if (!p || p.status !== 'published') return { error: 'That page is not live.' };
if (String(body.website || '').trim()) return { ok: true, next: p.content.cta.url || '/' }; // honeypot filled: pretend, never store
const email = norm(body.email); if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return { error: 'That email address does not look right.' };
const name = String(body.name || '').trim().slice(0, 60); const lsid = /^[a-z0-9]{6,20}$/i.test(String(body.lsid || '')) ? String(body.lsid) : '';
const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
if (!J.db.leads.some(l => l.p === p.id && l.email === email)) { J.db.leads.push({ p: p.id, owner: p.owner, email, name, ts: Date.now(), lsid, ip: crypto.createHash('sha256').update(ip).digest('hex').slice(0, 12) }); J.save(); }
return { ok: true, next: p.content.cta.url || '/', owner: p.owner, lsid, pageId: p.id };
}
async function leads(owner, id) { const p = id ? J.db.pages.find(p => p.id === String(id) && p.owner === norm(owner)) : null; return J.db.leads.filter(l => l.owner === norm(owner) && (!id || l.p === (p && p.id))).sort((a, b) => b.ts - a.ts).map(l => ({ page: (J.db.pages.find(p => p.id === l.p) || {}).title || '', email: l.email, name: l.name, ts: l.ts, lsid: l.lsid })); }
function csv(rows) { const q = s => '"' + String(s == null ? '' : s).replace(/"/g, '""') + '"'; return ['page,email,name,when'].concat(rows.map(r => [r.page, r.email, r.name, new Date(r.ts).toISOString()].map(q).join(','))).join('\r\n') + '\r\n'; }
// -- the URL scanner: what the destination says about itself (public hosts only, small, quick)
function isPrivateIp(ip) { if (net.isIPv4(ip)) { const p = ip.split('.').map(Number); return p[0] === 10 || p[0] === 127 || p[0] === 0 || (p[0] === 169 && p[1] === 254) || (p[0] === 172 && p[1] >= 16 && p[1] <= 31) || (p[0] === 192 && p[1] === 168); } return true; }
function fetchText(url, hops) {
return new Promise((resolve, reject) => {
let u; try { u = new URL(url); } catch (e) { return reject(new Error('bad url')); }
const mod = u.protocol === 'https:' ? https : http;
const req = mod.get(u, { headers: { 'User-Agent': 'Mozilla/5.0 (compatible; LinkSpinScanner/1.0)', Accept: 'text/html,*/*' }, timeout: 8000 }, res => {
if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location && (hops || 0) < 3) { res.resume(); return resolve(fetchText(new URL(res.headers.location, u).toString(), (hops || 0) + 1)); }
let d = ''; res.setEncoding('utf8'); res.on('data', c => { d += c; if (d.length > 600000) { req.destroy(); resolve({ status: res.statusCode, body: d, url: u.toString() }); } }); res.on('end', () => resolve({ status: res.statusCode, body: d, url: u.toString() }));
});
req.on('timeout', () => req.destroy(new Error('timeout'))); req.on('error', reject);
});
}
const meta = (h, name) => { const m = h.match(new RegExp('<meta[^>]+(?:property|name)=["\']' + name + '["\'][^>]*content=["\']([^"\']*)', 'i')) || h.match(new RegExp('<meta[^>]+content=["\']([^"\']*)["\'][^>]*(?:property|name)=["\']' + name + '["\']', 'i')); return m ? m[1].trim() : ''; };
const strip = s => String(s || '').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&#39;|&apos;/g, "'").replace(/&quot;/g, '"').replace(/\s+/g, ' ').trim();
async function scan(url) {
url = cleanUrl(withScheme(url)); if (!url) return { error: 'Give the scanner a website address, like example.com or https://example.com/page.' };
const host = new URL(url).hostname.toLowerCase();
if (!host.includes('.') || net.isIP(host)) return { error: 'Scan a public website address.' };
try { const rs = await dns.lookup(host, { all: true }); if (!rs.length || rs.some(r => isPrivateIp(r.address))) return { error: 'That host is not reachable from here.' }; } catch (e) { return { error: 'That host does not resolve.' }; }
let r; try { r = await fetchText(url); } catch (e) { return { error: 'Could not fetch that page (' + e.message + ').' }; }
const h = r.body || '';
const title = strip(meta(h, 'og:title') || (h.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || '');
const desc = strip(meta(h, 'og:description') || meta(h, 'description'));
const h1 = strip((h.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i) || [])[1] || '');
const image = cleanUrl(meta(h, 'og:image')); const color = (meta(h, 'theme-color') || '').slice(0, 9);
const heads = []; const re = /<h[23][^>]*>([\s\S]*?)<\/h[23]>/gi; let m; while ((m = re.exec(h)) && heads.length < 8) { const t = strip(m[1]); if (t && t.length < 120) heads.push(t); }
const lis = []; const re2 = /<li[^>]*>([\s\S]*?)<\/li>/gi; while ((m = re2.exec(h)) && lis.length < 12) { const t = strip(m[1]); if (t && t.length > 12 && t.length < 140) lis.push(t); }
return { ok: true, scan: { url: r.url, status: r.status, title: title.slice(0, 200), description: desc.slice(0, 300), h1: h1.slice(0, 200), image, color, headings: heads, bullets: lis.slice(0, 8), scannedAt: Date.now() } };
}
// -- copy: from the scan + angle, by the model when a key exists, else a plain template
// "Brand | Tagline" page titles: the brand names the site, the tagline is the headline. Separators: | — – - · : ::
function splitTitle(title, url) {
const t = String(title || '').trim(); if (!t) return { brand: '', tagline: '' };
const GENERIC = /^(home|homepage|welcome|index|official site|official website|main page|start)$/i;
const parts = t.split(/\s+[|\u2014\u2013\-\u00b7]+\s+|\s*\|\s*|:\s+/).map(x => x.trim()).filter(x => x && !GENERIC.test(x));
if (parts.length === 1) return { brand: parts[0], tagline: '' };
if (parts.length < 2) return { brand: t, tagline: '' };
let host = ''; try { host = new URL(url || '').hostname.replace(/^www\./, '').toLowerCase(); } catch (e) {}
const bare = host.replace(/\.[a-z]+$/, '');
const looksBrand = x => { const l = x.toLowerCase().replace(/\s+/g, ''); return !!host && (l === host || l === bare || l.includes(host) || (bare.length > 3 && l.includes(bare))); };
let brand = parts.find(looksBrand) || parts.slice().sort((a, b) => a.length - b.length)[0];
const rest = parts.filter(x => x !== brand);
return { brand, tagline: rest.slice().sort((a, b) => b.length - a.length)[0] || '' };
}
function templateCopy(type, scanRes, angle, cta) {
const s = Object.assign({ bullets: [], headings: [] }, scanRes || {}); const a = String(angle || '').trim();
const st = splitTitle(s.title, s.url); const name = st.brand || s.h1 || 'this page';
const head = st.tagline || s.h1 || name;
const base = { eyebrow: type === 'review' ? 'An honest look' : 'Before you click through', headline: a || (type === 'squeeze' ? 'Get the details on ' + name : head), sub: s.description || '', bullets: (s.bullets || []).slice(0, 5), cta: { text: type === 'squeeze' ? 'Send me the details' : 'Take a look', url: cta || s.url || '' }, image: s.image || '', body: '' };
if (type === 'review') Object.assign(base, { rating: 4, pros: (s.bullets || []).slice(0, 3), cons: ['Results depend on the work you put in'], verdict: 'Worth a look if ' + (a || 'this fits what you are already doing') + '.' });
if (type === 'bridge') base.body = (a ? a + '\n\n' : '') + (s.description ? s.description + '\n\n' : '') + 'I am sending you to ' + name + ' because it does what it says. Take a look, then decide.';
return base;
}
function llm(messages) {
const key = keyFn(); if (!key) return Promise.reject(new Error('nokey'));
return new Promise((resolve, reject) => {
const data = JSON.stringify({ model: 'deepseek/deepseek-chat', temperature: 0.7, max_tokens: 1400, messages });
const req = https.request({ hostname: 'openrouter.ai', path: '/api/v1/chat/completions', method: 'POST', headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) }, timeout: 60000 }, res => { let d = ''; res.on('data', c => d += c); res.on('end', () => { try { const j = JSON.parse(d); resolve(String(j.choices[0].message.content || '')); } catch (e) { reject(new Error('openrouter ' + res.statusCode)); } }); });
req.on('timeout', () => req.destroy(new Error('timeout'))); req.on('error', reject); req.write(data); req.end();
});
}
async function write(owner, id, body) {
const p = J.db.pages.find(p => p.id === String(id) && p.owner === norm(owner)); if (!p) return { error: 'No such page.' };
const s = p.scan || {}; const angle = String(body.angle != null ? body.angle : p.angle || '').slice(0, 160); const cta = cleanUrl(body.cta || (p.content.cta && p.content.cta.url) || s.url);
let content = templateCopy(p.type, s, angle, cta), by = 'template';
try {
const ask = 'Write a ' + p.type + ' page for an internet marketer. Facts about the destination: ' + JSON.stringify({ site: splitTitle(s.title, s.url).brand || s.title, tagline: splitTitle(s.title, s.url).tagline || undefined, description: s.description, headline: s.h1, points: s.bullets, headings: s.headings }).slice(0, 2500) + '. Angle in the marketer\'s words: "' + angle + '". Rules: plain, specific, no hype, no income promises, no em dashes, US English, first person. Return ONLY JSON with keys: eyebrow (<=60 chars), headline (<=90), sub (<=200), bullets (3-5 short strings), body (2-4 short paragraphs separated by blank lines, or empty for squeeze)' + (p.type === 'review' ? ', rating (1-5), pros (3), cons (2), verdict (<=200)' : '') + (p.type === 'bridge' ? ', bonusTitle, bonus (one short paragraph or empty)' : '') + ', ctaText (<=40).';
const txt = await llm([{ role: 'system', content: 'You write short, honest marketing pages. Output JSON only.' }, { role: 'user', content: ask }]);
const j = JSON.parse((txt.match(/\{[\s\S]*\}/) || ['{}'])[0]);
if (j.headline) { content = Object.assign(content, { eyebrow: j.eyebrow, headline: j.headline, sub: j.sub, bullets: strs(j.bullets, 6, 160), body: j.body || '', rating: j.rating, pros: strs(j.pros, 6, 140), cons: strs(j.cons, 6, 140), verdict: j.verdict, bonusTitle: j.bonusTitle, bonus: j.bonus, cta: { text: j.ctaText || content.cta.text, url: cta } }); by = 'model'; }
} catch (e) { if (e.message !== 'nokey') console.error('pages write', e.message); }
p.content = sanitizeContent(Object.assign({}, p.content, content, { formEmbed: p.content.formEmbed }), p.type); p.angle = angle; p.updated = Date.now(); J.save();
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 };