Files
yourprogrambuilder/server.js
T
martbost 0e508312c9 Dormant import honors dry (it wrote rows even with dry: true); e2e 125/125
Not deployed: ships with the go-live deploy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:06:15 -06:00

643 lines
59 KiB
JavaScript

// YourProgramBuilder web app, the Seed Bed (yourprogrambuilder.com rebuild, Marty 2026-11-17). Plain Node http server, no framework
// (the InstantAdPay / Downline Banners / VBB / ViralAdBlitz / ViralAdSource pattern).
// "Bring your program. The network grows it." A network member (network sign-in through the hub, membership checked with the hub)
// plants a program free; members save their referral ID in its packet; at REVIEW_SAVES saves it goes to Marty's review queue and,
// approved, is exported for the Crypto Team Build Network builder / DownlineHydra wild heads with every saved ID (seedbed.js).
// Paid part: a one-time Spotlight for a packet on YPBShop (shop.js, NOT deployed; staging has no contract).
// Pages: / (the Seed Bed), /p/<id> (a packet), /<username> (a member's packets, their links first), /my, /spotlight, /transplanted,
// /ledger, /contract, /promote, /guides/*, /terms, /disclaimer, /privacy, /admin.
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { verifyMessage, getAddress } = require('ethers');
const cfgMod = require('./config');
const C = cfgMod.get();
fs.mkdirSync(C.dataDir, { recursive: true });
const docstore = require('./docstore'); docstore.install(C.dataDir);
const store = require('./store');
const wire = require('./wire');
const seedbed = require('./seedbed');
const linkcheck = require('./linkcheck');
const networksso = require('./networksso');
const shop = require('./shop');
const promokit = require('./promokit');
const hubreport = require('./hubreport');
const hubpeople = require('./hubpeople');
const hubevents = require('./hubevents');
const hubline = require('./hubline');
const proof = require('./proof');
const netsites = require('./netsites');
const netdeals = require('./netdeals');
const lstrack = require('./lstrack');
const chatbot = require('./chatbot');
const adwriter = require('./hubadwriter');
const PUB = path.join(__dirname, 'public');
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/;
const PAGE_RE = /^\/([A-Za-z0-9_.-]{2,40})\/?$/;
const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|preview|monitor|wget|curl|python|httpclient|scrapy|semrush|ahrefs|headless|lighthouse|pingdom|go-http|java\/|okhttp|axios|node-fetch|phantom|selenium|puppeteer|playwright/i;
const SECRET = (() => {
if (process.env.SESSION_SECRET) return process.env.SESSION_SECRET;
const f = path.join(C.dataDir, '.secret');
try { return fs.readFileSync(f, 'utf8').trim(); } catch (e) {}
const s = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, s, { mode: 0o600 }); } catch (e) {} return s;
})();
const hash = s => crypto.createHmac('sha256', SECRET).update(s).digest('hex').slice(0, 24);
wire.setSecret(SECRET);
const TEST_SWITCH = C.staging && !/(^|\.)yourprogrambuilder\.com$/i.test(C.site); // never on the real domain
// ---- http helpers ----
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp',
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://linkspin.app https://polhunter.com; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
+ "img-src 'self' data: blob: https:; connect-src 'self' https://linkspin.app https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org "
+ "https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; "
+ "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: 'self'";
function headers(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); }
function json(res, code, obj, extra) { res.writeHead(code, headers(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); res.end(JSON.stringify(obj)); }
function sendFile(res, file, extra, code) {
fs.readFile(file, (err, data) => {
if (err) { res.writeHead(404, headers({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
const ext = path.extname(file).toLowerCase();
res.writeHead(code || 200, headers(Object.assign({ 'Content-Type': MIME[ext] || 'application/octet-stream', 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' }, extra)));
res.end(data);
});
}
function readRaw(req, max) {
return new Promise((resolve, reject) => { const ch = []; let n = 0;
req.on('data', c => { n += c.length; if (n > max * 8) { req.destroy(); return; } if (n <= max) ch.push(c); });
req.on('end', () => n > max ? reject(new Error('too big')) : resolve(Buffer.concat(ch))); req.on('error', reject); });
}
async function readBody(req) { const b = await readRaw(req, 32 * 1024); try { return b.length ? JSON.parse(b.toString('utf8')) : {}; } catch (e) { return {}; } }
function cookies(req) { const o = {}; for (const p of (req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { o[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } return o; }
function cookie(name, val, maxAgeSec, httpOnly) { return name + '=' + encodeURIComponent(val) + '; Path=/; SameSite=Lax; Max-Age=' + maxAgeSec + (httpOnly ? '; HttpOnly' : '') + (C.isProd ? '; Secure' : ''); }
function ip(req) {
if (process.env.CF_PROXIED === '1' && req.headers['cf-connecting-ip']) return String(req.headers['cf-connecting-ip']).trim();
const xff = String(req.headers['x-forwarded-for'] || '').split(',').map(s => s.trim()).filter(Boolean);
return (xff.length ? xff[xff.length - 1] : String(req.socket.remoteAddress || '')).replace(/^::ffff:/, '');
}
const isBot = req => !req.headers['user-agent'] || BOT_UA.test(req.headers['user-agent']);
const visitorKey = req => hash('vk|' + ip(req) + '|' + (req.headers['user-agent'] || ''));
const ipKey = req => hash('ip|' + ip(req));
const buckets = new Map();
function limited(req, name, max, windowMs) {
const k = name + ':' + ip(req); const now = Date.now(); let b = buckets.get(k);
if (!b || now - b.t > windowMs) { b = { t: now, n: 0 }; buckets.set(k, b); }
if (buckets.size > 100000) buckets.clear();
return ++b.n > max;
}
const isAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const g = String(req.headers['x-admin-token'] || '');
return t.length >= 8 && g.length === t.length && crypto.timingSafeEqual(Buffer.from(g), Buffer.from(t)); };
// ---- network membership through the hub (InstantAdPay's lookup only while the hub is unreachable) ----
const netCache = new Map();
async function netMember(q) {
const h = q.u ? await hubpeople.byRef(q.u) : await hubpeople.byWallet(q.a);
if (h.ok) { const a = hubpeople.wallet(h.person); return a ? { address: a, username: h.person.username ? String(h.person.username) : null, hubId: h.person.id || null, via: 'hub' } : null; }
if (!C.networkLookupUrl) return null;
const k = q.u ? 'u:' + q.u.toLowerCase() : 'a:' + q.a.toLowerCase();
const hit = netCache.get(k); if (hit && Date.now() - hit.at < 3600000) return hit.m;
let m = null;
try { const ac = new AbortController(); setTimeout(() => ac.abort(), 4000).unref();
const qs = q.u ? 'u=' + encodeURIComponent(q.u) : 'a=' + encodeURIComponent(q.a);
const j = await (await fetch(C.networkLookupUrl + '?' + qs, { signal: ac.signal })).json();
if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username), via: 'iap' }; } catch (e) { return null; }
netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear();
return m;
}
const netVerified = m => !!m && m.netOk === true && !m.blocked;
async function verifyNet(addr) {
const m = store.member(addr); if (!m) return;
if (netVerified(m) && m.hubId && m.netAt && Date.now() - m.netAt < 6 * 3600000) return;
const h = await hubpeople.byWallet(addr);
if (h.ok && h.person) {
const patch = { netOk: !h.person.blocked, blocked: !!h.person.blocked, netAt: Date.now(), netBy: 'hub', hubId: h.person.id || null };
const n = h.person.username ? String(h.person.username) : null;
if (n && NAME_RE.test(n)) { const other = store.memberByName(n); if (!other || other.address === m.address) patch.username = n; }
store.upsertMember(addr, patch); return;
}
if (h.ok && !h.person) { if (!m.testMember) store.upsertMember(addr, { netOk: false, netAt: Date.now(), netBy: 'hub' }); return; }
// hub down: InstantAdPay's lookup, or how the member signed in
if (netVerified(m)) return;
const n = await netMember({ a: addr }).catch(() => null);
if ((n && n.address === m.address) || m.via === 'iap' || m.via === 'linkspin' || m.via === 'hub') store.upsertMember(addr, { netOk: true, netAt: Date.now(), netBy: 'fallback', username: m.username || (n && n.username) || null });
}
const session = req => store.session(cookies(req)['ypb.sid']);
networksso.init({ self: C.siteId, peer: 'iap', peerBase: () => C.iapBase, from: { iap: () => C.iapBase, linkspin: () => C.lsBase },
isProd: C.isProd, dataDir: C.dataDir, defaultPath: '/my',
member: async req => { const s = session(req); return s ? { address: s.address } : null; },
accept: async (email, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
signIn: async (email, req, v) => {
const patch = { via: v.iss };
if (v.name && NAME_RE.test(v.name)) { const other = store.memberByName(v.name); if (!other || other.address === v.wallet) patch.username = v.name; }
store.upsertMember(v.wallet, patch);
await verifyNet(v.wallet).catch(() => {});
return cookie('ypb.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true);
},
landing: to => to, signinPath: to => to });
hubevents.init({ dataDir: C.dataDir, site: 'yourprogrambuilder', end: who => store.endSessions(x => who.match(x) || who.match(store.member(x.address)), who.before) });
// ---- old site links (the YourFreeWorld site): /?<old username>, /index.php?<old>, /splashpg.php?r=<old>, /lcp.php?r=<old>,
// /join.php?r=<old> -> that person's member page here (oldrefs.json from the reconcile, matched by email to the hub, loaded by
// POST /api/admin/oldrefs). The old member pages map to their new places; any other *.php -> / ----
let oldRefs = { at: 0, map: {} };
function oldRefMap() {
if (Date.now() - oldRefs.at < 60000) return oldRefs.map;
let m = {}; try { m = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'oldrefs.json'), 'utf8')) || {}; } catch (e) {}
oldRefs = { at: Date.now(), map: m }; return m;
}
const OLD_PAGES = { '/login.php': '/my', '/loginform.php': '/my', '/stats.php': '/my', '/addprograms.php': '/my?tab=plant', '/updateprograms.php': '/my', '/programs.php': '/', '/programs1.php': '/',
'/faq.php': '/guides/faq', '/terms.php': '/terms', '/privacy.php': '/privacy', '/upgradepro.php': '/spotlight', '/advertise.php': '/spotlight', '/marketingtools.php': '/promote', '/contactus2.php': '/guides/faq' };
function oldLink(u) {
const p = u.pathname; const bare = u.search.slice(1).split('&')[0];
if (p === '/' || p === '/index.php') { if (!/^[A-Za-z0-9_.-]{2,40}$/.test(bare)) return p === '/' ? null : '/'; }
else if (!/\.php$/i.test(p)) return null;
const lp = p.toLowerCase();
const named = ['/splashpg.php', '/lcp.php', '/join.php'].includes(lp);
const old = named ? String(u.searchParams.get('r') || u.searchParams.get('ref') || (/^[A-Za-z0-9_.-]{2,40}$/.test(bare) ? bare : '')) : (lp === '/' || lp === '/index.php') ? bare : '';
const net = /^[A-Za-z0-9_.-]{2,40}$/.test(old) ? oldRefMap()[old.toLowerCase()] : null;
if (net) return '/' + encodeURIComponent(net);
return OLD_PAGES[lp] || '/';
}
const PAGES = { '/': 'index.html', '/my': 'my.html', '/spotlight': 'spotlight.html', '/transplanted': 'transplanted.html', '/ledger': 'ledger.html', '/contract': 'contract.html',
'/admin': 'admin.html', '/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html',
'/guides': 'guides.html', '/guides/how-it-works': 'guide-how.html', '/guides/is-it-legit': 'guide-legit.html', '/guides/free-account': 'guide-free.html', '/guides/planting': 'guide-planting.html', '/guides/faq': 'guide-faq.html' };
const RESERVED = new Set(['api', 'assets', 'art', 'go', 'r', 'p', 'sso', 'health', 'promote', 'sitemap.xml', 'robots.txt', 'favicon.ico', 'index.php', 'my', 'spotlight', 'transplanted',
'ledger', 'contract', 'admin', 'terms', 'disclaimer', 'privacy', 'guides', 'faq', 'how', 'plant', 'bed', 'seedbed', 'support']);
const challenges = new Map();
const tickets = new Map();
const srcHost = raw => { try { const x = new URL(String(raw || '')); if (!/^https?:$/.test(x.protocol)) return ''; const h = x.hostname.toLowerCase().replace(/^www\./, ''); return h === C.site || h.endsWith('.' + C.site) || !h.includes('.') ? '' : h.slice(0, 80); } catch (e) { return ''; } };
const refOf = req => { const r = String(cookies(req)['ypb.ref'] || ''); return NAME_RE.test(r) ? r : null; };
const refCookie = name => cookie('ypb.ref', name, C.viaDays * 86400, false);
function issueTicket(req, page, shown, src) {
if (isBot(req) || req.headers['sec-fetch-site'] === 'cross-site' || limited(req, 'ticket', 240, 3600000)) return null;
const s = session(req); const t = crypto.randomBytes(12).toString('hex');
tickets.set(t, { vk: visitorKey(req), iph: ipKey(req), at: Date.now(), page, shown, src: srcHost(src), viewer: s ? s.address : null });
if (tickets.size > 50000) { const cut = Date.now() - 1800000; for (const [k, v] of tickets) if (v.at < cut) tickets.delete(k); }
return t;
}
const withReturn = url => { try { const x = new URL(url); if (!/^(www\.)?(instantadpay\.com|linkspin\.app)$/.test(x.hostname) && x.origin !== new URL(C.iapBase).origin) return url; x.searchParams.set('return', C.siteId); x.searchParams.set('to', '/my'); return x.toString(); } catch (e) { return url; } };
const joinUrl = ref => withReturn(ref ? C.joinUrl.split('{ref}').join(encodeURIComponent(ref)) : C.joinUrl.replace(/\/join\/\{ref\}.*$/, '/').replace(/[?&]ref=\{ref\}/, '').split('{ref}').join(''));
function cleanText(s, max) { return String(s == null ? '' : s).replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(/[–—]/g, '-').replace(/\s+/g, ' ').trim().slice(0, max + 1); }
// LinkSpin network ad zones (the ViralAdSource hook): LS_ZONES='{"footWide":"ls-..","footPhone":"ls-..","ledger":"ls-..","notFound":"ls-.."}', made on
// Marty's LinkSpin account through LinkSpin's admin zone route at go-live. Unset (staging): no zones shown.
const lsZones = () => { try { const z = JSON.parse(process.env.LS_ZONES || '{}'); const o = {}; for (const k of ['footWide', 'footPhone', 'ledger', 'notFound']) if (/^ls-[a-z0-9]{4,12}$/.test(String(z[k] || ''))) o[k] = z[k]; return o; } catch (e) { return {}; } };
const uname = a => { const m = store.member(a); return m && m.username ? m.username : null; };
const todayStats = () => { const t = store.today(); return { saves: t.saves || 0, planted: t.planted || 0, vclicks: t.vclicks || 0, packets: store.packets().filter(seedbed.shown).length }; };
function myEarned(me) {
let wei = 0n; const items = [];
for (const x of wire.purchases()) for (const q of x.pays || []) if (q.to === me && q.kind > 0) { try { wei += BigInt(q.wei); } catch (e) {} items.push({ tx: String(x.key).split(':')[0], at: (x.blockAt ? x.blockAt * 1000 : x.at), kind: q.kind, depth: q.depth, wei: q.wei, failed: !!q.failed, buyerName: uname(x.buyer) }); }
return { wei: wei.toString(), items: items.sort((a, b) => (b.at || 0) - (a.at || 0)).slice(0, 50) };
}
// the chain a link is chosen along: a ?r= / member-page / ref-cookie visitor starts at that member (depth 0) and goes up their line;
// a signed-in member starts at their sponsor (depth 1). The hub is the source of the line (cached 5 minutes, hubline.js).
async function chainFor(req, override) {
const s = session(req); const ref = override || refOf(req);
if (ref && (!s || (uname(s.address) || '').toLowerCase() !== ref.toLowerCase())) {
const lo = await hubline.lineOf({ ref: ref.toLowerCase() }, 6).catch(() => ({ ok: false, line: [] }));
const local = store.memberByName(ref);
const head = { wallet: (lo.person && hubpeople.wallet(lo.person)) || (local && local.address) || null, username: ref, depth: 0 };
return [head].concat((lo.line || []).filter(x => !x.blocked).map(x => ({ wallet: x.wallet, username: x.username, depth: x.depth })));
}
if (s) { const lo = await hubline.lineOf({ wallet: s.address }, 6).catch(() => ({ ok: false, line: [] })); return (lo.line || []).filter(x => !x.blocked).map(x => ({ wallet: x.wallet, username: x.username, depth: x.depth })); }
return [];
}
// a fresh check of a packet's link (plant, edit, recheck, admin). Probe off (LINK_PROBE=0, local tests): text flags only.
async function checkPacket(p, flags) {
const pr = C.linkProbe ? await linkcheck.probe(p.url).catch(() => ({ ok: false, why: 'check failed' })) : { skipped: true };
const v = linkcheck.verdict(flags || p.flags || [], pr, p.check);
p.check = Object.assign({ at: Date.now() }, v); p.flags = flags || p.flags || [];
if (p.status === 'live' || p.status === 'held') p.status = v.state === 'green' || (v.state === 'yellow' && p.yellowOk === seedbed.textHash(p)) ? 'live' : 'held';
if (p.reportsOpen >= C.reportHold && !p.reportsCleared) p.status = 'held';
store.savePacket(p); return v;
}
// the daily recheck of every live and held packet (one at a time, small batches)
async function recheckSweep(max) {
const due = Date.now() - C.recheckHours * 3600000; let n = 0;
for (const p of store.packets()) {
if (n >= (max || 20)) break;
if (!['live', 'held'].includes(p.status) || p.manualHold || (p.check && p.check.at > due)) continue;
n++; await checkPacket(p).catch(() => {});
}
return n;
}
function packetPublic(p, me) {
const sp = wire.spotProgress(p.id);
return seedbed.card(p, { spotlight: sp && sp.active ? { views: sp.views, delivered: sp.delivered } : null, mine: me ? !!store.saveOf(p.id, me) : false, own: me ? p.owner === me : false });
}
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://x'); const p = u.pathname;
{ const host = String(req.headers.host || '').toLowerCase().split(':')[0];
if (C.isProd && host !== C.site && host.endsWith('.' + C.site)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } }
try {
if (req.method === 'GET' && await networksso.page(req, res, u)) return;
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
if ((p === '/api/promo-kit' || p === '/promote') && promokit.handle(req, res, u, sendFile)) return;
if ((p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) && await chatbot.handle(req, res, p, u, { json, readBody, isAdmin })) return;
if (req.method === 'GET' || req.method === 'HEAD') {
if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files' });
{ const to = oldLink(u); if (to) { res.writeHead(301, { Location: to, 'Cache-Control': 'no-store' }); return res.end(); } }
if (PAGES[p]) {
const ex = {}; const ref = u.searchParams.get('ref');
if (ref && NAME_RE.test(ref)) ex['Set-Cookie'] = refCookie(ref);
if (p === '/my' || p === '/admin') ex['X-Frame-Options'] = 'DENY';
return sendFile(res, path.join(PUB, PAGES[p]), ex);
}
if (p === '/how' || p === '/faq' || p === '/plant') { res.writeHead(301, { Location: { '/how': '/guides/how-it-works', '/faq': '/guides/faq', '/plant': '/my?tab=plant' }[p] }); return res.end(); }
const pk = /^\/p\/(\d{1,9})\/?$/.exec(p);
if (pk) { const x = store.packet(pk[1]); if (!x || !seedbed.shown(x)) { res.writeHead(302, { Location: '/' }); return res.end(); }
const r = u.searchParams.get('r'); return sendFile(res, path.join(PUB, 'packet.html'), r && NAME_RE.test(r) ? { 'Set-Cookie': refCookie(r) } : {}); }
if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); }
if (p === '/sitemap.xml') {
const day = new Date().toISOString().slice(0, 10);
const urls = ['/', '/guides', '/guides/how-it-works', '/guides/is-it-legit', '/guides/free-account', '/guides/planting', '/guides/faq', '/spotlight', '/transplanted', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy']
.concat(store.packets().filter(seedbed.shown).map(x => '/p/' + x.id)).map(x => '<url><loc>https://' + C.site + x + '</loc><lastmod>' + day + '</lastmod></url>').join('');
res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }));
return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>');
}
if (p === '/robots.txt') { res.writeHead(200, headers({ 'Content-Type': 'text/plain; charset=utf-8' })); return res.end(C.staging ? 'User-agent: *\nDisallow: /\n' : 'User-agent: *\nAllow: /\nDisallow: /my\nDisallow: /admin\nDisallow: /api/\nDisallow: /go/\nDisallow: /sso/\n\nSitemap: https://' + C.site + '/sitemap.xml\n'); }
if (p.startsWith('/assets/') || p.startsWith('/art/') || p === '/favicon.ico') {
const f = path.normalize(path.join(PUB, p === '/favicon.ico' ? '/art/icon-192.png' : p)); if (!f.startsWith(PUB + path.sep)) { res.writeHead(400); return res.end(); }
return sendFile(res, f);
}
// click relay: /go/<packet>?v=<verified token>&p=<placement>&r=<member> -> the sponsor-first referral link (LinkSpin tracked when on)
const gm = /^\/go\/(\d{1,9})$/.exec(p);
if (gm) {
const x = store.packet(gm[1]); if (!x || !seedbed.shown(x)) { res.writeHead(302, { Location: '/' }); return res.end(); }
const r = u.searchParams.get('r'); const chain = await chainFor(req, r && NAME_RE.test(r) ? r : null);
const lk = seedbed.sponsorLink(x, chain); const sv = lk.save ? store.state().saves.find(s => s.id === lk.save) : null;
if (!isBot(req) && !limited(req, 'click', 600, 3600000)) { const vk = visitorKey(req); const ss = session(req); wire.click(x, vk, wire.vtokenOk(vk, u.searchParams.get('v')), ss ? ss.address : null, String(u.searchParams.get('p') || '').slice(0, 20), lk.save); }
const dest = (sv && lstrack.dest(sv, x)) || lk.url;
if (!dest) { res.writeHead(302, { Location: '/p/' + x.id }); return res.end(); }
res.writeHead(302, { Location: dest, 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end();
}
// a member's page: yourprogrambuilder.com/<network username> -> their saved packets, their links first (sets the ref tag)
const pm = PAGE_RE.exec(p);
if (pm && !RESERVED.has(pm[1].toLowerCase()) && !/\.php$/i.test(pm[1])) {
const name = pm[1]; const m = store.memberByName(name);
const h = m ? { ok: true, person: m } : await hubpeople.byRef(name.toLowerCase()).catch(() => ({ ok: false }));
if (h.ok && h.person) return sendFile(res, path.join(PUB, 'member.html'), { 'Set-Cookie': refCookie(m ? m.username : String(h.person.username || name)) });
}
}
// -- public API
if (p === '/api/config' && req.method === 'GET') {
const live = await shop.liveRules(C.spotlight.sku).catch(() => null);
return json(res, 200, { site: C.site, siteName: C.siteName, staging: C.staging, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId,
reviewSaves: C.reviewSaves, plantQuota: C.plantQuota, packet: C.packet, cats: seedbed.cats(), recheckHours: C.recheckHours,
spotlight: Object.assign({}, C.spotlight, live && live.sku ? { usd: live.sku.usdCents / 100, views: live.sku.views, live: true } : {}),
split: live ? { levelBps: live.levelBps, live: true } : Object.assign({ planned: true }, C.split),
sso: networksso.enabled() || networksso.hubOn(), shop: { live: shop.watching() && shop.signerOn(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, joinUrl: joinUrl(''),
dh: C.dhBase, zones: lsZones(), aiWriter: await adwriter.status().then(w => (w.on ? { daily: w.daily } : null)) });
}
// everything a page shows, with its visit ticket. page=front|packet|member|other, id=<packet>, u=<member>
if (p === '/api/wire' && req.method === 'GET') {
const kind = ['front', 'packet', 'member'].includes(u.searchParams.get('page')) ? u.searchParams.get('page') : 'other';
const s = session(req); const me = s ? s.address : null;
const out = { today: todayStats(), week: wire.weekStats(), need: C.reviewSaves }; const shown = []; const used = new Set();
if (kind === 'front') {
const live = store.packets().filter(seedbed.shown);
out.bed = live.map(x => packetPublic(x, me)).sort((a, b) => b.saves - a.saves || b.sownAt - a.sownAt);
out.bed.forEach(x => shown.push({ id: x.id, slot: 'bed' }));
}
if (kind === 'packet') {
const x = store.packet(Number(u.searchParams.get('id'))); if (!x || !seedbed.shown(x)) return json(res, 404, { error: 'That packet is not in the Seed Bed right now.' });
const lk = seedbed.sponsorLink(x, await chainFor(req, null));
out.packet = Object.assign(packetPublic(x, me), { linkBy: lk.by, linkFallback: lk.fallback, home: seedbed.homeUrl(x), recent: store.savesOf(x.id).filter(v => v.refId && seedbed.confirmed(v.owner)).sort((a, b) => b.at - a.at).slice(0, 12).map(v => uname(v.owner) || v.username).filter(Boolean) });
if (me) { const mine = store.saveOf(x.id, me); out.mySave = mine ? { refId: mine.refId, track: mine.track !== false, ls: lstrack.state(mine, x) } : null; }
shown.push({ id: x.id, slot: 'packet' }); used.add(x.id);
}
if (kind === 'member') {
const name = String(u.searchParams.get('u') || ''); const m = NAME_RE.test(name) ? store.memberByName(name) : null;
const h = m ? null : NAME_RE.test(name) ? await hubpeople.byRef(name.toLowerCase()).catch(() => ({ ok: false })) : { ok: false };
if (!m && !(h && h.ok && h.person)) return json(res, 404, { error: 'No network member by that name.' });
const list = m ? store.savesBy(m.address).filter(v => v.refId).map(v => store.packet(v.packetId)).filter(seedbed.shown) : [];
const planted = m ? store.packetsOf(m.address).filter(seedbed.shown) : [];
const ids = new Set(); const all = planted.concat(list).filter(x => (ids.has(x.id) ? false : ids.add(x.id)));
out.member = { username: m ? m.username : String(h.person.username || name), packets: all.map(x => Object.assign(packetPublic(x, me), { planted: !!(m && x.owner === m.address) })) };
all.forEach(x => { shown.push({ id: x.id, slot: 'member' }); used.add(x.id); });
out.joinUrl = joinUrl(out.member.username);
}
// the Spotlight places (top row of the bed; the strip on packet and member pages)
const spots = wire.pickSpots(C.spotlight.row, kind === 'front' ? null : used, seedbed.shown);
out.spotlights = spots.map(x => packetPublic(x, me)); spots.forEach(x => shown.push({ id: x.id, slot: 'spot' }));
const hunt = u.searchParams.get('hunt') === '1' || srcHost(u.searchParams.get('src')) === 'polhunter.com';
out.ticket = hunt ? null : issueTicket(req, kind, shown, u.searchParams.get('src'));
if (hunt) { out.hunt = true; store.bump('huntVisits'); }
out.seconds = C.visitSeconds;
return json(res, 200, out);
}
if (p === '/api/visit/seen' && req.method === 'POST') {
const b = await readBody(req); const t = tickets.get(String(b.ticket || ''));
if (!t || isBot(req) || t.vk !== visitorKey(req)) return json(res, 200, { verified: false, why: 'ticket' });
const age = Date.now() - t.at;
if (age < C.visitSeconds * 1000 - 300 || Number(b.visibleMs) < C.visitSeconds * 1000 - 300) return json(res, 200, { verified: false, why: 'early' });
tickets.delete(String(b.ticket));
if (age > 1800000) return json(res, 200, { verified: false, why: 'ticket' });
const r = wire.verify(t);
return json(res, 200, Object.assign(r, r.verified ? { vt: wire.vtoken(t.vk) } : {}));
}
// the packets in the bed, no visit ticket (pickers that do not show the packets, e.g. the Spotlight page: views are never counted here)
if (p === '/api/packets' && req.method === 'GET') return json(res, 200, { items: store.packets().filter(seedbed.shown).map(x => ({ id: x.id, no: String(x.id).padStart(3, '0'), name: x.name })) }, { 'Cache-Control': 'public, max-age=30' });
if (p === '/api/transplanted' && req.method === 'GET') {
const list = store.packets().filter(x => x.stage === 'approved' && x.status !== 'removed').sort((a, b) => (b.decidedAt || 0) - (a.decidedAt || 0)).slice(0, 100);
const review = store.packets().filter(x => x.stage === 'review' && seedbed.shown(x)).length;
return json(res, 200, { items: list.map(x => seedbed.card(x, { approvedAt: x.decidedAt || null })), inReview: review }, { 'Cache-Control': 'public, max-age=30' });
}
// DownlineHydra's "New in the network" slot (hook, not wired on DownlineHydra yet): the packets with a Spotlight still delivering
if (p === '/api/spotlight-feed' && req.method === 'GET') {
const items = wire.pickSpots(6, null, seedbed.shown).map(x => ({ id: x.id, name: x.name, desc: x.desc, host: x.host, url: 'https://' + C.site + '/p/' + x.id }));
return json(res, 200, { site: C.site, items }, { 'Cache-Control': 'public, max-age=60', 'Access-Control-Allow-Origin': '*' });
}
if (p === '/api/ledger' && req.method === 'GET') return json(res, 200, proof.ledger(u.searchParams.get('n')), { 'Cache-Control': 'public, max-age=10' });
if (p === '/api/contract' && req.method === 'GET') { if (limited(req, 'contract', 600, 3600000)) return json(res, 429, { error: 'Too many requests' }); return json(res, 200, await proof.contract(), { 'Cache-Control': 'public, max-age=60' }); }
if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res);
if (p === '/api/network-deals' && req.method === 'GET') return netdeals.handle(req, res, 'yourprogrambuilder');
if (p === '/api/recent' && req.method === 'GET') {
const cut = Date.now() - 30 * 60000;
const planted = store.packets().filter(x => x.createdAt > cut && seedbed.shown(x)).slice(-6).map(x => ({ kind: 'plant', key: 'p' + x.id, at: x.createdAt, name: x.ownerName || null, packet: x.name, id: x.id }));
const saves = store.saves().filter(s => s.at > cut && s.refId).slice(-6).map(s => { const x = store.packet(s.packetId); return x && seedbed.shown(x) ? { kind: 'save', key: 's' + s.id + s.at, at: s.at, name: uname(s.owner), packet: x.name, id: x.id } : null; }).filter(Boolean);
const grown = store.packets().filter(x => x.reviewAt && x.reviewAt > cut && seedbed.shown(x)).map(x => ({ kind: 'review', key: 'g' + x.id, at: x.reviewAt, packet: x.name, id: x.id }));
const spots = proof.ledger(10).items.filter(x => x.at && x.at > cut).map(x => ({ kind: 'spotlight', key: 'b' + x.tx + x.orderId, at: x.at, name: x.buyerName, packet: x.packet ? x.packet.name : null }));
return json(res, 200, { items: planted.concat(saves, grown, spots).sort((a, b) => b.at - a.at) }, { 'Cache-Control': 'public, max-age=10' });
}
if (p === '/api/quote' && req.method === 'GET') {
if (!shop.watching()) return json(res, 503, { error: 'Spotlights are not on sale yet.' });
if (limited(req, 'quote', 600, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const qty = Number(u.searchParams.get('qty') || 1);
if (!Number.isInteger(qty) || qty < 1 || qty > C.spotlight.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.spotlight.maxQty + ' Spotlights.' });
try { return json(res, 200, Object.assign({ usd: C.spotlight.usd * qty, views: C.spotlight.views * qty }, await shop.quote(C.spotlight.sku, qty))); } catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/gas' && req.method === 'GET') { try { return json(res, 200, shop.watching() ? await shop.fees() : {}); } catch (e) { return json(res, 200, {}); } }
if (/^\/api\/tx\/0x[0-9a-fA-F]{64}$/.test(p) && req.method === 'GET') {
if (!shop.watching() || limited(req, 'tx', 1200, 3600000)) return json(res, 200, { found: false });
try { return json(res, 200, await shop.receipt(p.slice(8))); } catch (e) { return json(res, 200, { found: false }); }
}
// wallet sign-in
if (p === '/api/auth/challenge' && req.method === 'POST') {
if (limited(req, 'auth', 30, 600000)) return json(res, 429, { error: 'Too many sign-in attempts. Wait a few minutes.' });
const b = await readBody(req); if (!ADDR_RE.test(b.address || '')) return json(res, 400, { error: 'Bad address' });
const a = b.address.toLowerCase(); const nonce = crypto.randomBytes(16).toString('hex');
const message = C.site + ' wants you to sign in with your wallet:\n' + getAddress(a) + '\n\nYourProgramBuilder sign-in. This signature is free and cannot move funds or approve anything.\n\nChain ID: ' + C.chainId + '\nNonce: ' + nonce + '\nIssued At: ' + new Date().toISOString();
challenges.set(a, { message, exp: Date.now() + 600000 }); if (challenges.size > 20000) challenges.clear();
return json(res, 200, { message });
}
if (p === '/api/auth/verify' && req.method === 'POST') {
const b = await readBody(req); const a = String(b.address || '').toLowerCase(); const ch = challenges.get(a);
if (!ch || ch.exp < Date.now()) return json(res, 400, { error: 'Sign-in request expired. Tap sign in again.' });
let rec; try { rec = verifyMessage(ch.message, String(b.signature || '')).toLowerCase(); } catch (e) { return json(res, 400, { error: 'Invalid signature.' }); }
if (rec !== a) return json(res, 400, { error: 'Your wallet signed with a different account (' + rec.slice(0, 6) + '...' + rec.slice(-4) + '). Switch accounts and try again.' });
challenges.delete(a);
store.upsertMember(a, store.member(a) ? {} : { via: 'wallet' });
await verifyNet(a).catch(() => {});
return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('ypb.sid', store.mintSession(a), store.SESSION_TTL / 1000, true) });
}
if (p === '/api/auth/logout' && req.method === 'POST') {
const s = session(req); if (s) store.dropSession(s.token);
return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('ypb.sid', '', 0, true), networksso.offCookie()] });
}
if (p === '/api/auth/logout-everywhere' && req.method === 'POST') {
const s = session(req); let hub = { ok: false };
if (s) { hub = await networksso.signOutEverywhere(s); store.endSessions(x => x.address === s.address, Date.now() + 1000); }
return json(res, 200, { ok: true, everywhere: !!hub.ok }, { 'Set-Cookie': [cookie('ypb.sid', '', 0, true), networksso.offCookie()] });
}
if (p === '/api/hub/events' && req.method === 'POST') {
let raw = ''; try { raw = (await readRaw(req, 256 * 1024)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
const r = await hubevents.receive(req.headers, raw); return json(res, r.status, r.body);
}
if (p === '/api/me' && req.method === 'GET') {
const s = session(req); if (!s) return json(res, 200, { signedIn: false });
const m = store.member(s.address);
return json(res, 200, { signedIn: true, address: s.address, username: m ? m.username : null, netVerified: netVerified(m), test: !!(m && m.testMember) });
}
// the report button (signed-in network members): REPORT_HOLD distinct reports send the packet back to Marty's queue
if (p === '/api/report' && req.method === 'POST') {
const s = session(req); if (!s) return json(res, 401, { error: 'Sign in with your network account to report a packet.' });
if (limited(req, 'report', 20, 3600000)) return json(res, 429, { error: 'Too many reports this hour.' });
const m = store.member(s.address); if (!netVerified(m)) return json(res, 403, { error: 'Reports are for network members.' });
const b = await readBody(req); const x = store.packet(Number(b.packetId)); if (!x || x.status === 'removed') return json(res, 404, { error: 'Not found' });
const reason = ['broken', 'scam', 'wrong', 'other'].includes(b.reason) ? b.reason : 'other';
if (x.owner === s.address) return json(res, 400, { error: 'This is your own packet. Edit it on My packets instead.' });
if (store.reports().some(r => r.packetId === x.id && r.by === s.address && !r.closed)) return json(res, 200, { ok: true, already: true });
store.addReport({ packetId: x.id, by: s.address, reason, note: cleanText(b.note, 200) });
x.reportsOpen = store.reports().filter(r => r.packetId === x.id && !r.closed).length;
if (x.reportsOpen >= C.reportHold && x.status === 'live') { x.status = 'held'; x.heldWhy = 'reported'; x.reportsCleared = false; }
store.savePacket(x); return json(res, 200, { ok: true });
}
// -- member API
if (p.startsWith('/api/my')) {
const s = session(req); if (!s) return json(res, 401, { error: 'Sign in first.' });
const me = s.address; if (!store.member(me)) store.upsertMember(me, { via: 'wallet' });
if (p === '/api/my' && req.method === 'GET') {
await verifyNet(me).catch(() => {}); const m = store.member(me);
const mine = store.packetsOf(me).filter(x => x.status !== 'dormant').map(x => Object.assign(seedbed.card(x), { status: x.status, check: x.check || null, heldWhy: x.heldWhy || null, url: x.url, ownerId: x.ownerId, views: x.views || 0, clicks: x.vclicks || 0,
reportsOpen: x.reportsOpen || 0, spotlight: wire.spotProgress(x.id), decidedNote: x.stage === 'rejected' ? x.decidedNote || null : null }));
const dormant = m.hubId ? store.packets().filter(x => x.status === 'dormant' && x.old && x.old.hubId === m.hubId).map(x => ({ id: x.id, name: x.name, url: x.old.url, added: x.old.added })) : [];
const saved = store.savesBy(me).filter(v => v.refId).map(v => { const x = store.packet(v.packetId); return x ? { packetId: x.id, name: x.name, refId: v.refId, link: seedbed.fill(x, v.refId), shown: seedbed.shown(x), stage: x.stage || 'sprouting', saves: x.sprouts || 0, clicks: v.clicks || 0, track: v.track !== false, ls: lstrack.state(v, x) } : null; }).filter(Boolean);
let lsClicks = null; if (lstrack.on() && m.username) lsClicks = await lstrack.clicks(m.username).catch(() => null);
return json(res, 200, { address: me, username: m.username, netVerified: netVerified(m), test: !!m.testMember, hubId: m.hubId || null, quota: C.plantQuota, packets: mine, dormant, saved, lsClicks,
spotlights: wire.purchases().filter(b => b.buyer === me).sort((x, y) => (y.at || 0) - (x.at || 0)).map(wire.spotView), earned: myEarned(me), joinUrl: joinUrl(''), page: m.username ? 'https://' + C.site + '/' + m.username : null });
}
if (p === '/api/my/plant' && req.method === 'POST') {
if (limited(req, 'plant', 20, 3600000)) return json(res, 429, { error: 'Too many changes this hour.' });
await verifyNet(me).catch(() => {}); const m = store.member(me);
if (!netVerified(m)) return json(res, 403, { error: 'Planting is free for network members. Join InstantAdPay or LinkSpin free, then sign in here with that account.', join: joinUrl('') });
const b = await readBody(req);
const v = seedbed.validatePlant(b); if (v.error) return json(res, 400, v);
const cur = b.id ? store.packet(Number(b.id)) : null;
if (b.id && (!cur || cur.owner !== me || cur.status === 'removed')) return json(res, 404, { error: 'That packet is not yours.' });
const dorm = b.dormant ? store.packet(Number(b.dormant)) : null;
if (b.dormant && !(dorm && dorm.status === 'dormant' && dorm.old && m.hubId && dorm.old.hubId === m.hubId)) return json(res, 404, { error: 'That old program is not yours to confirm.' });
if (!cur && !dorm && store.packetsOf(me).filter(x => x.status !== 'dormant').length >= C.plantQuota) return json(res, 400, { error: 'You have ' + C.plantQuota + ' packet planted, the most for one member. Remove it on My packets to plant a different one.' });
// one packet per program: the same link base (host + path before {id}) planted by someone else -> save your ID there instead
const stem = x => String(x.url).split('{id}')[0].toLowerCase().replace(/^https?:\/\/(www\.)?/, '');
const twin = store.packets().find(x => x !== cur && x !== dorm && !['removed', 'dormant'].includes(x.status) && x.url && stem(x) === stem(v.fields));
if (twin) return json(res, 409, { error: 'That program is already in the Seed Bed as packet No. ' + String(twin.id).padStart(3, '0') + '. Save your ID there instead.', packet: twin.id });
const pr = C.linkProbe ? await linkcheck.probe(v.fields.url).catch(() => ({ ok: false, why: 'check failed' })) : { skipped: true };
const vd = linkcheck.verdict(v.flags, pr, null);
if (vd.state === 'red') return json(res, 400, { error: 'The link check could not load your link (' + vd.why.filter(w => /^link /.test(w)).map(w => w.slice(5)).join(', ') + '). Check it opens in your browser, then try again.', check: vd });
let x = cur || dorm;
if (x) { const wasText = seedbed.textHash(x); Object.assign(x, v.fields, { owner: me, ownerName: m.username || null, flags: v.flags }); if (x.status === 'dormant') { x.status = 'live'; x.confirmedAt = Date.now(); x.createdAt = Date.now(); x.stage = 'sprouting'; } if (seedbed.textHash(x) !== wasText) delete x.yellowOk; }
else { x = store.addPacket(Object.assign({ owner: me, ownerName: m.username || null, status: 'live', stage: 'sprouting', flags: v.flags, views: 0, clicks: 0, vclicks: 0 }, v.fields)); store.bump('planted'); }
x.check = Object.assign({ at: Date.now() }, vd);
x.status = vd.state === 'green' || (vd.state === 'yellow' && x.yellowOk === seedbed.textHash(x)) ? 'live' : 'held'; if (x.status === 'held') x.heldWhy = 'link check';
seedbed.grow(x);
return json(res, 200, { ok: true, packet: { id: x.id, status: x.status, check: vd.state, why: vd.why }, created: !cur && !dorm });
}
if (p === '/api/my/packet/remove' && req.method === 'POST') {
const b = await readBody(req); const x = store.packet(Number(b.id)); if (!x || x.owner !== me || x.status === 'removed') return json(res, 404, { error: 'Not found' });
if (x.stage === 'approved') return json(res, 400, { error: 'This packet was transplanted into the builder. Ask network support to change it there.' });
x.status = 'removed'; x.removedBy = 'owner'; store.savePacket(x); return json(res, 200, { ok: true });
}
if (p === '/api/my/save' && req.method === 'POST') {
if (limited(req, 'save', 120, 3600000)) return json(res, 429, { error: 'Too many saves this hour.' });
await verifyNet(me).catch(() => {}); const m = store.member(me);
if (!netVerified(m)) return json(res, 403, { error: 'Saving your ID is free for network members. Sign in with your network account first.', join: joinUrl('') });
const b = await readBody(req); const x = store.packet(Number(b.packetId)); if (!x || !seedbed.shown(x)) return json(res, 404, { error: 'That packet is not in the Seed Bed right now.' });
if (x.owner === me) return json(res, 400, { error: 'This is your packet: your ID is the planter\'s ID. Change it on My packets.' });
const id = seedbed.cleanId(x, b.refId);
if (id === null) return json(res, 400, { error: 'That does not look like a referral ID for this program. Type only your ID, or paste your whole referral link for it.' });
if (id === '') { store.dropSave(x.id, me); seedbed.grow(x); return json(res, 200, { ok: true, removed: true, saves: x.sprouts }); }
const had = store.saveOf(x.id, me);
const sv = store.putSave(x.id, me, { refId: id, username: m.username || null, hubId: m.hubId || null, track: b.track === undefined ? (had ? had.track !== false : true) : b.track !== false });
if (!had) store.bump('saves');
const g = seedbed.grow(x);
if (lstrack.on()) lstrack.ensureSave(sv).catch(() => {});
return json(res, 200, { ok: true, refId: id, link: seedbed.fill(x, id), saves: g.n, review: g.review, need: C.reviewSaves });
}
if (p === '/api/my/order' && req.method === 'POST') {
if (!shop.watching() || !shop.signerOn()) return json(res, 503, { error: 'Spotlights are not on sale yet.' });
if (limited(req, 'order', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const b = await readBody(req); const qty = Number(b.qty || 1);
if (!Number.isInteger(qty) || qty < 1 || qty > C.spotlight.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.spotlight.maxQty + ' Spotlights.' });
const x = store.packet(Number(b.packetId)); if (!x || !seedbed.shown(x)) return json(res, 400, { error: 'Pick a packet that is in the Seed Bed.' });
const lo = await hubline.lineOf({ wallet: me }, shop.MAX_LINE);
if (!lo.ok) return json(res, 503, { error: 'Your sponsor line could not be checked with the network just now. Try again in a minute, so your team gets paid.' });
// eligibility (the ViralAdSource rule, Marty 2026-11-17): a network member (hub, not blocked) with a linked wallet earns a level,
// Spotlight or not. Dropping the ineligible here IS the compression; levels left when the line runs out go to the company
const line = lo.line.filter(y => y.wallet && !y.blocked && y.wallet !== me).map(y => y.wallet);
try { return json(res, 200, Object.assign({ buyer: me, usd: C.spotlight.usd * qty, views: C.spotlight.views * qty, qty, packetId: x.id }, await shop.order(me, C.spotlight.sku, qty, x.id, line))); }
catch (e) { console.error('order failed:', String(e && e.message || e).slice(0, 200)); return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); }
// the AI writer (2026-11-17, through the hub): a name and a one-sentence description from the program's own page; nothing is saved
if (p === '/api/my/adwriter' && req.method === 'POST') {
if (!(await adwriter.enabled())) return json(res, 503, { error: 'The writer is switched off right now. You can still write it yourself.' });
if (limited(req, 'adwriter', 12, 3600000)) return json(res, 429, { error: 'Too many writes from this connection this hour. Try again later, or write it yourself.' });
const m = store.member(me); await verifyNet(me).catch(() => {});
if (!netVerified(m)) return json(res, 403, { error: 'The writer is for network members. Sign in with your network account first.' });
const b = await readBody(req); const url = String(b.url || '').trim().replace(/\{id\}/g, 'x').slice(0, 600);
const r = await adwriter.write(me, url, { headline: C.packet.name, line: C.packet.desc });
if (r.error) return json(res, r.status || 400, { error: r.error, code: r.code, left: r.left });
return json(res, 200, { ok: true, options: r.options, url: r.url, cached: r.cached, left: r.left });
}
return json(res, 404, { error: 'Not found' });
}
// -- admin (x-admin-token: ADMIN_TOKEN)
if (p.startsWith('/api/admin/')) {
if (!isAdmin(req)) return json(res, 401, { error: 'no' });
if (p === '/api/admin/status' && req.method === 'GET') {
const S = store.state(); const P = store.packets();
const count = f => P.filter(f).length;
return json(res, 200, { day: store.ctDay(), week: store.ctWeek(), staging: C.staging, testSwitch: TEST_SWITCH, config: { reviewSaves: C.reviewSaves, plantQuota: C.plantQuota, spotlight: C.spotlight, split: C.split, hubJoin: C.hubJoin, payouts: C.payouts, linkProbe: C.linkProbe },
today: store.today(), totals: S.totals, members: store.members().length,
packets: { all: P.length, shown: count(seedbed.shown), held: count(x => x.status === 'held'), dormant: count(x => x.status === 'dormant'), review: count(x => x.stage === 'review' && x.status !== 'removed'), approved: count(x => x.stage === 'approved'), removed: count(x => x.status === 'removed') },
saves: store.saves().filter(v => v.refId).length, reportsOpen: store.reports().filter(r => !r.closed).length,
shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), hubEvents: hubevents.view(), sso: { hub: networksso.hubOn(), pairwise: networksso.enabled() },
linkspin: lstrack.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length, adWriter: await adwriter.status() });
}
// Marty's queue: held packets (yellow / red link, reported) and packets that reached the review threshold
if (p === '/api/admin/queue' && req.method === 'GET') {
const row = x => Object.assign(seedbed.card(x), { status: x.status, url: x.url, ownerId: x.ownerId, owner: x.owner, check: x.check || null, flags: x.flags || [], heldWhy: x.heldWhy || null,
reports: store.reports().filter(r => r.packetId === x.id && !r.closed).map(r => ({ id: r.id, reason: r.reason, note: r.note, by: uname(r.by) || r.by, at: r.at })), reviewAt: x.reviewAt || null, manualHold: !!x.manualHold });
const P = store.packets();
return json(res, 200, { held: P.filter(x => x.status === 'held').map(row), review: P.filter(x => x.stage === 'review' && x.status !== 'removed').sort((a, b) => (a.reviewAt || 0) - (b.reviewAt || 0)).map(row),
approved: P.filter(x => x.stage === 'approved').map(row).slice(0, 100), live: P.filter(seedbed.shown).length });
}
if (p === '/api/admin/packet' && req.method === 'POST') {
const b = await readBody(req); const x = store.packet(Number(b.id)); if (!x) return json(res, 404, { error: 'not found' });
const note = cleanText(b.note, 300); const a = String(b.action || '');
if (a === 'show') { x.yellowOk = seedbed.textHash(x); x.manualHold = false; x.reportsCleared = true; x.status = x.check && x.check.state === 'red' ? 'held' : 'live'; delete x.heldWhy; for (const r of store.reports()) if (r.packetId === x.id && !r.closed) { r.closed = Date.now(); store.saveReport(r); } x.reportsOpen = 0; }
else if (a === 'hold') { x.status = 'held'; x.manualHold = true; x.heldWhy = note || 'held by Marty'; }
else if (a === 'remove') { x.status = 'removed'; x.removedBy = 'admin'; x.note = note; }
else if (a === 'restore') { x.status = 'held'; x.manualHold = false; }
else if (a === 'recheck') { x.manualHold = false; await checkPacket(x); }
else if (a === 'approve') { if (x.stage !== 'review') return json(res, 400, { error: 'Only a packet in review can be approved.' }); x.stage = 'approved'; x.decidedAt = Date.now(); x.decidedNote = note; }
else if (a === 'reject') { if (x.stage !== 'review') return json(res, 400, { error: 'Only a packet in review can be rejected.' }); x.stage = 'rejected'; x.decidedAt = Date.now(); x.decidedNote = note; }
else if (a === 'reopen') { x.stage = 'sprouting'; delete x.decidedAt; seedbed.grow(x); }
else return json(res, 400, { error: 'action show | hold | remove | restore | recheck | approve | reject | reopen' });
store.savePacket(x); return json(res, 200, { ok: true, packet: { id: x.id, status: x.status, stage: x.stage, check: x.check ? x.check.state : null } });
}
// approved packets for the CTB builder / DownlineHydra wild heads, every saved ID carried. mark=1 stamps exportedAt (the
// add on CTB / DownlineHydra is done there: this site never writes to another site)
if (p === '/api/admin/export' && req.method === 'GET') {
const all = u.searchParams.get('all') === '1';
const list = store.packets().filter(x => x.stage === 'approved' && (all || !x.exportedAt));
if (u.searchParams.get('mark') === '1') for (const x of list) { x.exportedAt = Date.now(); store.savePacket(x); }
return json(res, 200, { v: 1, site: C.site, exportedAt: Date.now(), format: 'ctb-builder', placeholder: '{affiliateid}', packets: list.map(seedbed.exportPacket) });
}
if (p === '/api/admin/recheck' && req.method === 'POST') return json(res, 200, { checked: await recheckSweep(Number((await readBody(req)).max) || 50) });
if (p === '/api/admin/test-member' && req.method === 'POST') {
if (!TEST_SWITCH) return json(res, 403, { error: 'The test switch exists on staging only.' });
const b = await readBody(req); if (!ADDR_RE.test(b.address || '') || (b.username && !NAME_RE.test(b.username))) return json(res, 400, { error: 'address (+ username)' });
const a = b.address.toLowerCase(); const other = b.username ? store.memberByName(b.username) : null;
if (other && other.address !== a) return json(res, 409, { error: 'username taken here' });
const mm = store.upsertMember(a, { netOk: b.on !== false, netBy: 'test', netAt: Date.now() + 365 * 86400000, testMember: b.on !== false, hubId: b.hubId || (store.member(a) || {}).hubId || 'h_test' + crypto.createHash('sha256').update(a).digest('hex').slice(0, 10), username: b.username || (store.member(a) || {}).username || null });
return json(res, 200, { ok: true, member: mm });
}
if (p === '/api/admin/oldrefs' && req.method === 'POST') {
let b; try { b = JSON.parse((await readRaw(req, 4 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); }
if (!b || !b.oldrefs || typeof b.oldrefs !== 'object') return json(res, 400, { error: 'oldrefs object required' });
// old usernames are matched case-blind (the lookup lowercases); two old names that differ only in case point nowhere (a clash)
const o = {}, clash = new Set(); for (const [k0, v] of Object.entries(b.oldrefs)) { const k = String(k0).toLowerCase(); if (!/^[a-z0-9_.-]{2,40}$/.test(k) || !NAME_RE.test(String(v))) continue; if (o[k] && o[k] !== String(v)) clash.add(k); o[k] = String(v); }
for (const k of clash) delete o[k];
fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} };
return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length, clashes: clash.size });
}
// old YourProgramBuilder member programs as dormant packets (myheads.csv from the reconcile): {packets: [{oldId, oldUsername, hubId,
// name, url, added}]}. Only people the hub knows (hubId). Nothing shows until the owner confirms it with a {id} link on My packets.
if (p === '/api/admin/dormant' && req.method === 'POST') {
let b; try { b = JSON.parse((await readRaw(req, 2 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); }
const list = Array.isArray(b && b.packets) ? b.packets : null; if (!list) return json(res, 400, { error: 'packets array required' });
let created = 0, skipped = 0;
for (const r of list) {
const oldId = String(r.oldId || ''); const hubId = String(r.hubId || '');
if (!/^\d{1,9}$/.test(oldId) || !/^h_[0-9a-f]{16}$/.test(hubId) || store.packets().some(x => x.old && x.old.oldId === oldId)) { skipped++; continue; }
const name = cleanText(r.name, C.packet.name).slice(0, C.packet.name); const url = String(r.url || '').trim().slice(0, 500);
if (name.length < 2 || !/^https?:\/\//i.test(url)) { skipped++; continue; }
if (!b.dry) store.addPacket({ owner: '', ownerName: null, status: 'dormant', stage: 'sprouting', name, url: '', desc: '', old: { oldId, oldUsername: String(r.oldUsername || '').slice(0, 40), hubId, url, added: String(r.added || '').slice(0, 10) } });
created++; // with dry: counted, nothing written (it used to write anyway)
}
return json(res, 200, { ok: true, created, skipped, dry: !!b.dry });
}
if (p === '/api/admin/member-lookup' && req.method === 'GET') {
const q = String(u.searchParams.get('q') || '').trim(); let a = null;
if (ADDR_RE.test(q)) a = q.toLowerCase(); else if (NAME_RE.test(q)) { const m = store.memberByName(q); a = m ? m.address : null; }
if (!a) return json(res, 404, { error: 'not found' });
return json(res, 200, { address: a, record: store.member(a), packets: store.packetsOf(a).map(x => seedbed.card(x, { status: x.status })), saves: store.savesBy(a).length, earned: myEarned(a) });
}
return json(res, 404, { error: 'Not found' });
}
if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });
res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' }));
return res.end('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not found | YourProgramBuilder</title><body style="background:#F6FAF1;color:#12291F;font-family:\'Atkinson Hyperlegible\',system-ui,sans-serif;text-align:center;padding:40px 16px"><p style="font-size:22px;font-weight:700">Nothing has sprouted here.</p><p><a style="color:#C24A08;font-weight:700" href="/">Back to the Seed Bed</a></p>' + (lsZones().notFound ? '<p style="font-size:11px;margin:24px 0 4px;opacity:.7">Network</p><script async src="https://linkspin.app/z.js" data-zone="' + lsZones().notFound + '"></script>' : '') + '</body>');
} catch (e) {
console.error('request', p, e.message);
if (!res.headersSent) json(res, 500, { error: 'Server error' });
}
});
(async () => {
await docstore.init({ splits: store.SPLITS });
process.on('SIGTERM', () => { store.flush(); docstore.drain(8000).finally(() => process.exit(0)); });
store.load();
wire.init();
store.prune(); wire.rebuild();
hubreport.init({ dataDir: C.dataDir, purchases: () => wire.purchases().map(x => ({ key: x.key, buyer: x.buyer, sponsor: null, usdCents: x.usdCents, block: x.block, at: x.at })) });
proof.init(C, { shop, wire });
shop.setAttach(rec => { wire.attach(rec); store.bump('spotlights', Number(rec.qty) || 1); });
shop.setHook(proof.onPurchase);
shop.init(C);
setInterval(() => { if (store.prune()) wire.rebuild(); }, 3600000).unref();
chatbot.init();
lstrack.init(C, store, seedbed);
{ let busy = false; const tick = () => { if (busy) return; busy = true; Promise.all([lstrack.sweep(25), recheckSweep(20)]).catch(() => {}).finally(() => { busy = false; }); };
setTimeout(tick, Number(process.env.SWEEP_FIRST_MS || 30000)).unref(); setInterval(tick, Number(process.env.SWEEP_MS || 300000)).unref(); }
server.listen(C.port, () => console.log('YourProgramBuilder on :' + C.port + (C.staging ? ' (staging)' : '') + ', review at ' + C.reviewSaves + ' saves, store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)')));
})().catch(e => { console.error('start failed:', e.message); process.exit(1); });
process.on('SIGINT', () => { store.flush(); process.exit(0); });