// Shared network knowledge, site side (Marty 2026-11-15: every network site's chatbot answers about the whole network, with its // own site first). This site publishes its own knowledge-base entries to the network hub and reads the merged set back: // PUT HUB_URL/v1/kb {name, url, entries} replaces this site's set (the hub skips a set it already holds) // GET HUB_URL/v1/kb signed over an empty body, If-None-Match: the last version -> 304 when nothing changed // Signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + "\n" + raw body)), like hubreport.js. // The merged set is kept in memory and in DATA_DIR/netkb-cache.json (a MySQL document through docstore where the site has // DOCSTORE_URL; written only when the version changes), so a hub outage at boot still answers about the other sites. // Off when HUB_URL or a 32+ character HUB_SECRET is missing, or NETKB=0: the chatbot then answers about this site only. // The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline // Banners, Stack POL). Keep them identical. 'use strict'; const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const REFRESH_MS = 10 * 60 * 1000; let O = null; // { dataDir, site, name, url, netId, entries: async () => [...], linkFor: (url) => link } let merged = { version: '', sites: {}, entries: [] }, loadedAt = 0, publishedHash = '', pubTimer = null, timer = null; const stats = { published: 0, publishErrors: 0, reads: 0, notModified: 0, readErrors: 0, lastError: null, lastPublishAt: 0, lastReadAt: 0 }; const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, ''); const secret = () => String(process.env.HUB_SECRET || '').trim(); const siteName = () => String(process.env.HUB_SITE || (O && O.site) || '').trim(); const enabled = () => process.env.NETKB !== '0' && !!hubUrl() && secret().length >= 32 && !!siteName(); const cacheFile = () => (O && O.dataDir ? path.join(O.dataDir, 'netkb-cache.json') : null); async function call(method, route, body, headers) { const raw = body === undefined ? '' : JSON.stringify(body); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex'); const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(15000), headers: Object.assign({ 'Content-Type': 'application/json', 'X-Hub-Site': siteName(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, headers || {}) }); let j = null; if (r.status !== 304) { try { j = await r.json(); } catch (e) {} } return { status: r.status, body: j }; } // the entries this site shares: what the chatbot's knowledge base holds, minus the instant-answer patterns (those stay home) const shape = e => ({ id: String(e.id), title: e.title, questions: (e.questions || []).slice(0, 15), answer: e.answer, tags: (e.tags || []).slice(0, 15), link: e.link || (O && O.url) || undefined }); async function publish() { if (!enabled() || !O || typeof O.entries !== 'function') return { skipped: true }; const entries = (await O.entries()).filter(e => e && e.id && e.answer && !e.deleted).map(shape); const body = { name: O.name, url: O.url, entries }; const h = crypto.createHash('sha1').update(JSON.stringify(body)).digest('hex'); if (h === publishedHash) return { same: true }; try { const r = await call('PUT', '/v1/kb', body); if (r.status !== 200) { stats.publishErrors++; stats.lastError = 'publish ' + r.status + ' ' + ((r.body && r.body.error) || ''); return { error: stats.lastError }; } publishedHash = h; stats.published++; stats.lastPublishAt = Date.now(); return r.body; } catch (e) { stats.publishErrors++; stats.lastError = 'publish ' + e.message; return { error: e.message }; } } // an admin edit: publish a few seconds later (several quick edits go as one) function publishSoon() { if (pubTimer) return; pubTimer = setTimeout(() => { pubTimer = null; publish().catch(() => {}); }, 5000); if (pubTimer.unref) pubTimer.unref(); } function readCache() { const f = cacheFile(); if (!f) return; try { const d = JSON.parse(fs.readFileSync(f, 'utf8')); if (d && Array.isArray(d.entries)) { merged = d; loadedAt = 0; } } catch (e) {} } function writeCache() { const f = cacheFile(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(merged)); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('netkb cache', e.message); } } async function refresh() { if (!enabled()) return { skipped: true }; try { const r = await call('GET', '/v1/kb', undefined, merged.version ? { 'If-None-Match': '"' + merged.version + '"' } : {}); stats.lastReadAt = Date.now(); if (r.status === 304) { stats.notModified++; loadedAt = Date.now(); return { same: true }; } if (r.status !== 200 || !r.body || !Array.isArray(r.body.entries)) { stats.readErrors++; stats.lastError = 'read ' + r.status; return { error: stats.lastError }; } merged = { version: String(r.body.version || ''), sites: r.body.sites || {}, entries: r.body.entries }; loadedAt = Date.now(); stats.reads++; writeCache(); return { version: merged.version, count: merged.entries.length }; } catch (e) { stats.readErrors++; stats.lastError = 'read ' + e.message; return { error: e.message }; } } // other sites' entries, ready for the chatbot's index: id ":", plus where they come from and the link to send people to function remote() { const me = siteName(); const out = []; for (const e of merged.entries || []) { if (!e || e.site === me) continue; const s = (merged.sites || {})[e.site] || {}; const url = s.url || e.link || ''; out.push({ id: e.site + ':' + e.id, title: e.title, questions: e.questions || [], answer: e.answer, tags: e.tags || [], site: e.site, siteName: s.name || e.site, siteUrl: url, go: (O && typeof O.linkFor === 'function' && url ? O.linkFor(url) : '') || url }); } return out; } // the network's sites as the hub knows them (name, link), this one left out function sites() { const me = siteName(); return Object.entries(merged.sites || {}).filter(([k]) => k !== me).map(([k, s]) => ({ site: k, name: s.name || k, url: s.url || '', go: (O && typeof O.linkFor === 'function' && s.url ? O.linkFor(s.url) : '') || s.url || '', count: s.count || 0 })); } // opts: { dataDir, site (hub site id), name, url, entries: async () => [...], linkFor: url => tracked link } function init(opts) { O = opts || {}; readCache(); if (!enabled()) return; const first = setTimeout(async () => { await publish().catch(() => {}); await refresh().catch(() => {}); }, Math.max(0, Number(process.env.NETKB_FIRST_MS) || 8000)); if (first.unref) first.unref(); timer = setInterval(async () => { await refresh().catch(() => {}); if (!publishedHash) await publish().catch(() => {}); }, Math.max(1000, Number(process.env.NETKB_REFRESH_MS) || REFRESH_MS)); if (timer.unref) timer.unref(); } function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt }, stats); } function _set(m) { merged = m; } // tests const version = () => merged.version || ''; module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, _set };