Pages: bridge, review and squeeze pages from a scan plus an angle; parse-or-refuse forms; member-owned leads with CSV; served at /p/<slug> on every domain under a real CSP; lead event on the postback rails

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-09-29 16:06:11 -05:00
parent 8e1ddb892f
commit 53f5d51821
9 changed files with 459 additions and 3 deletions
+65
View File
@@ -0,0 +1,65 @@
// Parse-or-refuse for pasted autoresponder forms (ported from Branded Voice lib/formrestyle.ts, 2026-09-29).
// Keeps the MECHANICS (action, method, hidden fields, visible text/email fields), replaces the SKIN, escapes
// everything. Anything that cannot be rebuilt faithfully is REFUSED with a reason; member markup is never
// injected into a page as-is.
'use strict';
const EMBED_MAX_CHARS = 20000;
const escAttr = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
function attr(tag, name) {
const m = tag.match(new RegExp('\\b' + name + '\\s*=\\s*"([^"]*)"', 'i')) || tag.match(new RegExp('\\b' + name + "\\s*=\\s*'([^']*)'", 'i')) || tag.match(new RegExp('\\b' + name + '\\s*=\\s*([^\\s"\'>]+)', 'i'));
return m ? m[1] : null;
}
const hasFlag = (tag, name) => new RegExp('\\b' + name + '\\b', 'i').test(tag);
function derivePlaceholder(type, name) { const n = name.toLowerCase(); if (type === 'email' || n.includes('email')) return 'Your best email address'; if (n.includes('first')) return 'Your first name'; if (n.includes('last')) return 'Your last name'; if (n.includes('name')) return 'Your name'; return 'Your answer'; }
function problem(embed) {
const src = String(embed || '').trim();
if (!src) return null;
if (src.length > EMBED_MAX_CHARS) return 'Form code is too long. Paste only the <form> block your provider gives you.';
if (/<script|<iframe|<embed|<object/i.test(src)) return 'Form code contains a script, iframe or embed tag. Paste your provider\'s plain HTML form (the version without JavaScript).';
if (/recaptcha|g-recaptcha|h-captcha|hcaptcha|cf-turnstile/i.test(src)) return 'Form code includes a captcha, which cannot run on a published page. Turn the captcha off in your provider\'s form settings.';
const forms = src.match(/<form\b[\s\S]*?<\/form>/gi);
if (!forms || !forms.length) return 'No <form> tag was found in the form code.';
if (forms.length > 1) return 'Form code contains more than one form. Paste just the opt-in form.';
const formTag = forms[0].match(/<form\b[^>]*>/i)[0];
const action = attr(formTag, 'action');
if (!action || !/^https?:\/\//i.test(action)) return 'The form has no https:// action URL to submit to.';
if (/<select\b|<textarea\b/i.test(forms[0])) return 'The form uses a drop-down or text area, which cannot be restyled. Use a form with text and email fields only.';
const inputs = forms[0].match(/<input\b[^>]*>/gi) || [];
let visible = 0;
for (const tag of inputs) {
const type = (attr(tag, 'type') || 'text').toLowerCase();
if (type === 'hidden' || type === 'submit' || type === 'button' || type === 'image') continue;
if (type === 'text' || type === 'email') { if (!attr(tag, 'name')) return 'A visible field in the form has no name, so submissions would not reach your list.'; visible++; continue; }
return 'The form uses a "' + type + '" field, which cannot be restyled. Use a form with text and email fields only.';
}
if (!visible) return 'The form has no email or text field for the visitor to fill in.';
if (visible > 4) return 'The form has more than four visible fields. Opt-in forms with up to four fields are supported.';
return null;
}
// returns { action, method, charset, target, hidden:[{name,value}], fields:[{type,name,placeholder,required,value}], buttonText } or null
function parse(embed) {
if (problem(embed)) return null;
const src = String(embed).trim();
const formHtml = src.match(/<form\b[\s\S]*?<\/form>/gi)[0];
const formTag = formHtml.match(/<form\b[^>]*>/i)[0];
const action = attr(formTag, 'action');
const method = (attr(formTag, 'method') || 'post').toLowerCase() === 'get' ? 'get' : 'post';
const charset = attr(formTag, 'accept-charset'); const target = attr(formTag, 'target');
const hidden = [], fields = []; let buttonText = null;
for (const tag of formHtml.match(/<input\b[^>]*>/gi) || []) {
const type = (attr(tag, 'type') || 'text').toLowerCase(); const name = attr(tag, 'name') || '';
if (type === 'hidden') { if (name) hidden.push({ name, value: attr(tag, 'value') || '' }); continue; }
if (type === 'submit' || type === 'button' || type === 'image') { const v = attr(tag, 'value'); if (v && type === 'submit') buttonText = v; continue; }
fields.push({ type, name, placeholder: attr(tag, 'placeholder') || derivePlaceholder(type, name), required: hasFlag(tag, 'required'), value: attr(tag, 'value') || '' });
}
const btn = formHtml.match(/<button\b[^>]*>([\s\S]*?)<\/button>/i); if (btn && !buttonText) buttonText = btn[1].replace(/<[^>]+>/g, '').trim() || null;
return { action, method, charset, target, hidden, fields, buttonText };
}
function html(parsed, defaultButton) {
const open = '<form class="lsform" action="' + escAttr(parsed.action) + '" method="' + parsed.method + '"' + (parsed.charset ? ' accept-charset="' + escAttr(parsed.charset) + '"' : '') + (parsed.target ? ' target="' + escAttr(parsed.target) + '"' : '') + '>';
const hidden = parsed.hidden.map(h => '<input type="hidden" name="' + escAttr(h.name) + '" value="' + escAttr(h.value) + '">').join('\n');
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 };
+55
View File
@@ -0,0 +1,55 @@
// LinkSpin page renderer (2026-09-29): bridge, review and squeeze pages as standalone HTML. Everything the member
// typed is escaped; the only form on a page is either our own capture form or a provider form rebuilt by
// formrestyle (parse-or-refuse). No inline script: tracking lives in /assets/pt.js so the page can carry a real CSP.
'use strict';
const formrestyle = require('./formrestyle');
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const href = u => { const s = String(u || '').trim(); return /^https?:\/\/[^\s"'<>]+$/i.test(s) && s.length <= 700 ? s : ''; };
const PALETTES = {
graphite: { bg: '#0F1422', panel: '#161D31', ink: '#EEF2F8', muted: '#A7B4CB', line: '#27314A', accent: '#3B9DFF', accentInk: '#061225', font: "'Segoe UI',system-ui,-apple-system,Roboto,sans-serif", display: "Georgia,'Times New Roman',serif" },
ink: { bg: '#F6F4EE', panel: '#FFFFFF', ink: '#17191C', muted: '#5F6670', line: '#D9D4C7', accent: '#B8410E', accentInk: '#FFFFFF', font: "'Segoe UI',system-ui,-apple-system,Roboto,sans-serif", display: "Georgia,'Times New Roman',serif" },
ember: { bg: '#1A1210', panel: '#241A16', ink: '#F7EFE9', muted: '#C9B8AE', line: '#3A2B25', accent: '#FF8A3D', accentInk: '#1A0E08', font: "'Segoe UI',system-ui,-apple-system,Roboto,sans-serif", display: "Georgia,'Times New Roman',serif" },
};
const PALETTE_NAMES = Object.keys(PALETTES);
function css(P) {
return '*{box-sizing:border-box}body{margin:0;background:' + P.bg + ';color:' + P.ink + ';font-family:' + P.font + ';font-size:17px;line-height:1.55}a{color:' + P.accent + '}'
+ '.wrap{max-width:720px;margin:0 auto;padding:28px 18px 60px}.panel{background:' + P.panel + ';border:1px solid ' + P.line + ';border-radius:12px;padding:22px}'
+ 'h1{font-family:' + P.display + ';font-size:clamp(30px,5.6vw,44px);line-height:1.08;margin:0 0 12px;text-wrap:balance}h2{font-family:' + P.display + ';font-size:24px;margin:26px 0 8px}h3{font-size:18px;margin:18px 0 6px}'
+ '.sub{font-size:19px;color:' + P.muted + ';margin:0 0 18px}.eyebrow{font-size:12px;letter-spacing:.14em;text-transform:uppercase;font-weight:700;color:' + P.accent + ';margin-bottom:10px}'
+ 'ul.checks{list-style:none;padding:0;margin:14px 0;display:grid;gap:8px}ul.checks li{padding-left:28px;position:relative}ul.checks li::before{content:"";position:absolute;left:0;top:8px;width:16px;height:16px;border-radius:50%;background:' + P.accent + '}ul.checks li::after{content:"";position:absolute;left:5px;top:11px;width:6px;height:9px;border:solid ' + P.accentInk + ';border-width:0 2px 2px 0;transform:rotate(45deg)}'
+ '.cta{display:inline-block;background:' + P.accent + ';color:' + P.accentInk + ';font-weight:800;font-size:18px;text-decoration:none;padding:15px 26px;border-radius:10px;border:0;cursor:pointer;font-family:inherit}.cta:hover{filter:brightness(1.08)}.ctawrap{margin:18px 0;text-align:center}'
+ '.lsform{display:grid;gap:10px}.lsin{width:100%;padding:14px 16px;font:16px/1.4 inherit;border:1.5px solid ' + P.line + ';border-radius:10px;background:' + P.bg + ';color:' + P.ink + '}.lsin:focus{border-color:' + P.accent + ';outline:none}'
+ '.privacy{font-size:12.5px;color:' + P.muted + ';margin:10px 0 0;text-align:center}.hero img{width:100%;height:auto;border-radius:12px;margin:0 0 18px}'
+ '.pc{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.pc div{background:' + P.bg + ';border:1px solid ' + P.line + ';border-radius:10px;padding:14px}.pc h3{margin:0 0 8px}.pc ul{margin:0;padding-left:18px}@media(max-width:560px){.pc{grid-template-columns:1fr}}'
+ '.rating{font-size:22px;letter-spacing:2px;color:' + P.accent + '}.verdict{border-left:4px solid ' + P.accent + ';padding:10px 14px;margin:16px 0;background:' + P.bg + ';border-radius:0 10px 10px 0}'
+ '.foot{margin-top:34px;font-size:12.5px;color:' + P.muted + ';text-align:center}.foot a{color:' + P.muted + '}p{margin:0 0 14px}';
}
const paras = t => String(t || '').split(/\n\s*\n/).map(x => x.trim()).filter(Boolean).map(x => '<p>' + esc(x).replace(/\n/g, '<br>') + '</p>').join('');
const bullets = arr => (arr || []).filter(Boolean).length ? '<ul class="checks">' + arr.filter(Boolean).map(b => '<li>' + esc(b) + '</li>').join('') + '</ul>' : '';
function stars(n) { const k = Math.max(0, Math.min(5, Math.round(Number(n) || 0))); return '<div class="rating" aria-label="' + k + ' out of 5">' + '★'.repeat(k) + '☆'.repeat(5 - k) + '</div>'; }
function ctaBtn(c, cls) { const u = href(c && c.url); const t = esc(c && c.text || 'Continue'); return u ? '<div class="ctawrap"><a class="cta ' + (cls || '') + '" href="' + esc(u) + '" data-cta>' + t + '</a></div>' : ''; }
function formArea(page, opts) {
const c = page.content || {};
if (c.formEmbed) { const parsed = formrestyle.parse(c.formEmbed); if (parsed) return '<div class="formarea">' + formrestyle.html(parsed, c.cta && c.cta.text || 'Send me the details') + '</div>'; }
// our own capture: the lead lands on the member's LinkSpin list, then the visitor continues to the CTA URL
return '<div class="formarea"><form class="lsform" method="post" action="' + esc(opts.leadUrl) + '"><input class="lsin" type="text" name="name" placeholder="Your first name"><input class="lsin" type="email" name="email" placeholder="Your best email address" required><input type="text" name="website" tabindex="-1" autocomplete="off" style="position:absolute;left:-9999px" aria-hidden="true"><input type="hidden" name="lsid" value=""><button type="submit" class="cta">' + esc(c.cta && c.cta.text || 'Send me the details') + '</button></form></div>';
}
function render(page, opts) {
opts = opts || {}; const P = PALETTES[page.design && page.design.palette] || PALETTES.graphite; const c = page.content || {};
const head = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + esc(c.headline || page.title || 'Page') + '</title>'
+ '<meta name="description" content="' + esc((c.sub || '').slice(0, 160)) + '">' + (page.status !== 'published' ? '<meta name="robots" content="noindex,nofollow">' : '') + (c.image ? '<meta property="og:image" content="' + esc(href(c.image)) + '">' : '') + '<meta property="og:title" content="' + esc(c.headline || '') + '"><style>' + css(P) + '</style></head><body>';
let body = '';
const hero = c.image && href(c.image) ? '<div class="hero"><img src="' + esc(href(c.image)) + '" alt="' + esc(c.imageAlt || '') + '"></div>' : '';
if (page.type === 'squeeze') {
body = '<div class="wrap"><div class="panel">' + (c.eyebrow ? '<div class="eyebrow">' + esc(c.eyebrow) + '</div>' : '') + '<h1>' + esc(c.headline || '') + '</h1>' + (c.sub ? '<p class="sub">' + esc(c.sub) + '</p>' : '') + hero + bullets(c.bullets) + formArea(page, opts) + '<p class="privacy">' + esc(c.privacy || 'No spam, ever. Unsubscribe with one click.') + '</p></div>';
} else if (page.type === 'review') {
body = '<div class="wrap">' + (c.eyebrow ? '<div class="eyebrow">' + esc(c.eyebrow) + '</div>' : '<div class="eyebrow">Review</div>') + '<h1>' + esc(c.headline || '') + '</h1>' + (c.rating ? stars(c.rating) : '') + (c.sub ? '<p class="sub">' + esc(c.sub) + '</p>' : '') + hero + paras(c.body)
+ ((c.pros && c.pros.length) || (c.cons && c.cons.length) ? '<div class="pc"><div><h3>What works</h3><ul>' + (c.pros || []).filter(Boolean).map(x => '<li>' + esc(x) + '</li>').join('') + '</ul></div><div><h3>What to know</h3><ul>' + (c.cons || []).filter(Boolean).map(x => '<li>' + esc(x) + '</li>').join('') + '</ul></div></div>' : '')
+ (c.verdict ? '<div class="verdict"><b>Verdict.</b> ' + esc(c.verdict) + '</div>' : '') + ctaBtn(c.cta) + '</div>';
} else { // bridge
body = '<div class="wrap">' + (c.eyebrow ? '<div class="eyebrow">' + esc(c.eyebrow) + '</div>' : '') + '<h1>' + esc(c.headline || '') + '</h1>' + (c.sub ? '<p class="sub">' + esc(c.sub) + '</p>' : '') + hero + paras(c.body) + bullets(c.bullets) + ctaBtn(c.cta) + (c.bonus ? '<div class="panel"><h2 style="margin-top:0">' + esc(c.bonusTitle || 'Bonus when you join through this page') + '</h2>' + paras(c.bonus) + '</div>' : '') + ctaBtn(c.cta) + '</div>';
}
const foot = '<div class="foot">' + esc(c.disclaimer || 'Results depend on effort. Nothing here is a promise of income.') + (opts.footerLink ? ' · <a href="' + esc(opts.footerLink) + '">' + esc(opts.footerText || 'Made with LinkSpin') + '</a>' : '') + '</div>';
return head + body + foot + '<script src="' + esc(opts.trackSrc || '/assets/pt.js') + '" data-page="' + esc(page.slug) + '" defer></script></body></html>';
}
module.exports = { render, PALETTE_NAMES };
+145
View File
@@ -0,0 +1,145 @@
// 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 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 : ''; };
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);
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;
}
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: { palette: render.PALETTE_NAMES.includes(body.palette) ? body.palette : 'graphite' }, 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 && render.PALETTE_NAMES.includes(body.palette)) p.design.palette = body.palette;
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(url); if (!url) return { error: 'Give the scanner a full https:// address.' };
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
function templateCopy(type, scanRes, angle, cta) {
const s = Object.assign({ bullets: [], headings: [] }, scanRes || {}); const name = s.title || s.h1 || 'this page'; const a = String(angle || '').trim();
const base = { eyebrow: type === 'review' ? 'An honest look' : 'Before you click through', headline: a || (type === 'squeeze' ? 'Get the details on ' + name : name), 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({ title: s.title, 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 };
+1 -1
View File
@@ -17,7 +17,7 @@ const J = { db: null, FILE: () => path.join(DATA_DIR, 'postbacks.json'),
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } };
function init(opts) { DATA_DIR = opts.dataDir; ownHosts = opts.ownHosts || (() => []); rotator = opts.rotator; J.load(); }
const norm = e => String(e || '').trim().toLowerCase();
const EVENTS = ['join', 'wallet', 'purchase', 'external'];
const EVENTS = ['join', 'lead', 'wallet', 'purchase', 'external'];
const MACRO = /\{([a-z0-9_]{1,24})\}/gi;
function isPrivateIp(ip) {
+1 -1
View File
@@ -16,7 +16,7 @@ window.CR = (function () {
];
// screens not built yet fall back to the classic dashboard pane so nothing is a dead end
const FALLBACK = { pages: '/my#promo', zones: '/my#campaigns', team: '/my#line', wallet: '/my#wallet' };
const BUILT = new Set(['links', 'reports', 'team', 'wallet']);
const BUILT = new Set(['links', 'pages', 'reports', 'team', 'wallet']);
let ME = null, toastT;
function toast(msg, bad) { let t = $('crToast'); if (!t) { t = document.createElement('div'); t.id = 'crToast'; t.className = 'toast'; t.setAttribute('role', 'status'); document.body.appendChild(t); } t.textContent = msg; t.style.background = bad ? '#FF7A7A' : ''; t.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('on'), 2000); }
async function api(path, body) { const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) throw new Error(r.error); return r; }
+61
View File
@@ -0,0 +1,61 @@
// LinkSpin Pages screen: gallery + wizard (scan -> type -> angle -> write) + editor + leads.
(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 = [];
const PAL = { graphite: '#3B9DFF', ink: '#B8410E', ember: '#FF8A3D' };
CR.mount({ active: 'pages', title: 'Pages', sub: 'loading', actions: '<button class="btn pri" type="button" id="newBtn">+ New page</button>' });
const pageUrl = p => '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 || [];
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);
$('tiles').innerHTML = [['Pages', fmt(PAGES.length)], ['Live', fmt(pubd)], ['Views', fmt(views)], ['Clicks through', fmt(clicks)], ['Leads on your list', fmt(leads)]].map(([k, v], i) => '<div class="tile' + (i === 4 ? ' hi' : '') + '"><span class="k">' + k + '</span><span class="v">' + v + '</span></div>').join('');
$('gal').innerHTML = PAGES.length ? PAGES.map(p => '<div class="card' + (p.id === SEL ? ' on' : '') + '" data-id="' + p.id + '" role="button" tabindex="0"><div class="thumb"><i class="t"></i><i style="width:55%"></i><i style="width:65%"></i><i class="b"></i></div><div class="cap"><b>' + esc(p.title) + '</b><span class="mono muted" style="font-size:11px">' + p.type + ' · ' + (p.status === 'published' ? '<span class="ok">live</span>' : 'draft') + ' · ' + fmt(p.views) + ' views' + (p.leads ? ' · ' + fmt(p.leads) + ' leads' : '') + '</span></div></div>').join('')
: '<div class="muted">No pages yet. Scan the page you promote and write your first bridge page in a minute.</div>';
$('gal').querySelectorAll('.card').forEach(c => { const go = () => openEditor(c.dataset.id); c.addEventListener('click', go); c.addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); });
try { const L = await CR.get('/api/my/pages/leads'); const rows = L.leads || []; $('leadsBox').hidden = !rows.length; $('leadRows').innerHTML = rows.slice(0, 50).map(l => '<div class="rw"><span><b>' + esc(l.email) + '</b>' + (l.name ? ' <span class="muted">' + esc(l.name) + '</span>' : '') + '</span><span class="muted">' + esc(l.page) + '</span><span class="mono muted" style="font-size:11px">' + new Date(l.ts).toLocaleString() + '</span></div>').join(''); $('leadFoot').textContent = rows.length + ' lead' + (rows.length === 1 ? '' : 's') + ' on your list · yours to export'; } catch (e) {}
if (keepSel && SEL) openEditor(SEL, true);
}
// wizard
$('types').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { TYPE = b.dataset.t; $('types').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }));
$('scanBtn').addEventListener('click', async () => { const url = $('scanUrl').value.trim(); if (!url) return $('scanUrl').focus(); $('scanBtn').disabled = true; $('scanOut').hidden = false; $('scanOut').innerHTML = '<span class="muted">Scanning…</span>'; try { const r = await api('/api/my/pages/scan', { url }); SCAN = r.scan; $('scanOut').innerHTML = '<span class="mono ok" style="font-size:11px">SCANNED · HTTP ' + SCAN.status + '</span><div><b>' + esc(SCAN.title || SCAN.h1 || '(no title)') + '</b></div><div class="muted">' + esc((SCAN.description || '').slice(0, 160)) + '</div>' + (SCAN.image ? '<div class="muted mono" style="font-size:11px">image found</div>' : '') + (SCAN.bullets.length ? '<div class="muted mono" style="font-size:11px">' + SCAN.bullets.length + ' points found</div>' : ''); } catch (e) { SCAN = null; $('scanOut').innerHTML = '<span class="bad">' + esc(e.message) + '</span>'; } $('scanBtn').disabled = false; });
async function createPage(writeIt) {
const url = $('scanUrl').value.trim(); const angle = $('angle').value.trim();
if (!SCAN && url && writeIt) { $('scanBtn').click(); await new Promise(r => setTimeout(r, 2500)); }
try {
const r = await api('/api/my/pages', { type: TYPE, title: (SCAN && (SCAN.title || SCAN.h1)) || angle || 'New ' + TYPE + ' page', angle, scan: SCAN || (url ? { url } : null), content: { cta: { url: url, text: TYPE === 'squeeze' ? 'Send me the details' : 'Take a look' }, headline: angle || '' } });
SEL = r.page.id;
if (writeIt) { toast('Writing…'); await api('/api/my/pages/' + SEL + '/write', { angle, cta: url }); }
await load(); openEditor(SEL);
} catch (e) { toast(e.message, true); }
}
$('writeBtn').addEventListener('click', () => createPage(true)); $('blankBtn').addEventListener('click', () => createPage(false));
$('newBtn').addEventListener('click', () => { $('editor').hidden = true; $('wizard').hidden = false; $('scanUrl').focus(); });
// editor
const F = { bridge: [['eyebrow', 'Eyebrow'], ['headline', 'Headline'], ['sub', 'Subhead'], ['body', 'Body, blank line between paragraphs', 'ta'], ['bullets', 'Bullets, one per line', 'ta'], ['bonusTitle', 'Bonus title'], ['bonus', 'Bonus text', 'ta'], ['ctaText', 'Button text'], ['ctaUrl', 'Button link'], ['image', 'Hero image URL'], ['disclaimer', 'Footer line']],
review: [['eyebrow', 'Eyebrow'], ['headline', 'Headline'], ['rating', 'Rating 1 to 5'], ['sub', 'Subhead'], ['body', 'Review body, blank line between paragraphs', 'ta'], ['pros', 'What works, one per line', 'ta'], ['cons', 'What to know, one per line', 'ta'], ['verdict', 'Verdict'], ['ctaText', 'Button text'], ['ctaUrl', 'Button link'], ['image', 'Hero image URL'], ['disclaimer', 'Footer line']],
squeeze: [['eyebrow', 'Eyebrow'], ['headline', 'Headline'], ['sub', 'Subhead'], ['bullets', 'What they get, one per line', 'ta'], ['ctaText', 'Button text'], ['ctaUrl', 'Where they go after the form'], ['image', 'Image URL'], ['privacy', 'Privacy line'], ['formEmbed', 'Your autoresponder form (optional, plain HTML form only, no JavaScript). Leave empty to capture leads on your LinkSpin list.', 'ta'], ['disclaimer', 'Footer line']] };
function openEditor(id, quiet) {
const p = PAGES.find(x => x.id === id); if (!p) return; SEL = id;
$('gal').querySelectorAll('.card').forEach(c => c.classList.toggle('on', c.dataset.id === id));
$('wizard').hidden = true; $('editor').hidden = false;
$('edTitle').textContent = p.title; $('edStatus').innerHTML = p.status === 'published' ? '<span class="ok"><span class="dot"></span>LIVE</span>' : '<span class="warn"><span class="dot"></span>DRAFT</span>';
$('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('');
$('pal').innerHTML = Object.entries(PAL).map(([k, col]) => '<button type="button" title="' + k + '" data-p="' + k + '" class="' + ((p.design && p.design.palette) === k ? 'on' : '') + '" style="background:' + col + '"></button>').join('');
$('pal').querySelectorAll('button').forEach(b => b.addEventListener('click', async () => { try { await api('/api/my/pages/' + p.id, { palette: b.dataset.p }); load(true); } catch (e) { toast(e.message, true); } }));
if (!quiet && window.matchMedia('(max-width:900px)').matches) $('side').scrollIntoView({ behavior: 'smooth' });
}
function collect(p) { const g = k => { const el = $('f-' + k); return el ? el.value : undefined; }; const c = {}; for (const [k] of F[p.type]) { if (k === 'ctaText' || k === 'ctaUrl') continue; c[k] = g(k); } c.cta = { text: g('ctaText'), url: g('ctaUrl') }; for (const k of ['bullets', 'pros', 'cons']) if (c[k] != null) c[k] = c[k].split('\n'); return c; }
$('edSave').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; try { await api('/api/my/pages/' + p.id, { content: collect(p), title: ($('f-headline').value || p.title).slice(0, 100) }); toast('Saved'); load(true); } catch (e) { toast(e.message, true); } });
$('edPublish').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; try { await api('/api/my/pages/' + p.id, { content: collect(p) }); const r = await api('/api/my/pages/' + p.id, { status: p.status === 'published' ? 'draft' : 'published' }); toast(r.page.status === 'published' ? 'Live at ' + pageUrl(r.page) : 'Unpublished'); load(true); } catch (e) { toast(e.message, true); } });
$('edRewrite').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; const v = await dialog({ title: 'Write again', text: 'A fresh draft from the scan and your angle. Your current text is replaced.', fields: [{ k: 'angle', label: 'Angle', value: p.angle || '' }], ok: 'Write' }); if (!v) return; try { toast('Writing…'); await api('/api/my/pages/' + p.id + '/write', { angle: v.angle }); load(true); } catch (e) { toast(e.message, true); } });
$('edDelete').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; if (!await dialog({ title: 'Delete ' + p.title + '?', text: 'The page stops answering. Leads already on your list stay.', ok: 'Delete', danger: true })) return; try { await api('/api/my/pages/' + p.id, { remove: true }); SEL = null; $('editor').hidden = true; $('wizard').hidden = false; load(); } catch (e) { toast(e.message, true); } });
$('edClose').addEventListener('click', () => { $('editor').hidden = true; $('wizard').hidden = false; });
$('edSpin').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; if (p.status !== 'published') return toast('Publish the page first.', true); try { const r = await CR.get('/api/my/rotations'); const rots = r.rotations || []; if (!rots.length) { const c = await api('/api/my/rotations', { name: p.title }); await api('/api/my/rotations/' + c.rotation.id + '/dest', { url: pageUrl(p), label: p.title, weight: 10 }); toast('New spin made with this page'); location.href = '/links#' + c.rotation.id; return; } const v = await dialog({ title: 'Which spin?', html: '<label class="lbl">Spin<select class="field" id="dlg-rot">' + rots.map(x => '<option value="' + x.id + '">' + esc(x.name) + '</option>').join('') + '</select></label>', ok: 'Add page' }); if (!v) return; const id = document.getElementById('dlg-rot') ? document.getElementById('dlg-rot').value : rots[0].id; await api('/api/my/rotations/' + id + '/dest', { url: pageUrl(p), label: p.title, weight: 10 }); toast('Added to the spin'); location.href = '/links#' + id; } catch (e) { toast(e.message, true); } });
CR.requireSession(() => load());
})();
+14
View File
@@ -0,0 +1,14 @@
// LinkSpin page tracking (external so pages carry a real CSP). (1) click-id passthrough: params on the page URL
// (clickid, subids, utm, lsid) ride onto every CTA link; (2) our own capture form gets the lsid; (3) a view /
// click beacon per page (no cookies, no personal data).
(function () {
var s = document.currentScript, slug = s && s.getAttribute('data-page'); if (!slug) return;
var P = {}, n = 0;
try { new URLSearchParams(location.search).forEach(function (v, k) { if (n < 20 && /^[a-zA-Z0-9_-]{1,32}$/.test(k)) { P[k] = String(v).slice(0, 200); n++; } }); } catch (e) {}
var lsid = /^[a-z0-9]{6,20}$/i.test(P.lsid || '') ? P.lsid : '';
document.querySelectorAll('a[data-cta]').forEach(function (a) {
try { var u = new URL(a.href); for (var k in P) if (!u.searchParams.has(k)) u.searchParams.set(k, P[k]); a.href = u.toString(); } catch (e) {}
a.addEventListener('click', function () { try { navigator.sendBeacon('/api/p/' + slug + '/hit', new Blob([JSON.stringify({ k: 'cta' })], { type: 'application/json' })); } catch (e) {} });
});
var f = document.querySelector('.lsform input[name="lsid"]'); if (f && lsid) f.value = lsid;
})();
+61
View File
@@ -0,0 +1,61 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="robots" content="noindex, nofollow">
<title>Pages · LinkSpin</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700&family=JetBrains+Mono:wght@500;700&display=swap">
<link rel="stylesheet" href="/assets/cr.css?v=20260929b">
<style>
.ws{display:grid;grid-template-columns:minmax(0,1fr) 440px;min-height:calc(100vh - 53px)}
.body{padding:16px 24px;display:grid;gap:14px;align-content:start}
.gal{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);overflow:hidden;cursor:pointer;display:grid}
.card.on{border-color:var(--accent)}
.thumb{height:96px;background:var(--panel-2);padding:12px;display:grid;gap:6px;align-content:start} .thumb i{display:block;background:var(--line);height:6px;border-radius:2px} .thumb i.t{background:var(--accent-dim);height:10px;width:70%} .thumb i.b{background:var(--accent);height:14px;width:40%;margin-top:auto}
.card .cap{padding:10px 12px;display:grid;gap:3px} .card .cap b{font-size:13px}
.side{border-left:1px solid var(--line);padding:16px;display:grid;gap:12px;align-content:start;background:var(--rail)}
.side h2{font-family:var(--display);font-size:18px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;margin:0}
.types{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px} .types button{background:transparent;border:1px solid var(--line);border-radius:var(--r);color:var(--ink);padding:8px 6px;cursor:pointer;display:grid;gap:2px;text-align:left} .types button.on{border-color:var(--accent)} .types small{color:var(--muted);font-size:11px}
.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}
@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>
<body>
<div id="page">
<div class="ws">
<div class="body">
<div class="tiles" id="tiles"></div>
<div class="sec">Your pages · click one to edit</div>
<div class="gal" id="gal"></div>
<div class="tbl leads" id="leadsBox" hidden><div class="hd"><span>Lead</span><span>Page</span><span>When</span></div><div id="leadRows"></div><div class="ft" style="display:flex;justify-content:space-between;align-items:center"><span id="leadFoot"></span><a class="btn sm" id="leadCsv" href="/api/my/pages/leads.csv">Download CSV</a></div></div>
</div>
<div class="side" id="side">
<div id="wizard">
<h2>New page</h2>
<label class="lbl">Paste the page you are sending people to<input class="field mono" id="scanUrl" type="url" placeholder="https://"></label>
<button class="btn pri" type="button" id="scanBtn">Scan it</button>
<div id="scanOut" class="panel" hidden></div>
<div class="sec">Page type</div>
<div class="types" id="types"><button type="button" class="on" data-t="bridge"><b>Bridge</b><small>Your story, then the link</small></button><button type="button" data-t="review"><b>Review</b><small>Pros, cons, verdict</small></button><button type="button" data-t="squeeze"><b>Squeeze</b><small>Email first, then the link</small></button></div>
<label class="lbl">Angle, one line<input class="field" id="angle" type="text" maxlength="160" placeholder="I got paid before I finished my coffee"></label>
<div style="display:flex;gap:8px"><button class="btn pri" type="button" id="writeBtn">Write it</button><button class="btn" type="button" id="blankBtn">Start blank</button></div>
<div class="muted">A published page carries tracking and goes straight into any spin. Forms: our own capture (leads stay on your list) or your provider's plain HTML form, checked before it is used.</div>
</div>
<div id="editor" hidden>
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap"><h2 id="edTitle">Page</h2><span class="grow"></span><button class="btn sm" type="button" id="edClose">Close</button></div>
<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center"><span id="edStatus"></span><a class="btn sm" id="edPreview" href="#" target="_blank" rel="noopener">Preview</a><button class="btn sm pri" type="button" id="edPublish">Publish</button><button class="btn sm" type="button" id="edSpin">Put it in a spin</button><button class="btn sm danger" type="button" id="edDelete">Delete</button></div>
<div class="code" id="edUrl" hidden></div>
<div class="ed" id="edFields"></div>
<div style="display:flex;gap:8px;align-items:center"><span class="sec">Look</span><div class="pal" id="pal"></div><span class="grow"></span><button class="btn sm" type="button" id="edRewrite">Write again</button><button class="btn pri" type="button" id="edSave">Save</button></div>
</div>
</div>
</div>
</div>
<script src="/assets/cr-shell.js?v=20260929a"></script>
<script src="/assets/pages-screen.js?v=20260929a"></script>
</body>
</html>
+56 -1
View File
@@ -39,7 +39,8 @@ const toolkit = require('./toolkit');
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
const carry = require('./carry'); // sponsor carry-over: engine activation, claim window, notices
const rotator = require('./rotator');
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29) // the rotator: rotations, weighted destinations, /r/<code>
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) // the rotator: rotations, weighted destinations, /r/<code>
const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15)
const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15)
const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12)
@@ -389,6 +390,7 @@ async function boot() {
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean));
rotator.init({ dataDir: DATA_DIR, geo, ownHosts });
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator });
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 ''; } } });
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: 'https://linkspin-test.saasy.top' });
@@ -873,6 +875,31 @@ const server = http.createServer(async (req, res) => {
if (hit && hit.url) { res.writeHead(302, { Location: hit.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); }
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone'));
}
// -- member pages: /p/<slug> on the app host and on every link domain; the lead form and the hit beacon live beside it
let pm = /^\/p\/([a-z0-9-]{3,60})$/i.exec(p);
if (pm && (req.method === 'GET' || req.method === 'HEAD')) {
const pg = pages.bySlug(pm[1]);
const preview = u.searchParams.get('preview') === '1';
if (!pg || (pg.status !== 'published' && !preview)) { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(isLinkHost(req) ? linkSitePage(reqHost(req), 'gone') : '<!doctype html><title>Not found</title><p style="font-family:system-ui;padding:40px">That page is not live.</p>'); }
if (preview) { const sess = await auth.fromRequest(req); if (!sess || !sess.email || String(sess.email).toLowerCase() !== pg.owner) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } }
else pages.view(pg, req, 'view');
const lsid = String(u.searchParams.get('lsid') || '');
const hdr = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin',
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src https: data:; form-action https: http:; base-uri 'none'; frame-ancestors *; connect-src 'self'" };
if (/^[a-z0-9]{6,20}$/i.test(lsid)) hdr['Set-Cookie'] = 'ls.click=' + lsid + '; Path=/; SameSite=Lax; Max-Age=2592000' + (IS_PROD ? '; Secure' : '');
res.writeHead(200, hdr); return res.end(pages.html(pg, { leadUrl: '/p/' + pg.slug + '/lead', trackSrc: '/assets/pt.js', footerLink: 'https://' + SITE_HOST + '/', footerText: 'Made with LinkSpin' }));
}
pm = /^\/p\/([a-z0-9-]{3,60})\/lead$/i.exec(p);
if (pm && req.method === 'POST') {
const raw = await new Promise(r => { let d = ''; req.on('data', c => { d += c; if (d.length > 20000) req.destroy(); }); req.on('end', () => r(d)); });
const b = {}; try { const ct = String(req.headers['content-type'] || ''); if (/json/.test(ct)) Object.assign(b, JSON.parse(raw)); else for (const [k, v] of new URLSearchParams(raw)) b[k] = v; } catch (e) {}
const r = await pages.lead(pm[1], b, req);
if (r.error) { res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('<!doctype html><title>Try again</title><p style="font-family:system-ui;padding:40px">' + r.error + ' <a href="javascript:history.back()">Go back</a></p>'); }
if (r.owner && r.lsid) { try { postbacks.bindClick(String(b.email || '').toLowerCase(), r.lsid); const hit = await rotator.convert(r.lsid, 'lead', {}); if (hit) postbacks.fire(hit.owner, 'lead', Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: r.lsid, code: hit.code })).catch(() => {}); } catch (e) {} }
res.writeHead(302, { Location: r.next || '/', 'Cache-Control': 'no-store' }); return res.end();
}
if (p.startsWith('/api/p/') && req.method === 'POST' && /\/hit$/.test(p)) { const sl = p.split('/')[3]; const pg = pages.bySlug(sl); if (pg) pages.view(pg, req, 'cta'); res.writeHead(204); return res.end(); }
if (p === '/assets/pt.js' && isLinkHost(req)) return sendFile(res, path.join(PUBLIC_DIR, 'assets', 'pt.js'));
// -- short link domains: a real small site (home, disclosure, terms, privacy, abuse) so the domain never looks parked
if (isLinkHost(req)) {
const page = { '/': 'home', '/disclosure': 'disclosure', '/terms': 'terms', '/privacy': 'privacy', '/abuse': 'abuse', '/robots.txt': 'robots' }[p];
@@ -1804,6 +1831,33 @@ const server = http.createServer(async (req, res) => {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await rotator.stats(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such rotation.' });
}
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.'));
return json(res, 200, { pages: await pages.list(s.email), hosts: hosts.length ? hosts : [SITE_HOST], types: pages.TYPES }, { 'Cache-Control': 'no-store' });
}
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.' });
const r = await pages.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/pages/scan' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req); const r = await pages.scan(b.url); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/pages/leads' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, { leads: await pages.leads(s.email, u.searchParams.get('page') || null) }, { 'Cache-Control': 'no-store' });
}
if (p === '/api/my/pages/leads.csv' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const rows = await pages.leads(s.email, u.searchParams.get('page') || null);
res.writeHead(200, { 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="linkspin-leads.csv"', 'Cache-Control': 'no-store' }); return res.end(pages.csv(rows));
}
m = /^\/api\/my\/pages\/([a-f0-9]{10})(\/write)?$/.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); const r = m[2] ? await pages.write(s.email, m[1], b) : await pages.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r);
}
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));
@@ -2841,6 +2895,7 @@ const server = http.createServer(async (req, res) => {
if (p === '/my') return sendFile(res, path.join(PUBLIC_DIR, 'my.html'));
if (p === '/links') return sendFile(res, path.join(PUBLIC_DIR, 'links.html')); // Control Room: the links workspace, first screen of the new front end (2026-09-29)
if (p === '/reports') return sendFile(res, path.join(PUBLIC_DIR, 'reports.html'));
if (p === '/pages') return sendFile(res, path.join(PUBLIC_DIR, 'pages.html'));
if (p === '/team') return sendFile(res, path.join(PUBLIC_DIR, 'team.html'));
if (p === '/wallet') return sendFile(res, path.join(PUBLIC_DIR, 'wallet.html'));
if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html'));