From 53f5d51821c4b9c5d694d8595be752bda468455c Mon Sep 17 00:00:00 2001 From: martbost Date: Tue, 29 Sep 2026 16:06:11 -0500 Subject: [PATCH] Pages: bridge, review and squeeze pages from a scan plus an angle; parse-or-refuse forms; member-owned leads with CSV; served at /p/ on every domain under a real CSP; lead event on the postback rails Co-Authored-By: Claude Fable 5.1 --- formrestyle.js | 65 +++++++++++++++ pagerender.js | 55 +++++++++++++ pages.js | 145 ++++++++++++++++++++++++++++++++++ postbacks.js | 2 +- public/assets/cr-shell.js | 2 +- public/assets/pages-screen.js | 61 ++++++++++++++ public/assets/pt.js | 14 ++++ public/pages.html | 61 ++++++++++++++ server.js | 57 ++++++++++++- 9 files changed, 459 insertions(+), 3 deletions(-) create mode 100644 formrestyle.js create mode 100644 pagerender.js create mode 100644 pages.js create mode 100644 public/assets/pages-screen.js create mode 100644 public/assets/pt.js create mode 100644 public/pages.html diff --git a/formrestyle.js b/formrestyle.js new file mode 100644 index 0000000..73f7711 --- /dev/null +++ b/formrestyle.js @@ -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, '&').replace(//g, '>').replace(/"/g, '"'); +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
block your provider gives you.'; + if (//gi); + if (!forms || !forms.length) return 'No 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(/]*>/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 (/]*>/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(//gi)[0]; + const formTag = formHtml.match(/]*>/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(/]*>/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(/]*>([\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 = ''; + const hidden = parsed.hidden.map(h => '').join('\n'); + const inputs = parsed.fields.map(f => '').join('\n'); + return [open, hidden, inputs, '', ''].join('\n'); +} +module.exports = { EMBED_MAX_CHARS, problem, parse, html }; diff --git a/pagerender.js b/pagerender.js new file mode 100644 index 0000000..90a4dc8 --- /dev/null +++ b/pagerender.js @@ -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 => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[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 => '

' + esc(x).replace(/\n/g, '
') + '

').join(''); +const bullets = arr => (arr || []).filter(Boolean).length ? '
    ' + arr.filter(Boolean).map(b => '
  • ' + esc(b) + '
  • ').join('') + '
' : ''; +function stars(n) { const k = Math.max(0, Math.min(5, Math.round(Number(n) || 0))); return '
' + '★'.repeat(k) + '☆'.repeat(5 - k) + '
'; } +function ctaBtn(c, cls) { const u = href(c && c.url); const t = esc(c && c.text || 'Continue'); return u ? '' : ''; } +function formArea(page, opts) { + const c = page.content || {}; + if (c.formEmbed) { const parsed = formrestyle.parse(c.formEmbed); if (parsed) return '
' + formrestyle.html(parsed, c.cta && c.cta.text || 'Send me the details') + '
'; } + // our own capture: the lead lands on the member's LinkSpin list, then the visitor continues to the CTA URL + return '
'; +} +function render(page, opts) { + opts = opts || {}; const P = PALETTES[page.design && page.design.palette] || PALETTES.graphite; const c = page.content || {}; + const head = '' + esc(c.headline || page.title || 'Page') + '' + + '' + (page.status !== 'published' ? '' : '') + (c.image ? '' : '') + ''; + let body = ''; + const hero = c.image && href(c.image) ? '
' + esc(c.imageAlt || '') + '
' : ''; + if (page.type === 'squeeze') { + body = '
' + (c.eyebrow ? '
' + esc(c.eyebrow) + '
' : '') + '

' + esc(c.headline || '') + '

' + (c.sub ? '

' + esc(c.sub) + '

' : '') + hero + bullets(c.bullets) + formArea(page, opts) + '

' + esc(c.privacy || 'No spam, ever. Unsubscribe with one click.') + '

'; + } else if (page.type === 'review') { + body = '
' + (c.eyebrow ? '
' + esc(c.eyebrow) + '
' : '
Review
') + '

' + esc(c.headline || '') + '

' + (c.rating ? stars(c.rating) : '') + (c.sub ? '

' + esc(c.sub) + '

' : '') + hero + paras(c.body) + + ((c.pros && c.pros.length) || (c.cons && c.cons.length) ? '

What works

    ' + (c.pros || []).filter(Boolean).map(x => '
  • ' + esc(x) + '
  • ').join('') + '

What to know

    ' + (c.cons || []).filter(Boolean).map(x => '
  • ' + esc(x) + '
  • ').join('') + '
' : '') + + (c.verdict ? '
Verdict. ' + esc(c.verdict) + '
' : '') + ctaBtn(c.cta) + '
'; + } else { // bridge + body = '
' + (c.eyebrow ? '
' + esc(c.eyebrow) + '
' : '') + '

' + esc(c.headline || '') + '

' + (c.sub ? '

' + esc(c.sub) + '

' : '') + hero + paras(c.body) + bullets(c.bullets) + ctaBtn(c.cta) + (c.bonus ? '

' + esc(c.bonusTitle || 'Bonus when you join through this page') + '

' + paras(c.bonus) + '
' : '') + ctaBtn(c.cta) + '
'; + } + const foot = '
' + esc(c.disclaimer || 'Results depend on effort. Nothing here is a promise of income.') + (opts.footerLink ? ' · ' + esc(opts.footerText || 'Made with LinkSpin') + '' : '') + '
'; + return head + body + foot + ''; +} +module.exports = { render, PALETTE_NAMES }; diff --git a/pages.js b/pages.js new file mode 100644 index 0000000..48a812c --- /dev/null +++ b/pages.js @@ -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/ 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(']+(?:property|name)=["\']' + name + '["\'][^>]*content=["\']([^"\']*)', 'i')) || h.match(new RegExp(']+content=["\']([^"\']*)["\'][^>]*(?:property|name)=["\']' + name + '["\']', 'i')); return m ? m[1].trim() : ''; }; +const strip = s => String(s || '').replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/&/g, '&').replace(/'|'/g, "'").replace(/"/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(/]*>([\s\S]*?)<\/title>/i) || [])[1] || ''); + const desc = strip(meta(h, 'og:description') || meta(h, 'description')); + const h1 = strip((h.match(/]*>([\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 = /]*>([\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 = /]*>([\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 }; diff --git a/postbacks.js b/postbacks.js index 7cb103c..4aeff1d 100644 --- a/postbacks.js +++ b/postbacks.js @@ -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) { diff --git a/public/assets/cr-shell.js b/public/assets/cr-shell.js index 18174df..60515d0 100644 --- a/public/assets/cr-shell.js +++ b/public/assets/cr-shell.js @@ -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; } diff --git a/public/assets/pages-screen.js b/public/assets/pages-screen.js new file mode 100644 index 0000000..d94fd4c --- /dev/null +++ b/public/assets/pages-screen.js @@ -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: '' }); + 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) => '
' + k + '' + v + '
').join(''); + $('gal').innerHTML = PAGES.length ? PAGES.map(p => '
' + esc(p.title) + '' + p.type + ' · ' + (p.status === 'published' ? 'live' : 'draft') + ' · ' + fmt(p.views) + ' views' + (p.leads ? ' · ' + fmt(p.leads) + ' leads' : '') + '
').join('') + : '
No pages yet. Scan the page you promote and write your first bridge page in a minute.
'; + $('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 => '
' + esc(l.email) + '' + (l.name ? ' ' + esc(l.name) + '' : '') + '' + esc(l.page) + '' + new Date(l.ts).toLocaleString() + '
').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 = 'Scanning…'; try { const r = await api('/api/my/pages/scan', { url }); SCAN = r.scan; $('scanOut').innerHTML = 'SCANNED · HTTP ' + SCAN.status + '
' + esc(SCAN.title || SCAN.h1 || '(no title)') + '
' + esc((SCAN.description || '').slice(0, 160)) + '
' + (SCAN.image ? '
image found
' : '') + (SCAN.bullets.length ? '
' + SCAN.bullets.length + ' points found
' : ''); } catch (e) { SCAN = null; $('scanOut').innerHTML = '' + esc(e.message) + ''; } $('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' ? 'LIVE' : 'DRAFT'; + $('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]) => '').join(''); + $('pal').innerHTML = Object.entries(PAL).map(([k, col]) => '').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: '', 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()); +})(); diff --git a/public/assets/pt.js b/public/assets/pt.js new file mode 100644 index 0000000..7f5a3dd --- /dev/null +++ b/public/assets/pt.js @@ -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; +})(); diff --git a/public/pages.html b/public/pages.html new file mode 100644 index 0000000..863f576 --- /dev/null +++ b/public/pages.html @@ -0,0 +1,61 @@ + + + + + + +Pages · LinkSpin + + + + + +
+
+
+
+
Your pages · click one to edit
+
+ +
+
+
+

New page

+ + + +
Page type
+
+ +
+
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.
+
+ +
+
+
+ + + + diff --git a/server.js b/server.js index 6d4668c..71f96cc 100644 --- a/server.js +++ b/server.js @@ -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/ +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) // the rotator: rotations, weighted destinations, /r/ 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/ 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') : 'Not found

That page is not live.

'); } + 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('Try again

' + r.error + ' Go back

'); } + 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'));