Site assistant (Marty 2026-11-15): chat widget in the ViralAdBlitz look on every page, CANNED + FACTS from this repo's code (Boost $5/500 views, 10% x 5 + 50% company, 20 places, 30-day delivery, ad limits, verified views), retrieval over the shared network knowledge base on the hub (netkb.js publishes this site's entries and reads the others', home entries boosted), OpenRouter deepseek-v4-flash with reasoning off, account problems hand off to network support. kb.json is a MySQL document. qa/chatbot.test.mjs 195 pass, smoke 198/198
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -41,3 +41,13 @@ Admin: `/admin` with the `ADMIN_TOKEN` (status, Boost delivery, member lookup, a
|
||||
Coolify app `p5abaw5evbtf9qpk0wbv0mfd` (compose, Crypto Projects/production, volume vab-data, connect_to_docker_network on) on https://vab.saasy.top, MySQL `6dgur7sbgbwcawlxen6du1jr` (viraladblitz-mysql, binlog expiry 3 h, in /root/db-hourly-dump.sh). Repo git.saasy.top/marty/viraladblitz (contracts: marty/viraladblitz-contracts, private). SITE_HOST=vab.saasy.top, TG_* empty (no sale cards), HUB_ENABLED=1, KEEPER_KEY from /root/.vab-keeper-key, ADMIN_TOKEN /root/.vab-admin-token, HUB_SECRET /root/.vab-hub-secret (root-only on core).
|
||||
|
||||
Domain switch DONE 2026-11-15 ~8 AM CT: Coolify domains viraladblitz.com + www + vab.saasy.top, SITE_HOST=viraladblitz.com, TG_* from VBB (payments topic 632242), IAP VAB_URL, hub LOOKUP_SITES vab url (NETWORK_SITES with the hub deploy), Reown allowlist, rhi zone apex A 140.99.254.14 + MX mail.viraladblitz.com A 89.116.149.103, old crons off, old members reconciled on the hub (108 sponsors filled, 330 quiet joins, 6 bots blocked), oldrefs 2,351.
|
||||
|
||||
## Site assistant (2026-11-15)
|
||||
|
||||
Chat widget on every page (`public/assets/chat.js` + `chat.css` in this site's look). `chatbot.js` holds what it knows (CANNED
|
||||
instant answers + FACTS, written from this repo's code); `chatcore.js` (engine), `kb.js` (BM25 knowledge base, `kb.json` = a MySQL
|
||||
document) and `netkb.js` (the shared network knowledge on the hub: publishes this site's entries, reads the other sites') are the same
|
||||
files on every rebuilt site. OpenRouter key: `/app/data/openrouter.key` on the volume (copied from InstantAdPay). Account problems hand
|
||||
off to network support (`https://instantadpay.com/support?from=viraladblitz`). Admin API (x-admin-token): `/api/admin/kb`,
|
||||
`/api/admin/kb/<id>`, `/api/admin/kb/test`, `/api/admin/kb/network?refresh=1&publish=1`. Test: `node qa/chatbot.test.mjs`
|
||||
(Q&A in `qa/chat-qa.json`). House rule: a feature change updates CANNED + FACTS and KNOWLEDGE_DATE in the same commit.
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
// ViralAdBlitz's site assistant (Marty 2026-11-15): what it knows. The engine is chatcore.js (the same on every rebuilt site);
|
||||
// retrieval also covers the other network sites through the hub (netkb.js), this site's entries first.
|
||||
//
|
||||
// Every fact below was checked against this repo on KNOWLEDGE_DATE: config.js (Boost $5 / 500 views / max 10, split 10% x 5 +
|
||||
// 50% company, 20 places, 30-day delivery, ad 60/90/90 characters, 6 s visit, 3 browsers per connection a day), server.js
|
||||
// (/api/my/ad: network members only, https link, no shorteners, the link must answer; /api/my/order), shop.js + ../contracts
|
||||
// (VABShop: LEVELS 5, LEVEL_BPS 1000, MAX_DEPTH 20, MAX_QTY 10, no owner withdraw, undeliverable shares wait to be claimed),
|
||||
// wire.js (verified views and clicks), vabnas.js (Network Ad Space finishes a Boost after 30 days), lstrack.js (LinkSpin
|
||||
// tracked link, default on), hubline.js (the 5 people above with a live ad, up to 20 places), promokit.js, public/*.html.
|
||||
// HOUSE RULE: when a feature changes, update CANNED and FACTS in the same commit and bump KNOWLEDGE_DATE.
|
||||
// Plain words, no em dashes, never a promise of income, "SafePal or any other crypto wallet", never RM Circle.
|
||||
'use strict';
|
||||
const core = require('./chatcore');
|
||||
const C = require('./config').get();
|
||||
|
||||
const KNOWLEDGE_DATE = '2026-11-15';
|
||||
const URL_ = 'https://' + C.site;
|
||||
const SUPPORT = 'https://instantadpay.com/support';
|
||||
const B = C.boost, SP = C.split;
|
||||
const NOT_INCOME = 'A Boost buys advertising, not income.';
|
||||
|
||||
const CANNED = [
|
||||
{ id: 'support', title: 'Talk to a person, or a problem with my account', q: ['How do I contact support?', 'My Boost did not show up', 'I need a real person'], tags: ['support', 'help', 'ticket', 'problem'],
|
||||
re: core.SUPPORT_RE, handoff: true,
|
||||
a: 'Network support handles every network site, ViralAdBlitz included: open ' + SUPPORT + ', say it is about ViralAdBlitz, and include your wallet address and the transaction link if it is about a Boost. Marty answers there and by email. Tap "Open network support" below and your question goes with you.' },
|
||||
{ id: 'refund', title: 'Refunds', q: ['Can I get a refund?', 'Can you cancel my Boost?'], tags: ['refund', 'cancel'],
|
||||
re: /\brefund|cancel (my |a |the )?boost|money back|reverse (my |a |the )?(payment|transaction)/i, handoff: true,
|
||||
a: 'Boosts are paid on Polygon and are final once confirmed, so they cannot be reversed or refunded. If your ad is removed for breaking the terms, the views left on its Boosts are not delivered or refunded. If something went wrong with a purchase, open network support at ' + SUPPORT + ' with the transaction link.' },
|
||||
{ id: 'about', title: 'What is ViralAdBlitz?', q: ['What is ViralAdBlitz?', 'How does ViralAdBlitz work?', 'What is VAB?'], tags: ['viraladblitz', 'vab', 'text ads', 'overview'],
|
||||
re: /(what('s| is) (viral ?ad ?blitz|vab|this (site|place))|how does (viral ?ad ?blitz|vab|this site|it) work|explain (viral ?ad ?blitz|this))/i,
|
||||
a: 'ViralAdBlitz is the network\'s home for text ads. Network members post one free text ad (a headline, two lines and a link). Your page at ' + URL_ + '/your-name shows your ad plus the ads of the five people above you in your sponsor line, so your ad also shows on the pages of the people you bring in, five levels down. A $' + B.usd + ' Boost adds ' + B.views + ' guaranteed views. See ' + URL_ + '/how' },
|
||||
{ id: 'sign-in', title: 'Signing in and who can post', q: ['How do I sign in?', 'Do I need an account?', 'Why can I not post my ad?'], tags: ['sign in', 'member', 'instantadpay', 'linkspin', 'wallet'],
|
||||
re: /(sign ?(in|up)|log ?in|register|\bjoin\b|account|(can.?t|cannot|can i not|unable to|not able to) post|not a member|network member)/i,
|
||||
a: 'Sign in on My page (' + URL_ + '/my) through your InstantAdPay or LinkSpin account, or with your wallet (a free signature that cannot move funds). Posting a text ad is free for network members. Not a member yet? Join InstantAdPay free at https://instantadpay.com/join, then sign in here through it.' },
|
||||
{ id: 'free-ad', title: 'Posting your free text ad', q: ['How do I post my ad?', 'How long can my headline be?', 'Can I edit my ad?', 'Is the text ad free?'], tags: ['free ad', 'post', 'edit', 'headline', 'link'],
|
||||
re: /(post|create|make|write|edit|change|update) (my |a |an |the )?(free )?(text )?ad\b|headline|how (long|many characters)|free (text )?ad|(text )?ad (is )?free|is (it|the (text )?ad|posting) free|link shortener/i,
|
||||
a: 'Sign in on My page (' + URL_ + '/my) and fill in your one free text ad: a headline of 3 to ' + C.ad.headline + ' characters, a first line of 3 to ' + C.ad.line + ', an optional second line up to ' + C.ad.line + ', and an https link to a real page that loads (no link shorteners). You can edit it any time. Text ads are free for network members: anyone with an InstantAdPay or LinkSpin account.' },
|
||||
{ id: 'promote', title: 'Promote ViralAdBlitz', q: ['Where are the banners?', 'How do I promote my page?', 'Is there a promo kit?'], tags: ['promote', 'kit', 'banners', 'creatives'],
|
||||
re: /(promo|promote|banners?|creatives?|kit|share (my )?page|referral link|invite link)/i,
|
||||
a: 'The promo kit at ' + URL_ + '/promote has your links, creatives in every common size and copy you can paste anywhere, all carrying your network username. Your own page is ' + URL_ + '/your-name, and visitors who join from it join free under you.' },
|
||||
{ id: 'spread', title: 'How your ad spreads five levels down', q: ['How does my ad spread?', 'What is on a member page?', 'What are the five levels?', 'Why is someone skipped on my page?'], tags: ['levels', 'member page', 'spread', 'team'],
|
||||
re: /(spread|five levels|5 levels|level ?[1-5]\b|member page|my page|whose ads|team ads|skipped|someone in between)/i,
|
||||
a: 'Each member page shows the owner\'s ad on top, then the ads of the first five people above them in their sponsor line who have a live ad (labelled LEVEL 1 to LEVEL 5), then two Boosted places, then a button to join free under them. So your ad shows on the pages of the people you bring in, five levels down. If someone in between has no live ad, the next person up takes their place (the site looks up to ' + C.lineSearch + ' places).' },
|
||||
{ id: 'withdraw', title: 'Withdrawals', q: ['How do I withdraw?', 'Where is my balance?', 'How do I cash out?'], tags: ['withdraw', 'balance', 'cash out'],
|
||||
re: /(withdraw|cash ?out|my balance|pending (pay|commission)|claim (my )?(pol|payment|share))/i,
|
||||
a: 'There is nothing to withdraw. Each share goes straight to the person\'s own wallet inside the buyer\'s transaction, so nothing is held. If a payment cannot be delivered to a wallet, it waits in the contract for that wallet to claim, and nobody else can take it. Every payout shows in the live ledger at ' + URL_ + '/ledger' },
|
||||
{ id: 'split', title: 'Where the $5 goes: the split', q: ['How do payouts work?', 'Where does my $5 go?', 'Who gets paid when I boost?', 'What is the commission?'], tags: ['split', 'payout', 'commission', 'levels', 'passed over'],
|
||||
re: /(split|payouts?|commission|who gets paid|where does (my|the) (money|\$ ?5) go|percent|pass(ed)? over|pass.?up|qualif|earn|get paid)/i,
|
||||
a: 'The ViralAdBlitz contract splits every Boost in the same transaction: ' + SP.levelPct + '% to each of ' + SP.levels + ' people up the buyer\'s sponsor line and ' + SP.companyPct + '% to the company. Only someone who has bought at least one Boost receives a share; anyone who has not is passed over and the share moves up to the next person who has. The contract looks up to ' + SP.maxDepth + ' places up the line, and a share nobody qualifies for goes to the company. Nothing is promised: you are paid only when people in your team choose to buy Boosts. ' + NOT_INCOME },
|
||||
{ id: 'boost', title: 'What a Boost is and what it costs', q: ['What is a Boost?', 'How much is a Boost?', 'What do I get for $5?', 'How many Boosts can I buy?'], tags: ['boost', 'price', '$5', '500 views', 'ticker'],
|
||||
re: /(boost|\$ ?5\b|five dollars|500 views|how much(?! pol)|price|cost|guaranteed views|ticker|starred)/i,
|
||||
a: 'A Boost is a one-time $' + B.usd + ' purchase for your text ad: ' + B.views + ' guaranteed network views, a gold star on the live ticker while they are delivered, and a place in the two Boosted spots on member pages. You can buy 1 to ' + B.maxQty + ' at a time; each adds its own ' + B.views + ' views. It is paid in POL on Polygon at the live price, never a subscription. Views not delivered on ViralAdBlitz within ' + C.deliverDays + ' days are finished through Network Ad Space as a text ad. ' + NOT_INCOME },
|
||||
{ id: 'views', title: 'What counts as a view', q: ['How are views counted?', 'Do my own views count?', 'Why did my view count not go up?'], tags: ['views', 'verified', 'counting', 'bots'],
|
||||
re: /(views? (count|counted)|count(s|ed)? as a view|verified (view|visit)|my own views?|reload|bots?\b|why .*views?)/i,
|
||||
a: 'A view counts only when a real browser keeps a ViralAdBlitz page open and visible for a few seconds, once per visitor per ad in 24 hours. The server decides which ads the page showed. Your own views never count, and bots, early sends and more than ' + C.perIpDay + ' browsers from one connection in a day are refused. Boosted ads follow the same rules.' },
|
||||
{ id: 'clicks', title: 'Verified clicks and Top ads this week', q: ['What is a verified click?', 'How do I get on Top ads this week?'], tags: ['clicks', 'top ads', 'board', 'leaderboard'],
|
||||
re: /(verified clicks?|clicks? count|top ads|this week|board|leaderboard|rank)/i,
|
||||
a: 'A click counts as verified once per visitor per ad per 24 hours, never your own. Top ads this week on the front page ranks ads by verified clicks. Raw clicks are counted too, apart from the verified ones.' },
|
||||
{ id: 'linkspin-track', title: 'Track with LinkSpin', q: ['What is Track with LinkSpin?', 'Where do I see my ad clicks?'], tags: ['linkspin', 'tracked link', 'clicks'],
|
||||
re: /(track(ed|ing)? (with |by |link)|linkspin (link|track|click)|track with linkspin|see my (ad )?clicks|my (ad )?clicks)/i,
|
||||
a: 'When you save your ad with "Track with LinkSpin" on (the default), your link goes out as a tracked link on your own LinkSpin account and My page shows its LinkSpin clicks. Visitors still land on your link. You can turn it off on the ad form; links with {clickid} or {placement} are not tracked.' },
|
||||
{ id: 'line', title: 'Your sponsor line', q: ['Who is my sponsor?', 'Can my sponsor line change?', 'Where does my line come from?'], tags: ['sponsor', 'line', 'hub', 'upline'],
|
||||
re: /(sponsor|upline|my line|change (my )?line|who invited|wrong sponsor)/i,
|
||||
a: 'Your sponsor line comes from the network hub: the same sponsor you have across InstantAdPay, LinkSpin and the other network sites. On your first Boost the site signs your line and the contract records it. After that it never changes, so every later Boost pays the same people. People in the line without a wallet in the network are left out of the recorded line.' },
|
||||
{ id: 'wallet', title: 'Which wallet and coin', q: ['Which wallet should I use?', 'What crypto do I pay with?', 'How much POL do I need?'], tags: ['wallet', 'pol', 'polygon', 'safepal', 'gas'],
|
||||
re: /(which wallet|what wallet|wallet|metamask|safepal|trust wallet|\bpol\b|polygon|matic|crypto|gas|fee)/i,
|
||||
a: 'Use SafePal or any other crypto wallet that works on Polygon. Boosts are priced in dollars and paid in POL, Polygon\'s coin, at the live price the contract reads when you buy (anything you send above the price comes back in the same transaction). Keep a little extra POL for the network fee. Never share your recovery phrase; nobody from the network will ask for it.' },
|
||||
{ id: 'safe', title: 'Is it safe? Is it a scheme?', q: ['Is this a pyramid scheme?', 'Is ViralAdBlitz legit?', 'Who holds the money?'], tags: ['safe', 'legit', 'pyramid', 'contract'],
|
||||
re: /(pyramid|ponzi|scam|scheme|legit|safe|trust|rug|who holds)/i,
|
||||
a: 'What you buy is advertising for your own text ad: guaranteed views, a ticker spot and member-page places. The split is fixed in the contract on Polygon: no owner withdraw, nothing held, every share paid in the buyer\'s own transaction. Check every Boost in the live ledger (' + URL_ + '/ledger) and the contract at ' + URL_ + '/contract. Nobody earns unless real Boosts are bought in their line. ' + NOT_INCOME },
|
||||
{ id: 'rules', title: 'Ad rules', q: ['What ads are not allowed?', 'Why was my ad removed?'], tags: ['rules', 'not allowed', 'removed'],
|
||||
re: /(not allowed|allowed|prohibited|rules|removed|banned|adult|malware)/i,
|
||||
a: 'Your ad and link must be yours or ones you have the right to use, and the link must lead to a lawful page that loads. No adult content, malware, phishing, deceptive offers, hate, or anything illegal where you or your visitors live, and no link shorteners. An ad that breaks the rules can be paused or removed. Full terms: ' + URL_ + '/terms' }
|
||||
];
|
||||
|
||||
const FAQ = [
|
||||
{ id: 'f-network', title: 'ViralAdBlitz and the other network sites', source: 'faq', tags: ['network', 'instantadpay', 'linkspin', 'one account'],
|
||||
questions: ['Is ViralAdBlitz part of InstantAdPay?', 'Do I need a new account?', 'Which network sites are there?'],
|
||||
answer: 'ViralAdBlitz is part of the network: one network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, DownlineHydra, 5xYourTeam, Stack POL and Earners Corner, with the same username and sponsor everywhere. Sign in here through InstantAdPay or LinkSpin.' },
|
||||
{ id: 'f-nas', title: 'Network Ad Space finishes a Boost', source: 'faq', tags: ['network ad space', 'nas', 'delivery', '30 days'],
|
||||
questions: ['What happens if my Boost is not delivered?', 'What is Network Ad Space?'],
|
||||
answer: 'If a Boost\'s ' + B.views + ' views are not all delivered on ViralAdBlitz within ' + C.deliverDays + ' days, the rest are delivered through Network Ad Space, a network ad site, as a text ad with your same headline, lines and link, for exactly the views still owed. Those views count toward the same guarantee.' },
|
||||
{ id: 'f-old-links', title: 'Old ViralAdBlitz links', source: 'faq', tags: ['old link', 'old account', 'splash page'],
|
||||
questions: ['Does my old ViralAdBlitz link still work?', 'Where is my old account?'],
|
||||
answer: 'Old ViralAdBlitz referral links now open the member\'s new page at ' + URL_ + '/their-network-username. Old accounts and balances were not carried over; members were matched to the network by email.' }
|
||||
];
|
||||
|
||||
const FACTS = () => [
|
||||
'- WHAT IT IS: ViralAdBlitz (' + URL_ + ') is the network\'s text-ad home. One free text ad per network member (an InstantAdPay or LinkSpin account, checked with the network hub). Sign in on ' + URL_ + '/my through InstantAdPay or LinkSpin (network sign-in) or with a wallet signature (free, cannot move funds).',
|
||||
'- THE AD: headline 3 to ' + C.ad.headline + ' characters, line 1 3 to ' + C.ad.line + ', line 2 optional up to ' + C.ad.line + ', an https link to a real public page that answers, no link shorteners. One ad per member, editable any time, a Boost follows the ad when it is edited. "Track with LinkSpin" (default on) sends the link through the member\'s own LinkSpin tracked link; My page shows those clicks; {clickid}/{placement} links are not tracked.',
|
||||
'- MEMBER PAGE ' + URL_ + '/<network username>: the owner\'s ad on top, then the ads of the first 5 people above them in the hub sponsor line who have a live ad (labelled LEVEL 1 to LEVEL 5 in the order shown; the site walks up to ' + C.lineSearch + ' places), then ' + C.boostSlots + ' Boosted places, then "Join free under @owner" (InstantAdPay\'s join page). Front page: a live ticker of the newest ads (Boosted ones starred), "Top ads this week" by verified clicks, today\'s numbers, the live ledger and contract proof.',
|
||||
'- VERIFIED VIEWS: a real browser keeps the page open and visible for ' + C.visitSeconds + ' seconds; the server decides which ads were shown; one view per visitor per ad per 24 hours; never the owner\'s own; bots, early sends and more than ' + C.perIpDay + ' browsers per connection per day are refused. Verified clicks: once per visitor per ad per 24 hours, never the owner\'s own; raw clicks are counted apart.',
|
||||
'- BOOST: one-time $' + B.usd + ' (never a subscription) = ' + B.views + ' guaranteed network views + a gold star on the ticker while delivering + the Boosted places on member pages (furthest-behind first). 1 to ' + B.maxQty + ' per purchase, each adds ' + B.views + ' views. A member must have a live text ad first. Paid in POL on Polygon at the live Chainlink POL/USD price the contract reads; any overpayment comes back in the same transaction. Not delivered on-site within ' + C.deliverDays + ' days: finished through Network Ad Space as a text ad for exactly the views owed. ' + NOT_INCOME,
|
||||
'- SPLIT (VABShop contract constants, no setter): ' + SP.levelPct + '% to each of ' + SP.levels + ' sponsor levels + ' + SP.companyPct + '% company, in the same transaction. Only Boost buyers (one Boost ever is enough) receive a level share; a non-buyer is passed over and the share goes up to the next buyer; the contract looks up to ' + SP.maxDepth + ' places; an unclaimed share goes to the company. No owner withdraw, no balance held; an undeliverable share waits in the contract for that wallet to claim.',
|
||||
'- SPONSOR LINE: from the network hub (same sponsor as InstantAdPay/LinkSpin). On the first Boost the keeper signs the line and the contract records it link by link; a recorded link never changes. People without a wallet in the network are left out.',
|
||||
'- TRUST: ' + URL_ + '/ledger (every Boost, every level paid, who was passed over, delivery), ' + URL_ + '/contract (live contract facts), toasts of real events, a Telegram card per Boost. Terms ' + URL_ + '/terms, Earnings Disclaimer ' + URL_ + '/disclaimer, Privacy ' + URL_ + '/privacy. Run by TrustClickz, 615 Green Valley Drive, Moody, AL 35004.',
|
||||
'- PROMO: ' + URL_ + '/promote (links, creatives in every common size, copy, all with the member\'s network username). Old ViralAdBlitz referral links open the member\'s new page; old balances were not carried.',
|
||||
'- NO REFUNDS: blockchain payments are final; views left on a removed ad\'s Boosts are not delivered or refunded. SUPPORT for account or purchase problems: network support at ' + SUPPORT + ' (InstantAdPay runs the one desk for every network site).'
|
||||
].join('\n');
|
||||
|
||||
const SITE = {
|
||||
id: 'viraladblitz', hubSite: 'viraladblitz', netId: 'viraladblitz', name: 'ViralAdBlitz', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE,
|
||||
dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS,
|
||||
intro: 'You are the assistant on ViralAdBlitz (' + URL_ + '), the network\'s text-ad site: one free text ad per network member that spreads five levels down their team, and a $' + B.usd + ' Boost for ' + B.views + ' guaranteed views. It is part of a network of sites that share one account.',
|
||||
quickTopics: ['How does my ad spread?', 'What is a Boost?', 'Where does the $5 go?', 'What is DownlineHydra?']
|
||||
};
|
||||
|
||||
function init() { return core.init(SITE); }
|
||||
module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE };
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
// The site assistant's engine (Marty 2026-11-15: a chatbot on every rebuilt network site), ported from LinkSpin's chatbot.js.
|
||||
// The site's own chatbot.js holds what it knows (CANNED instant answers + FACTS, written from that site's code); this file
|
||||
// holds how it answers, the same on every site:
|
||||
// 1. the knowledge base's instant answers (kb.js, seeded from CANNED; first matching pattern wins, no AI call)
|
||||
// 2. retrieval over the merged NETWORK knowledge base (this site's entries boosted, netkb.js), into the system prompt
|
||||
// 3. OpenRouter (deepseek/deepseek-v4-flash:nitro, reasoning OFF, retried once), house rules in the prompt and on the way out
|
||||
// Account problems go to the network support desk on InstantAdPay (handoff: true makes the widget offer it).
|
||||
// Routes: POST /api/chat, GET /api/chat/kb-stamp, admin GET/POST /api/admin/kb, GET/PUT/DELETE /api/admin/kb/<id>,
|
||||
// POST /api/admin/kb/test, GET /api/admin/kb/network (x-admin-token, the site's own isAdmin).
|
||||
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
const kb = require('./kb');
|
||||
const netkb = require('./netkb');
|
||||
|
||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||
let S = null; // the site: { id, hubSite, name, url, dataDir, canned, faq, facts(), about, supportUrl, linkFor, quickTopics }
|
||||
|
||||
function key() {
|
||||
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
|
||||
if (!S || !S.dataDir) return '';
|
||||
try { return fs.readFileSync(path.join(S.dataDir, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
|
||||
}
|
||||
const enabled = () => !!key();
|
||||
|
||||
// CANNED + FAQ in the shape kb.js stores (order keeps the first-match-wins sequence)
|
||||
function seeds() {
|
||||
return S.canned.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re ? c.re.source : '',
|
||||
handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(S.faq || []);
|
||||
}
|
||||
|
||||
const supportUrl = () => S.supportUrl || 'https://instantadpay.com/support';
|
||||
// asking for a person, or one person's own account problem: every site's first CANNED entry uses this (handoff: true)
|
||||
const SUPPORT_RE = /((contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|someone|a (human|person|real person))|real person|\bhuman\b|customer (service|support)|open a ticket|support (ticket|desk|team|email)|help ?desk|(my|the) (boost|purchase|payment|payout|order|account|sign.?in|log.?in|pro|upgrade|ad|banner|pick)s? (is |was |has |did |does )?(not|never|n.?t|missing|stuck|wrong|failed|broken|lost|gone)|(did ?n.?t|did not|never|has ?n.?t|have ?n.?t) (show|arriv|appear|receiv|get paid|go through|work|confirm)|i (was|got) (charged|scammed)|charged twice)/i;
|
||||
const HOUSE_RULES = () => `RULES:
|
||||
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page.
|
||||
- Your main job is ${S.name}. Questions about another network site: answer from that site's knowledge-base entry, say which site it is about, and give that site's link exactly as the entry gives it. Never mix two sites' prices, splits or rules.
|
||||
- NEVER promise or estimate income, and never state a maximum or total anyone can earn. This is advertising with a referral program, never an investment. Nobody earns unless real purchases happen in their line. Crypto payments are final.
|
||||
- Whenever ad credits come up, say: Ad credits buy advertising, not income.
|
||||
- Wallets: say "SafePal or any other crypto wallet". Never recommend MetaMask.
|
||||
- Never mention RM Circle. It is not part of this network.
|
||||
- No em dashes. If you do not know, say so plainly; never guess a price, a percentage or a rule.
|
||||
- Anything about one person's own account (a missing payout, a sign-in that will not work, a purchase that did not show, a bug) you cannot look up: say so and send them to network support at ${supportUrl()}.`;
|
||||
|
||||
function networkLine() {
|
||||
const list = netkb.sites();
|
||||
if (!list.length) return '';
|
||||
return '\nNETWORK SITES (one network account works across them; link to use for each):\n' + list.map(s => '- ' + s.name + ': ' + s.go).join('\n') + '\n';
|
||||
}
|
||||
function systemPrompt(kbBlock) {
|
||||
return S.intro + '\n\nFACTS (checked against this site\'s code on ' + S.knowledgeDate + '):\n' + S.facts() + '\n' + networkLine() + '\n' + HOUSE_RULES() + (kbBlock ? '\n\n' + kbBlock : '');
|
||||
}
|
||||
|
||||
function endpoint() {
|
||||
try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); }
|
||||
}
|
||||
function askOnce(message, historyText, kbBlock) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify({
|
||||
model: MODEL,
|
||||
reasoning: { enabled: false }, // deepseek-v4-flash reasons by default and can spend the whole max_tokens on it (2026-10-16)
|
||||
max_tokens: 320,
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt(kbBlock) },
|
||||
...(historyText ? [{ role: 'user', content: 'Earlier context: ' + String(historyText).slice(0, 800) }] : []),
|
||||
{ role: 'user', content: String(message).slice(0, 600) }
|
||||
]
|
||||
});
|
||||
const ep = endpoint();
|
||||
const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST',
|
||||
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body),
|
||||
'HTTP-Referer': S.url, 'X-Title': S.name + ' assistant' }, timeout: 30000 },
|
||||
res => {
|
||||
let d = '';
|
||||
res.on('data', c => { d += c; });
|
||||
res.on('end', () => {
|
||||
// OpenRouter can pad a slow upstream with keepalive lines before the JSON (IAP, 2026-09-17): find the object
|
||||
const i = d.indexOf('{'); let txt = '';
|
||||
try { txt = String(JSON.parse(i < 0 ? d : d.slice(i)).choices[0].message.content || '').trim(); }
|
||||
catch (e) { return reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(0, 150))); }
|
||||
if (!txt) return reject(new Error('openrouter ' + res.statusCode + ': empty content'));
|
||||
resolve(txt);
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.on('timeout', () => req.destroy(new Error('openrouter timeout')));
|
||||
req.end(body);
|
||||
});
|
||||
}
|
||||
async function askAI(message, historyText, kbBlock) {
|
||||
try { return await askOnce(message, historyText, kbBlock); }
|
||||
catch (e) { await new Promise(r => setTimeout(r, 700)); return askOnce(message, historyText, kbBlock); } // one provider dropping it is the usual cause
|
||||
}
|
||||
|
||||
// house rules on the way out, whatever the model wrote
|
||||
const RMC_RE = /\brm ?circle\b|rmcircle/i;
|
||||
function scrub(t) {
|
||||
let s = String(t || '').replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ');
|
||||
s = s.replace(/\*\*(.+?)\*\*/g, '$1').replace(/^#+\s*/gm, '');
|
||||
s = s.replace(/\bMeta ?Mask\b(\s*(,|or|and)\s*)?/gi, '').replace(/\s{2,}/g, ' ').trim();
|
||||
return s;
|
||||
}
|
||||
const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) ?not (see|check|look)|contact support|network support|support desk|\/support\b)/i;
|
||||
|
||||
async function answer(message, historyText) {
|
||||
const r = await answerRaw(message, historyText);
|
||||
if (r && typeof r.reply === 'string') {
|
||||
r.reply = scrub(r.reply);
|
||||
if (RMC_RE.test(r.reply)) r.reply = 'I can only help with ' + S.name + ' and the network sites. For anything else, network support at ' + supportUrl() + ' can point you the right way.';
|
||||
}
|
||||
return r;
|
||||
}
|
||||
async function answerRaw(message, historyText) {
|
||||
const msg = String(message || '').trim().slice(0, 600);
|
||||
if (!msg) return { error: 'Say something first.' };
|
||||
let hit = null, kbOk = true;
|
||||
try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
||||
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
|
||||
if (!kbOk) for (const c of S.canned) if (c.re && c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||
let kbBlock = '', kbIds = [], hits = [];
|
||||
try {
|
||||
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
|
||||
hits = await kb.context(query, 6);
|
||||
kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id);
|
||||
} catch (e) { console.error('kb search', e.message); }
|
||||
if (!enabled()) {
|
||||
// no AI: the best matching entry, if it is a clear match, else the honest fallback
|
||||
if (hits.length) { const e = hits[0].entry; return { reply: e.answer + (e.site ? ' More at ' + e.go : ''), kb: [e.id] }; }
|
||||
return { reply: S.fallback || ('Good question. The quick answers I have cover how ' + S.name + ' works, what it costs and how payouts work. For anything else, network support at ' + supportUrl() + ' will help.'), handoff: true };
|
||||
}
|
||||
try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); }
|
||||
catch (e) {
|
||||
console.error('chat AI failed', e.message);
|
||||
if (hits.length) { const x = hits[0].entry; return { reply: x.answer + (x.site ? ' More at ' + x.go : ''), kb: [x.id] }; }
|
||||
return { reply: 'I hit a snag answering that one, on our side. The live ledger at ' + S.url + '/ledger and the contract page at ' + S.url + '/contract cover most deep questions, or network support at ' + supportUrl() + ' will answer.', handoff: true };
|
||||
}
|
||||
}
|
||||
|
||||
// ---- rate limit: per visitor, in memory ----
|
||||
const hits = new Map();
|
||||
function limited(ip) {
|
||||
const now = Date.now(); const h = hits.get(ip) || { m: 0, mAt: now, d: 0, dAt: now };
|
||||
if (now - h.mAt > 60000) { h.m = 0; h.mAt = now; }
|
||||
if (now - h.dAt > 86400000) { h.d = 0; h.dAt = now; }
|
||||
h.m++; h.d++; hits.set(ip, h);
|
||||
if (hits.size > 20000) hits.clear();
|
||||
return h.m > 12 || h.d > 300;
|
||||
}
|
||||
const ipOf = req => String(req.headers['cf-connecting-ip'] || String(req.headers['x-forwarded-for'] || '').split(',')[0] || (req.socket && req.socket.remoteAddress) || 'x').trim();
|
||||
|
||||
// h: { json(res, code, obj, extra), readBody(req), isAdmin(req) }; returns true when it answered
|
||||
async function handle(req, res, p, u, h) {
|
||||
if (p === '/api/chat' && req.method === 'POST') {
|
||||
if (limited(ipOf(req))) { h.json(res, 429, { error: 'Give it a minute, then ask again.' }); return true; }
|
||||
const b = await h.readBody(req);
|
||||
const hist = Array.isArray(b.history) ? b.history.map(x => String(x || '')).join(' ').slice(-800) : String(b.history || '').slice(-800);
|
||||
const r = await answer(b.message, hist);
|
||||
if (r.handoff) r.support = supportLink(b.message);
|
||||
h.json(res, r.error ? 400 : 200, r); return true;
|
||||
}
|
||||
if (p === '/api/chat/config' && req.method === 'GET') { h.json(res, 200, { name: S.name, support: supportUrl(), topics: S.quickTopics || [] }, { 'Cache-Control': 'public, max-age=300' }); return true; }
|
||||
if (p === '/api/chat/kb-stamp' && req.method === 'GET') { h.json(res, 200, Object.assign(await kb.stamp(), { knowledgeDate: S.knowledgeDate }), { 'Cache-Control': 'no-store' }); return true; }
|
||||
if (!p.startsWith('/api/admin/kb')) return false;
|
||||
if (!h.isAdmin(req)) { h.json(res, 401, { error: 'no' }); return true; }
|
||||
if (p === '/api/admin/kb') {
|
||||
if (req.method === 'GET') { h.json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }); return true; }
|
||||
if (req.method === 'POST') { const r = await kb.create(await h.readBody(req)); h.json(res, r.error ? 400 : 200, r); return true; }
|
||||
}
|
||||
if (p === '/api/admin/kb/test' && req.method === 'POST') { const b = await h.readBody(req); h.json(res, 200, Object.assign(await kb.test(b.question), b.answer ? { answer: await answer(b.question) } : {})); return true; }
|
||||
if (p === '/api/admin/kb/network' && req.method === 'GET') {
|
||||
if (u.searchParams.get('refresh') === '1') await netkb.refresh();
|
||||
if (u.searchParams.get('publish') === '1') await netkb.publish();
|
||||
h.json(res, 200, Object.assign(netkb.view(), { ai: enabled(), model: MODEL })); return true;
|
||||
}
|
||||
const m = /^\/api\/admin\/kb\/([A-Za-z0-9._:-]{1,80})$/.exec(p);
|
||||
if (m) {
|
||||
if (req.method === 'GET') { const e = await kb.get(m[1]); h.json(res, e ? 200 : 404, e ? { entry: e } : { error: 'Entry not found.' }); return true; }
|
||||
if (req.method === 'PUT') { const r = await kb.update(m[1], await h.readBody(req)); h.json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); return true; }
|
||||
if (req.method === 'DELETE') { const r = await kb.remove(m[1]); h.json(res, r.error ? 404 : 200, r); return true; }
|
||||
}
|
||||
h.json(res, 404, { error: 'Not found' }); return true;
|
||||
}
|
||||
// the support desk link the widget offers: InstantAdPay's public form, told which site and question it came from
|
||||
function supportLink(q) {
|
||||
const qs = new URLSearchParams({ from: S.id, subject: (S.name + ': ' + String(q || '').replace(/\s+/g, ' ').trim()).slice(0, 120) });
|
||||
return supportUrl() + '?' + qs.toString();
|
||||
}
|
||||
|
||||
// the link to another network site: its LinkSpin tracked link with ?src=<this site> (netsites.js), else its plain address
|
||||
const hostOf = x => { try { return new URL(x).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||
function linkVia(netId) {
|
||||
return url => {
|
||||
try {
|
||||
const ns = require('./netsites'); const h = hostOf(url);
|
||||
const m = ns.list().concat(ns.FALLBACK || []).find(s => hostOf(s.url) === h);
|
||||
return (m && netId && m.id !== netId && ns.tracked(m.id, netId)) || url;
|
||||
} catch (e) { return url; }
|
||||
};
|
||||
}
|
||||
|
||||
// site: see S above. Call after docstore.init (kb.json is a MySQL document there).
|
||||
function init(site) {
|
||||
S = site; if (!S.linkFor) S.linkFor = linkVia(S.netId);
|
||||
const ready = kb.init({ dataDir: site.dataDir, seeds: seeds(), siteUrl: site.url, helpText: 'network support at ' + supportUrl() });
|
||||
netkb.init({ dataDir: site.dataDir, site: site.hubSite, name: site.name, url: site.url, entries: () => kb.own(), linkFor: site.linkFor });
|
||||
return ready;
|
||||
}
|
||||
|
||||
module.exports = { init, handle, answer, enabled, seeds, systemPrompt, scrub, supportLink, linkVia, SUPPORT_RE, _limited: limited };
|
||||
@@ -0,0 +1,274 @@
|
||||
// Knowledge base behind the site assistant (Marty's support-desk plan, 2026-10-20).
|
||||
// The chatbot answers from maintained entries, and good support replies become entries.
|
||||
//
|
||||
// An entry: { id, title, questions[], answer, tags[], pattern, handoff, order, source, ticketRef,
|
||||
// updated, created, edited, deleted, seedHash }
|
||||
// pattern optional regex (case-insensitive). Entries with one are the instant CANNED fast path:
|
||||
// the first pattern that matches (lowest order) is the reply, no AI call. The CANNED list
|
||||
// in chatbot.js seeds these, so there is ONE source: edit the answer here and the fast
|
||||
// path serves the new text.
|
||||
// source canned | faq | ticket | admin
|
||||
//
|
||||
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
|
||||
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
|
||||
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
|
||||
//
|
||||
// Seeds stay in step with the code: an entry that came from a seed and was never edited in the admin
|
||||
// pane is refreshed when the seed text changes; an edited one is left alone; a deleted seed stays
|
||||
// deleted (tombstone row), and a seed dropped from the code is retired unless an admin edited it.
|
||||
//
|
||||
// Store: DATA_DIR/kb.json (written to a temp file and renamed), which docstore.js keeps in MySQL when DOCSTORE_URL is set
|
||||
// (Marty's database rule). Ported from LinkSpin's kb.js (2026-11-15); keep the scoring and seed rules in step.
|
||||
//
|
||||
// NETWORK (2026-11-15, netkb.js): the other network sites' entries, read from the hub, sit in the same index. This site's
|
||||
// own entries are boosted first (HOME_BOOST); a question that names another site boosts that site's entries instead
|
||||
// (NAMED_BOOST). Other sites' entries never take the instant-answer fast path: they only ride along as context, labelled
|
||||
// with the site and the link to send people to. This site's own entries are published to the hub (netkb.publish).
|
||||
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
let netkb = null; try { netkb = require('./netkb'); } catch (e) {}
|
||||
|
||||
let DATA_DIR = null, SEEDS = [], ready = null, SITE_URL = '', HELP_TEXT = '', MEMORY = false;
|
||||
let cache = null, cacheAt = 0, index = null;
|
||||
const TTL = 30000; // two app copies share the volume for about 30 s during a deploy: re-read now and then
|
||||
|
||||
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
|
||||
const STOP = new Set(('a an and are as at be been being but by can could do does did doing for from has have having how i if in into is it its '
|
||||
+ 'me my of on or our ours so than that the their them then there these they this those to too us was we were what when where which who whom why '
|
||||
+ 'will with would you your yours im ive id am just also any about please hi hello hey thanks thank ok okay really very much some there here '
|
||||
+ 'should shall may might must anyone someone something thing things want wanted like know tell').split(' '));
|
||||
const SYN = { paid: 'pay', payment: 'pay', payments: 'pay', paying: 'pay', withdrawal: 'withdraw', withdrawals: 'withdraw', cashout: 'withdraw',
|
||||
signup: 'join', register: 'join', registration: 'join', joining: 'join', joined: 'join', login: 'log', logged: 'log', logout: 'log', signin: 'log',
|
||||
wallets: 'wallet', email: 'email', mail: 'email', pol: 'pol', matic: 'pol', prices: 'price', pricing: 'price', cost: 'price', costs: 'price',
|
||||
ads: 'ad', advert: 'ad', adverts: 'ad', advertising: 'ad', referrals: 'referral', refer: 'referral', referring: 'referral', referred: 'referral' };
|
||||
function stem(w) {
|
||||
if (SYN[w]) return SYN[w];
|
||||
if (w.length > 6 && w.endsWith('able')) return w.slice(0, -4);
|
||||
if (w.length > 5 && w.endsWith('ing')) return w.slice(0, -3);
|
||||
if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
|
||||
if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) return w.slice(0, -2);
|
||||
if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1);
|
||||
return w;
|
||||
}
|
||||
function words(text) {
|
||||
return String(text || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9$]+/g, ' ').split(' ')
|
||||
.filter(w => w && !STOP.has(w) && (w.length > 1 || /\d/.test(w))).map(stem);
|
||||
}
|
||||
// unigrams + bigrams of the content words: "coinbase account" scores as a phrase, not two loose words
|
||||
function terms(text) {
|
||||
const w = words(text), out = w.slice();
|
||||
for (let i = 0; i + 1 < w.length; i++) out.push(w[i] + '_' + w[i + 1]);
|
||||
return out;
|
||||
}
|
||||
const FIELDS = { title: 2.0, questions: 2.5, tags: 2.0, answer: 0.35 };
|
||||
const K1 = 1.2, B = 0.75;
|
||||
function fieldText(e, f) {
|
||||
if (f === 'questions') return (e.questions || []).join(' . ');
|
||||
if (f === 'tags') return (e.tags || []).join(' . ');
|
||||
return e[f] || '';
|
||||
}
|
||||
function buildIndex(entries) {
|
||||
const docs = entries.map(e => {
|
||||
const d = { e, f: {} };
|
||||
for (const f of Object.keys(FIELDS)) {
|
||||
const t = terms(fieldText(e, f)), tf = new Map();
|
||||
for (const x of t) tf.set(x, (tf.get(x) || 0) + 1);
|
||||
d.f[f] = { tf, len: t.length };
|
||||
}
|
||||
return d;
|
||||
});
|
||||
const df = new Map(), avg = {};
|
||||
for (const f of Object.keys(FIELDS)) avg[f] = docs.reduce((s, d) => s + d.f[f].len, 0) / Math.max(1, docs.length) || 1;
|
||||
for (const d of docs) {
|
||||
const seen = new Set();
|
||||
for (const f of Object.keys(FIELDS)) for (const t of d.f[f].tf.keys()) seen.add(t);
|
||||
for (const t of seen) df.set(t, (df.get(t) || 0) + 1);
|
||||
}
|
||||
return { docs, df, avg, n: docs.length };
|
||||
}
|
||||
const HOME_BOOST = 2, NAMED_BOOST = 3;
|
||||
// which network sites a question names, by the site name or a short alias ("dlb", "vbb", "iap", ...)
|
||||
const ALIASES = { iap: ['iap', 'instant ad pay'], linkspin: ['link spin'], bannerline: ['dlb', 'downline banner', 'downline banners'], vbb: ['vbb', 'viral banner'],
|
||||
viraladblitz: ['vab', 'viral ad blitz'], downlinehydra: ['hydra', 'dh'], fivex: ['5x', '5x your team', 'five x', 'the draft'], stackpol: ['stack pol', 'stackpol'] };
|
||||
const norm = s => ' ' + String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim() + ' ';
|
||||
function namedSites(query, idx) {
|
||||
const q = norm(query); const out = new Set();
|
||||
for (const s of (idx && idx.sites) || []) {
|
||||
const names = [s.name, s.site].concat(ALIASES[s.site] || []).map(norm);
|
||||
if (names.some(n => n.trim() && q.includes(n))) out.add(s.site);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function rank(idx, query, k) {
|
||||
if (!idx || !idx.n) return [];
|
||||
const qt = [...new Set(terms(query))];
|
||||
if (!qt.length) return [];
|
||||
const named = namedSites(query, idx);
|
||||
const out = [];
|
||||
for (const d of idx.docs) {
|
||||
let s = 0;
|
||||
for (const t of qt) {
|
||||
const n = idx.df.get(t); if (!n) continue;
|
||||
const idf = Math.log(1 + (idx.n - n + 0.5) / (n + 0.5)) * (t.includes('_') ? 1.5 : 1);
|
||||
for (const f of Object.keys(FIELDS)) {
|
||||
const tf = d.f[f].tf.get(t); if (!tf) continue;
|
||||
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
|
||||
}
|
||||
}
|
||||
if (s > 0 && d.e.site) s *= named.has(d.e.site) ? NAMED_BOOST : 1;
|
||||
else if (s > 0) s *= named.size ? 1 : HOME_BOOST;
|
||||
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
|
||||
}
|
||||
out.sort((a, b) => b.score - a.score);
|
||||
return out.slice(0, k || 5);
|
||||
}
|
||||
// keep hits that are close to the best one, and only when the best is a real match
|
||||
const MIN_SCORE = 3;
|
||||
function relevant(hits) {
|
||||
if (!hits.length || hits[0].score < MIN_SCORE) return [];
|
||||
const floor = Math.max(MIN_SCORE, hits[0].score * 0.3);
|
||||
return hits.filter(h => h.score >= floor);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- store
|
||||
const mem = { entries: [] }; // a site with no data volume (Stack POL): seeds in memory only
|
||||
const J = {
|
||||
file: () => path.join(DATA_DIR, 'kb.json'),
|
||||
async ensure() {},
|
||||
async all() { if (MEMORY) return mem.entries.slice(); try { const d = JSON.parse(fs.readFileSync(J.file(), 'utf8')); return Array.isArray(d.entries) ? d.entries : []; } catch (e) { return []; } },
|
||||
async put(e) {
|
||||
const all = await J.all(), i = all.findIndex(x => x.id === e.id);
|
||||
if (i >= 0) all[i] = e; else all.push(e);
|
||||
if (MEMORY) { mem.entries = all; return; }
|
||||
const tmp = J.file() + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify({ entries: all }));
|
||||
fs.renameSync(tmp, J.file());
|
||||
}
|
||||
};
|
||||
const store = () => J;
|
||||
|
||||
// ---------------------------------------------------------------- seeds
|
||||
const SEED_FIELDS = ['title', 'questions', 'answer', 'tags', 'pattern', 'handoff', 'order', 'source'];
|
||||
const seedHash = s => crypto.createHash('sha1').update(JSON.stringify(SEED_FIELDS.map(f => s[f] == null ? null : s[f]))).digest('hex');
|
||||
function seedEntry(s) {
|
||||
return { id: s.id, title: s.title, questions: s.questions || [], answer: s.answer, tags: s.tags || [], pattern: s.pattern || '', handoff: !!s.handoff,
|
||||
order: s.order == null ? null : s.order, source: s.source || 'faq' };
|
||||
}
|
||||
async function syncSeeds() {
|
||||
const all = await store().all(), byId = new Map(all.map(e => [e.id, e])), now = Date.now();
|
||||
const seedIds = new Set(SEEDS.map(s => s.id));
|
||||
let added = 0, refreshed = 0, retired = 0;
|
||||
for (const s of SEEDS) {
|
||||
const h = seedHash(seedEntry(s)), cur = byId.get(s.id);
|
||||
if (!cur) { await store().put(Object.assign(seedEntry(s), { ticketRef: '', seedHash: h, edited: false, deleted: false, created: now, updated: now })); added++; }
|
||||
else if (!cur.deleted && !cur.edited && cur.seedHash !== h) { await store().put(Object.assign({}, cur, seedEntry(s), { seedHash: h, updated: now })); refreshed++; }
|
||||
}
|
||||
// a seed taken out of the code goes with it, unless an admin has made the entry their own (guard: a broken seed list retires nothing)
|
||||
if (SEEDS.length >= 10) for (const e of all) if (e.seedHash && !e.edited && !e.deleted && !seedIds.has(e.id)) { await store().put(Object.assign({}, e, { deleted: true, updated: now })); retired++; }
|
||||
if (added || refreshed || retired) console.log('kb: seeds synced, ' + added + ' added, ' + refreshed + ' refreshed, ' + retired + ' retired');
|
||||
}
|
||||
|
||||
// opts: { dataDir (null = memory only), seeds, siteUrl, helpText (where a member gets a person) }
|
||||
function init(opts) {
|
||||
DATA_DIR = opts.dataDir || null; MEMORY = !DATA_DIR; SEEDS = opts.seeds || []; cache = null; index = null; mem.entries = [];
|
||||
SITE_URL = String(opts.siteUrl || '').replace(/\/+$/, ''); HELP_TEXT = opts.helpText || 'network support at https://instantadpay.com/support';
|
||||
ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); });
|
||||
return ready;
|
||||
}
|
||||
// this site's own entries, for netkb.publish
|
||||
async function own() { await load(); return cache.slice(); }
|
||||
async function load(force) {
|
||||
if (ready) await ready;
|
||||
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
|
||||
const all = await store().all();
|
||||
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); rx.clear();
|
||||
index = buildIndex(cache.concat(netkb ? netkb.remote() : [])); index.sites = netkb ? netkb.sites() : [];
|
||||
return cache;
|
||||
}
|
||||
const rx = new Map();
|
||||
function compiled(src) {
|
||||
if (!rx.has(src)) { let r = null; try { r = new RegExp(src, 'i'); } catch (e) {} rx.set(src, r); }
|
||||
return rx.get(src);
|
||||
}
|
||||
const byOrder = (a, b) => (a.order == null ? 1e9 : a.order) - (b.order == null ? 1e9 : b.order) || a.updated - b.updated;
|
||||
|
||||
// ---------------------------------------------------------------- the chatbot side
|
||||
async function fastPath(msg) {
|
||||
const list = (await load()).filter(e => e.pattern).sort(byOrder);
|
||||
for (const e of list) { const r = compiled(e.pattern); if (r && r.test(msg)) return e; }
|
||||
return null;
|
||||
}
|
||||
async function search(query, k) { await load(); return rank(index, query, k || 5); }
|
||||
async function context(query, k) { return relevant(await search(query, k || 6)); }
|
||||
const label = e => e.site ? ' (about ' + e.siteName + ', another network site; send people to ' + e.go + ')' : '';
|
||||
function promptBlock(hits) {
|
||||
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP_TEXT + '.';
|
||||
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
|
||||
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
|
||||
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
|
||||
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + label(h.entry) + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the admin side
|
||||
const clean = s => String(s == null ? '' : s).replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ').replace(/\r\n/g, '\n').trim(); // house rule: no em dashes in member-facing text
|
||||
function validate(o, cur) {
|
||||
o = o || {};
|
||||
const questions = (Array.isArray(o.questions) ? o.questions : String(o.questions || '').split('\n')).map(clean).filter(Boolean).map(q => q.slice(0, 300)).slice(0, 15);
|
||||
const tags = (Array.isArray(o.tags) ? o.tags : String(o.tags || '').split(',')).map(t => clean(t).toLowerCase().slice(0, 40)).filter(Boolean).slice(0, 15);
|
||||
const answer = clean(o.answer).slice(0, 4000);
|
||||
const title = (clean(o.title) || questions[0] || '').slice(0, 200);
|
||||
const pattern = String(o.pattern == null ? (cur ? cur.pattern : '') : o.pattern).trim().slice(0, 2000);
|
||||
if (!title) return { error: 'Give the entry a title or at least one question.' };
|
||||
if (!answer) return { error: 'The answer is empty.' };
|
||||
if (pattern) { try { new RegExp(pattern, 'i'); } catch (e) { return { error: 'The instant-answer pattern is not a valid regular expression: ' + e.message }; } }
|
||||
const order = o.order === '' || o.order == null ? (cur ? cur.order : null) : Number(o.order);
|
||||
return { title, questions, tags, answer, pattern, handoff: o.handoff == null ? !!(cur && cur.handoff) : !!o.handoff, order: Number.isFinite(order) ? Math.round(order) : null };
|
||||
}
|
||||
async function list(q) {
|
||||
const all = (await load(true)).slice();
|
||||
if (!q) return all.sort((a, b) => b.updated - a.updated);
|
||||
const ranked = rank(index, q, 50).filter(h => !h.entry.site).map(h => Object.assign({ score: h.score }, h.entry));
|
||||
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
|
||||
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
|
||||
return ranked.concat(plain);
|
||||
}
|
||||
async function get(id) { return (await load(true)).find(e => e.id === String(id)) || null; }
|
||||
async function create(o) {
|
||||
const v = validate(o); if (v.error) return v;
|
||||
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
|
||||
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
|
||||
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
|
||||
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
|
||||
return { ok: true, entry: e };
|
||||
}
|
||||
async function update(id, o) {
|
||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||
const v = validate(o, cur); if (v.error) return v;
|
||||
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
|
||||
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
|
||||
return { ok: true, entry: e };
|
||||
}
|
||||
async function remove(id) {
|
||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true); if (netkb) netkb.publishSoon();
|
||||
return { ok: true };
|
||||
}
|
||||
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
|
||||
// guard compares it with release-note dates. Seed refreshes do not count: those follow chatbot.js, whose
|
||||
// KNOWLEDGE_DATE already speaks for the code.
|
||||
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
async function stamp() {
|
||||
const all = await load();
|
||||
const max = all.reduce((m, e) => e.edited ? Math.max(m, e.updated || 0) : m, 0);
|
||||
return { updated: max ? ctDay(max) : '', count: all.length };
|
||||
}
|
||||
async function test(question) {
|
||||
const fast = await fastPath(String(question || ''));
|
||||
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
|
||||
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, site: h.entry.site || '', title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
|
||||
}
|
||||
|
||||
module.exports = { init, load, own, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
|
||||
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, namedSites, MIN_SCORE, HOME_BOOST, NAMED_BOOST } };
|
||||
@@ -0,0 +1,105 @@
|
||||
// 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 "<site>:<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
|
||||
|
||||
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, _set };
|
||||
@@ -36,6 +36,7 @@
|
||||
<div id="status" class="note" hidden></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/admin.js?v=6"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/* Site assistant widget, ViralAdBlitz look (vab.css): royal header, white clipped-corner panel, red send, gold chips.
|
||||
Variables fall back to the same values so the widget looks right even before vab.css has loaded. */
|
||||
#scChat{--sc-bg:var(--card,#fff);--sc-ink:var(--ink,#0A1F6B);--sc-sub:var(--sub,#3E4C7A);--sc-head:var(--royal,#0A1F6B);--sc-head-ink:#fff;
|
||||
--sc-accent:var(--red,#E3141E);--sc-accent-ink:#fff;--sc-me:var(--royal2,#12308F);--sc-me-ink:#fff;--sc-bot:var(--tint,#E1EBFF);--sc-line:var(--line,#C9D6F5);
|
||||
--sc-chip:var(--gtint,#FFF3CC);--sc-chip-ink:var(--gold-ink,#7A5B00);--sc-gold:var(--gold,#FFC21A);
|
||||
--sc-font:var(--body,Inter,system-ui,sans-serif);--sc-headfont:var(--head,'Chakra Petch',system-ui,sans-serif);--sc-cut:polygon(0 0,calc(100% - 14px) 0,100% 14px,100% 100%,14px 100%,0 calc(100% - 14px));
|
||||
position:fixed;right:18px;bottom:18px;z-index:80;font-family:var(--sc-font)}
|
||||
#scBtn{width:58px;height:58px;border:0;cursor:pointer;background:var(--sc-accent);color:var(--sc-accent-ink);display:flex;align-items:center;justify-content:center;
|
||||
clip-path:polygon(0 0,calc(100% - 12px) 0,100% 12px,100% 100%,12px 100%,0 calc(100% - 12px));box-shadow:0 6px 18px rgba(6,26,102,.35)}
|
||||
#scBtn:hover{background:#C70F18}
|
||||
#scBtn:focus-visible{outline:3px solid var(--sc-gold);outline-offset:3px}
|
||||
#scChat.open #scBtn{background:var(--sc-head)}
|
||||
#scPanel{position:absolute;right:0;bottom:72px;width:370px;max-width:calc(100vw - 32px);height:540px;max-height:calc(100vh - 110px);display:flex;flex-direction:column;
|
||||
background:var(--sc-bg);color:var(--sc-ink);clip-path:var(--sc-cut);border:1px solid var(--sc-line);box-shadow:0 18px 48px rgba(6,26,102,.3)}
|
||||
.sc-head{display:flex;align-items:flex-start;gap:10px;padding:14px 16px;background:var(--sc-head);color:var(--sc-head-ink);border-bottom:3px solid var(--sc-gold)}
|
||||
.sc-head>div{flex:1;min-width:0}
|
||||
.sc-title{display:block;font-family:var(--sc-headfont);font-size:18px;letter-spacing:.02em}
|
||||
.sc-sub{display:block;font-size:12.5px;opacity:.8}
|
||||
#scClose{background:transparent;border:0;color:inherit;font-size:26px;line-height:1;cursor:pointer;padding:0 2px}
|
||||
.sc-msgs{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:9px}
|
||||
.sc-m{max-width:88%;padding:9px 12px;font-size:14.5px;line-height:1.45;word-wrap:break-word;overflow-wrap:anywhere}
|
||||
.sc-m.bot{align-self:flex-start;background:var(--sc-bot);color:var(--sc-ink);clip-path:polygon(0 0,100% 0,100% 100%,8px 100%,0 calc(100% - 8px))}
|
||||
.sc-m.me{align-self:flex-end;background:var(--sc-me);color:var(--sc-me-ink);clip-path:polygon(0 0,calc(100% - 8px) 0,100% 8px,100% 100%,0 100%)}
|
||||
.sc-m a{color:inherit;text-decoration:underline}
|
||||
.sc-m.wait{opacity:.6}
|
||||
.sc-cta{display:inline-block;background:var(--sc-accent);color:var(--sc-accent-ink)!important;text-decoration:none!important;font-weight:700;padding:8px 14px;
|
||||
clip-path:polygon(0 0,calc(100% - 8px) 0,100% 8px,100% 100%,8px 100%,0 calc(100% - 8px))}
|
||||
.sc-handoff{background:transparent!important;padding:0!important}
|
||||
.sc-topics{display:flex;flex-wrap:wrap;gap:6px;padding:0 14px 8px}
|
||||
.sc-topics button{background:var(--sc-chip);color:var(--sc-chip-ink);border:1px solid var(--sc-gold);font:600 12.5px var(--sc-font);padding:5px 10px;cursor:pointer}
|
||||
.sc-input{display:flex;gap:8px;padding:10px 12px;border-top:1px solid var(--sc-line)}
|
||||
.sc-input input{flex:1;min-width:0;border:1px solid var(--sc-line);padding:10px 12px;font:15px var(--sc-font);color:var(--sc-ink);background:#fff}
|
||||
.sc-input input:focus{outline:2px solid var(--blue,#1F66FF);outline-offset:-1px}
|
||||
.sc-input button{background:var(--sc-accent);color:var(--sc-accent-ink);border:0;font:700 14px var(--sc-font);padding:0 16px;cursor:pointer;
|
||||
clip-path:polygon(0 0,calc(100% - 8px) 0,100% 8px,100% 100%,8px 100%,0 calc(100% - 8px))}
|
||||
.sc-human{display:block;text-align:center;font-size:12.5px;color:var(--sc-sub);padding:0 0 10px}
|
||||
@media (max-width:600px){#scChat{right:12px;bottom:12px}#scBtn{width:52px;height:52px}#scPanel{bottom:64px;height:calc(100vh - 100px)}}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Site assistant widget (2026-11-15): a round button bottom right, a panel that asks /api/chat. The look is this site's own,
|
||||
// in /assets/chat.css (colors and fonts from the site's stylesheet). When an answer cannot help, or the visitor asks for a
|
||||
// person, it offers "Open network support": InstantAdPay's support desk, which already knows the question and the site.
|
||||
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
|
||||
(function () {
|
||||
if (window.__siteChat || /^\/admin/.test(location.pathname)) return;
|
||||
window.__siteChat = 1;
|
||||
var css = document.createElement('link'); css.rel = 'stylesheet'; css.href = '/assets/chat.css?v=20261115c'; document.head.appendChild(css);
|
||||
var NAME = 'this site', TOPICS = [];
|
||||
var root = document.createElement('div'); root.id = 'scChat';
|
||||
root.innerHTML = '<button id="scBtn" type="button" aria-label="Ask a question" aria-expanded="false">'
|
||||
+ '<svg viewBox="0 0 24 24" width="26" height="26" aria-hidden="true"><path fill="currentColor" d="M4 4h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-5 4v-4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zm3 6.5a1.5 1.5 0 1 0 0 .01zm5 0a1.5 1.5 0 1 0 0 .01zm5 0a1.5 1.5 0 1 0 0 .01z"/></svg></button>'
|
||||
+ '<section id="scPanel" role="dialog" aria-label="Questions" hidden>'
|
||||
+ '<header class="sc-head"><div><b class="sc-title" id="scTitle">Ask a question</b><span class="sc-sub">Straight answers about this site and the network</span></div>'
|
||||
+ '<button id="scClose" type="button" aria-label="Close">×</button></header>'
|
||||
+ '<div class="sc-msgs" id="scMsgs" aria-live="polite"></div>'
|
||||
+ '<div class="sc-topics" id="scTopics"></div>'
|
||||
+ '<form class="sc-input" id="scForm"><input id="scIn" autocomplete="off" maxlength="600" placeholder="Type your question" aria-label="Your question">'
|
||||
+ '<button type="submit" id="scSend">Send</button></form>'
|
||||
+ '<a class="sc-human" id="scHuman" href="https://instantadpay.com/support" target="_blank" rel="noopener">Need a person? Open network support</a>'
|
||||
+ '</section>';
|
||||
document.body.appendChild(root);
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
var msgs = $('scMsgs'), input = $('scIn'), panel = $('scPanel'), btn = $('scBtn');
|
||||
var history = [], greeted = false, support = 'https://instantadpay.com/support';
|
||||
fetch('/api/chat/config').then(function (r) { return r.json(); }).then(function (c) {
|
||||
if (c.name) { NAME = c.name; $('scTitle').textContent = 'Ask ' + c.name; }
|
||||
if (c.support) { support = c.support; $('scHuman').href = c.support; }
|
||||
TOPICS = c.topics || [];
|
||||
}).catch(function () {});
|
||||
|
||||
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
||||
function add(text, who) {
|
||||
var d = document.createElement('div'); d.className = 'sc-m ' + who;
|
||||
d.innerHTML = esc(text).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)])/g, '<a href="$1" target="_blank" rel="noopener">$1</a>');
|
||||
msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight; return d;
|
||||
}
|
||||
function offer(link) {
|
||||
var old = msgs.querySelector('.sc-handoff'); if (old) old.remove();
|
||||
var d = document.createElement('div'); d.className = 'sc-m bot sc-handoff';
|
||||
var a = document.createElement('a'); a.className = 'sc-cta'; a.href = link || support; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'Open network support';
|
||||
d.appendChild(a); msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
|
||||
}
|
||||
function open() {
|
||||
panel.hidden = false; btn.setAttribute('aria-expanded', 'true'); root.className = 'open';
|
||||
if (!greeted) {
|
||||
greeted = true;
|
||||
add('Hi. Ask me how ' + NAME + ' works, what it costs, how payouts work, or about any other site in the network. Straight answers, no income hype.', 'bot');
|
||||
var t = $('scTopics'); TOPICS.slice(0, 4).forEach(function (q) {
|
||||
var b = document.createElement('button'); b.type = 'button'; b.textContent = q; b.addEventListener('click', function () { input.value = q; send(); }); t.appendChild(b);
|
||||
});
|
||||
}
|
||||
setTimeout(function () { input.focus(); }, 50);
|
||||
}
|
||||
function close() { panel.hidden = true; btn.setAttribute('aria-expanded', 'false'); root.className = ''; }
|
||||
btn.addEventListener('click', function () { panel.hidden ? open() : close(); });
|
||||
$('scClose').addEventListener('click', close);
|
||||
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !panel.hidden) close(); });
|
||||
async function send() {
|
||||
var q = input.value.trim(); if (!q) return;
|
||||
input.value = ''; $('scTopics').innerHTML = '';
|
||||
add(q, 'me'); var wait = add('...', 'bot wait');
|
||||
try {
|
||||
var r = await (await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: q, history: history.slice(-6) }) })).json();
|
||||
wait.remove();
|
||||
add(r.reply || r.error || 'Something went wrong. Try again in a moment.', 'bot');
|
||||
history.push(q, r.reply || '');
|
||||
if (r.handoff) offer(r.support);
|
||||
} catch (e) { wait.remove(); add('I could not reach the assistant just now. Try again in a moment, or open network support.', 'bot'); offer(); }
|
||||
}
|
||||
$('scForm').addEventListener('submit', function (e) { e.preventDefault(); send(); });
|
||||
})();
|
||||
@@ -68,6 +68,7 @@
|
||||
<div id="status" class="note" hidden></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/wallet.js?v=6"></script>
|
||||
<script src="/assets/buy.js?v=6"></script>
|
||||
<script src="/assets/boost.js?v=6"></script>
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
<div id="status" class="note" hidden></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/contract.js?v=6"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
<div class="card"><h2>Who to ask</h2><p>TrustClickz, 615 Green Valley Drive, Moody, AL 35004. <a href="https://instantadpay.com/support" target="_blank" rel="noopener">Network support</a>.</p></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/static.js?v=6"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -130,6 +130,7 @@
|
||||
<div id="status" class="note" hidden></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/how.js?v=6"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -96,6 +96,7 @@
|
||||
<div id="status" class="note" hidden></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/front.js?v=6"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
<div id="status" class="note" hidden></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/ledger.js?v=6"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
<div id="status" class="note" hidden></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/member.js?v=6"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -85,6 +85,7 @@
|
||||
<div id="status" class="note" hidden></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/wallet.js?v=6"></script>
|
||||
<script src="/assets/my.js?v=6"></script>
|
||||
</body>
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
<div class="card"><h2>Contact</h2><p>Questions, problems or a request about your data: <a href="https://instantadpay.com/support" target="_blank" rel="noopener">network support</a>, or write to TrustClickz, 615 Green Valley Drive, Moody, AL 35004.</p></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/static.js?v=6"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
<div id="kit" style="display:flex;flex-direction:column;gap:16px"><p class="muted">Loading the kit...</p></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/kitpage.js?v=6"></script>
|
||||
<script src="/assets/promote.js?v=6"></script>
|
||||
</body>
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
<div class="card"><h2>Contact</h2><p>Questions, problems or a request about your data: <a href="https://instantadpay.com/support" target="_blank" rel="noopener">network support</a>, or write to TrustClickz, 615 Green Valley Drive, Moody, AL 35004.</p></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=7"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/static.js?v=6"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"site": "viraladblitz",
|
||||
"home": [
|
||||
{ "q": "What is ViralAdBlitz?", "kb": "about", "must": ["text ad", "five", "Boost"] },
|
||||
{ "q": "How long can my headline be?", "kb": "free-ad", "must": ["60", "90", "no link shorteners"] },
|
||||
{ "q": "How much does a Boost cost and what do I get?", "kb": "boost", "must": ["\\$5", "500", "not income"] },
|
||||
{ "q": "Where does my $5 go when I boost?", "kb": "split", "must": ["10%", "50%", "passed over", "20 places"] },
|
||||
{ "q": "How do I withdraw my earnings?", "kb": "withdraw", "must": ["nothing to withdraw", "same|inside the buyer"] },
|
||||
{ "q": "Do my own views count?", "kb": "views", "must": ["never count", "24 hours"] },
|
||||
{ "q": "Why is someone skipped on my page?", "kb": "spread", "must": ["LEVEL 1 to LEVEL 5", "next person up"] },
|
||||
{ "q": "Which wallet should I use?", "kb": "wallet", "must": ["SafePal or any other crypto wallet", "POL"] },
|
||||
{ "q": "Can I get a refund on my Boost?", "kb": "refund", "must": ["final"] },
|
||||
{ "q": "Is this a pyramid scheme?", "kb": "safe", "must": ["contract", "not income"] }
|
||||
],
|
||||
"cross": [
|
||||
{ "q": "What is Downline Banners?", "site": "bannerline" },
|
||||
{ "q": "How much is Pro on DownlineHydra?", "site": "downlinehydra" },
|
||||
{ "q": "How does the 5xYourTeam draft work?", "site": "fivex" },
|
||||
{ "q": "What is a spin link on LinkSpin?", "site": "linkspin" },
|
||||
{ "q": "How do InstantAdPay ad packages work?", "site": "iap" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// Site assistant checks (2026-11-15): node qa/chatbot.test.mjs
|
||||
// No network: a stand-in OpenRouter and a stand-in hub. Checks the instant answers route every example question to its own entry,
|
||||
// the house rules (no em dashes, no MetaMask, never RM Circle, ad-credits line where credits come up, no income promises),
|
||||
// the network merge (home boosted, a named site boosted), the support hand-off, and the site's scripted Q&A (qa/chat-qa.json:
|
||||
// home questions must land on the named entry and contain the expected facts).
|
||||
// The SAME file ships in every rebuilt network site.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
|
||||
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'chat-'));
|
||||
process.env.DATA_DIR = DIR; delete process.env.DOCSTORE_URL; process.env.NETKB = '0'; delete process.env.OPENROUTER_API_KEY;
|
||||
let pass = 0, fail = 0; const bad = [];
|
||||
const ok = (c, m) => { if (c) pass++; else { fail++; bad.push(m); console.log('FAIL', m); } };
|
||||
|
||||
// stand-in OpenRouter: answers with what the system prompt says about the first KB entry, so we can see the prompt
|
||||
let lastPrompt = '', reply = 'Fine.';
|
||||
const or = http.createServer((req, res) => { let b = ''; req.on('data', c => { b += c; }); req.on('end', () => {
|
||||
const j = JSON.parse(b); lastPrompt = j.messages[0].content; ok(j.reasoning && j.reasoning.enabled === false, 'reasoning is switched off');
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('\n\n' + JSON.stringify({ choices: [{ message: { content: reply } }] })); }); });
|
||||
await new Promise(r => or.listen(0, r));
|
||||
process.env.OPENROUTER_URL = 'http://127.0.0.1:' + or.address().port + '/v1/chat/completions';
|
||||
|
||||
const cfg = require(path.join(ROOT, 'config.js')); if (cfg.reset) cfg.reset();
|
||||
const bot = require(path.join(ROOT, 'chatbot.js'));
|
||||
const core = require(path.join(ROOT, 'chatcore.js'));
|
||||
const kb = require(path.join(ROOT, 'kb.js'));
|
||||
const netkb = require(path.join(ROOT, 'netkb.js'));
|
||||
const dataDir = bot.SITE.dataDir;
|
||||
await bot.init();
|
||||
|
||||
// 1. seeds and the fast path: every example question of a canned entry lands on that entry (first match wins)
|
||||
const seeds = core.seeds();
|
||||
ok(seeds.length >= 12, 'at least 12 seeded entries (' + seeds.length + ')');
|
||||
for (const c of bot.CANNED) {
|
||||
ok(c.re instanceof RegExp, c.id + ' has a pattern');
|
||||
for (const q of c.q || []) { const hit = await kb.fastPath(q); ok(hit && hit.id === 'c-' + c.id, 'example "' + q + '" -> ' + c.id + ' (got ' + (hit && hit.id) + ')'); }
|
||||
}
|
||||
// 2. house rules in every seeded answer
|
||||
for (const s of seeds) {
|
||||
ok(!/[—―]/.test(s.answer + s.title), s.id + ': no em dashes');
|
||||
ok(!/metamask/i.test(s.answer), s.id + ': never recommends MetaMask');
|
||||
ok(!/rm ?circle/i.test(s.answer), s.id + ': never RM Circle');
|
||||
ok(!/(guarantee[ds]? (income|earnings|profit)|you will (earn|make)|passive income|get rich|up to \$?\d[\d,.]* (a|per) (day|week|month))/i.test(s.answer), s.id + ': no income promise');
|
||||
if (/\bad credits?\b/i.test(s.answer)) ok(/Ad credits buy advertising, not income\./.test(s.answer), s.id + ': ad credits line');
|
||||
if (/wallet/i.test(s.answer) && /(which|use|recommend)/i.test(s.answer) && /safepal/i.test(s.answer)) ok(/SafePal or any other crypto wallet/i.test(s.answer), s.id + ': wallet wording');
|
||||
}
|
||||
// 3. the engine: scrub, support hand-off, the AI path
|
||||
ok(core.scrub('A — B, use MetaMask or SafePal') === 'A, B, use SafePal', 'scrub: em dash and MetaMask (' + core.scrub('A — B, use MetaMask or SafePal') + ')');
|
||||
{ const r = await bot.answer('I need to talk to a real person about my account'); ok(r.handoff === true, 'asking for a person hands off'); }
|
||||
{ const r = await bot.answer(''); ok(!!r.error, 'empty question refused'); }
|
||||
fs.writeFileSync(path.join(dataDir || DIR, 'openrouter.key'), 'test-key');
|
||||
reply = 'Sure — try RM Circle'; { const r = await bot.answer('zzqx unrelated words nobody wrote down'); ok(!/rm ?circle/i.test(r.reply) && !/—/.test(r.reply), 'an RM Circle or em dash reply never leaves (' + r.reply + ')'); }
|
||||
ok(/NEVER promise or estimate income/.test(lastPrompt) && /SafePal or any other crypto wallet/.test(lastPrompt) && /Ad credits buy advertising, not income\./.test(lastPrompt), 'house rules in the system prompt');
|
||||
reply = 'Fine.';
|
||||
|
||||
// 4. the network merge: home boosted, a named site boosted, labelled with the site and its link
|
||||
const GENERAL = bot.CANNED.find(c => c.id !== 'support' && c.id !== 'refund' && (c.q || []).length).q[0].replace(/\?$/, '');
|
||||
netkb._set({ version: 'v1', sites: { othersite: { name: 'Other Site', url: 'https://other.example', count: 1 }, [process.env.HUB_SITE || bot.SITE.hubSite]: { name: bot.SITE.name, url: bot.SITE.url } },
|
||||
entries: [{ site: 'othersite', id: 'about', title: 'What is Other Site?', questions: ['What is Other Site?', GENERAL + ' on Other Site'], answer: 'Other Site is a test site with its own rules.', tags: ['test'] }] });
|
||||
await kb.load(true);
|
||||
{ const hits = await kb.search(GENERAL, 8); const top = hits[0] && hits[0].entry; ok(top && !top.site, 'home entries first for a general question (top ' + (top && top.id) + ')'); }
|
||||
{ const hits = await kb.search(GENERAL + ' on Other Site', 8); const top = hits[0] && hits[0].entry; ok(top && top.site === 'othersite', 'a named site boosts its own entry (top ' + (top && top.id) + ')'); }
|
||||
{ const block = kb.promptBlock(await kb.context('What is Other Site', 6)); ok(/about Other Site, another network site; send people to https:\/\/other\.example/.test(block), 'remote entry labelled with site and link'); }
|
||||
{ const fp = await kb.fastPath('What is Other Site?'); ok(!fp || !String(fp.id).startsWith('othersite:'), 'other sites never take the fast path'); }
|
||||
{ const own = await kb.own(); ok(own.length === seeds.length && own.every(e => !e.site), 'publish set = this site\'s own entries only'); }
|
||||
|
||||
// 5. the scripted Q&A (home questions)
|
||||
const qaFile = path.join(ROOT, 'qa', 'chat-qa.json');
|
||||
if (fs.existsSync(qaFile)) {
|
||||
const qa = JSON.parse(fs.readFileSync(qaFile, 'utf8'));
|
||||
for (const t of qa.home || []) {
|
||||
const r = await bot.answer(t.q);
|
||||
if (t.kb) ok(r.kb === 'c-' + t.kb || (Array.isArray(r.kb) && r.kb.includes('c-' + t.kb)), 'Q&A "' + t.q + '" -> ' + t.kb + ' (got ' + JSON.stringify(r.kb) + ')');
|
||||
for (const m of t.must || []) ok(new RegExp(m, 'i').test(r.reply) || new RegExp(m, 'i').test(lastPrompt), 'Q&A "' + t.q + '" mentions /' + m + '/');
|
||||
}
|
||||
}
|
||||
or.close();
|
||||
console.log((fail ? 'FAILED ' : 'ok ') + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
+8
-1
@@ -127,7 +127,7 @@ const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA,
|
||||
VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '2', LINK_PROBE: '0', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + LOOKUP_PORT + '/api/network/member',
|
||||
NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid', NETWORK_SITES_HUB: '0',
|
||||
CONTRACT_ADDRESS: SHOP, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200', EXPLORER: 'https://explorer.invalid',
|
||||
HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'viraladblitz', HUB_TICK_MS: '300', HUB_DOWN_MS: '300', HUB_CACHE_MS: '200',
|
||||
HUB_ENABLED: '1', NETKB: '0', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'viraladblitz', HUB_TICK_MS: '300', HUB_DOWN_MS: '300', HUB_CACHE_MS: '200',
|
||||
LS_TRACK_URL: 'http://127.0.0.1:' + LS_PORT, LS_SWEEP_FIRST_MS: '300', LS_SWEEP_MS: '300', LS_RETRY_MS: '300', LS_CACHE_MS: '100',
|
||||
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT });
|
||||
process.on('exit', () => { try { srv && srv.kill(); } catch (e) {} });
|
||||
@@ -208,6 +208,13 @@ async function main() {
|
||||
ok(/script-src[^;]*https:\/\/linkspin\.app/.test(r.headers.get('content-security-policy') || ''), 'CSP admits linkspin.app (network zones)');
|
||||
r = await anon.req('/nobody-at-all'); ok(r.status === 404 && /Back to the wire/.test(await r.text()), 'a username the hub does not know: 404');
|
||||
r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in');
|
||||
// the site assistant (2026-11-15): widget on every page, canned answers without AI, admin KB behind the token
|
||||
ok(/<script src="\/assets\/chat\.js\?v=\d+" defer><\/script>/.test(home) && (await anon.req('/assets/chat.js')).status === 200 && (await anon.req('/assets/chat.css')).status === 200, 'chat widget on the page, its script and styles served');
|
||||
{ const cr = await anon.req('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'What is a Boost?' }) }); const cj = await cr.json();
|
||||
ok(cr.status === 200 && cj.canned && /\$5/.test(cj.reply) && /500/.test(cj.reply) && /A Boost buys advertising, not income\./.test(cj.reply), 'chat: canned Boost answer', cj); }
|
||||
{ const cr = await anon.req('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'my boost did not show up' }) }); const cj = await cr.json();
|
||||
ok(cj.handoff === true && /^https:\/\/instantadpay\.com\/support\?from=viraladblitz/.test(cj.support || ''), 'chat: account problem hands off to network support', cj); }
|
||||
ok((await anon.req('/api/admin/kb')).status === 401, 'admin KB needs the token');
|
||||
|
||||
console.log('4. promo kit');
|
||||
{ const kr = await anon.req('/api/promo-kit?u=smokeleader'); const k = await kr.json();
|
||||
|
||||
@@ -31,6 +31,7 @@ const proof = require('./proof');
|
||||
const netsites = require('./netsites');
|
||||
const vabnas = require('./vabnas');
|
||||
const lstrack = require('./lstrack');
|
||||
const chatbot = require('./chatbot'); // the site assistant (2026-11-15): chatcore.js + kb.js + the network knowledge base (netkb.js)
|
||||
|
||||
const PUB = path.join(__dirname, 'public');
|
||||
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
|
||||
@@ -214,6 +215,7 @@ const server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
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' });
|
||||
@@ -471,6 +473,7 @@ const server = http.createServer(async (req, res) => {
|
||||
shop.init(C);
|
||||
vabnas.init({ boosts: () => wire.purchases(), remaining: b => wire.remaining(b), ad: id => store.ad(id) });
|
||||
setInterval(() => { if (store.prune()) wire.rebuild(); }, 3600000).unref();
|
||||
chatbot.init(); // after docstore.init: kb.json is a MySQL document
|
||||
lstrack.init(C, store); // LinkSpin tracked links for text ads: retry sweep (fails soft while LinkSpin is down or does not know the endpoint)
|
||||
{ let busy = false; const tick = () => { if (busy) return; busy = true; lstrack.sweep(25).catch(() => {}).finally(() => { busy = false; }); };
|
||||
setTimeout(tick, Number(process.env.LS_SWEEP_FIRST_MS || 20000)).unref(); setInterval(tick, Number(process.env.LS_SWEEP_MS || 120000)).unref(); }
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const PUB = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'public');
|
||||
const SITE = 'https://viraladblitz.com';
|
||||
const V = { css: 6, common: 7, page: 6 };
|
||||
const V = { css: 6, common: 7, page: 6, chat: 1 }; // chat: the site assistant widget (2026-11-15)
|
||||
const F = { co: 'TrustClickz', addr: '615 Green Valley Drive, Moody, AL 35004', updated: 'November 14, 2026', boostUsd: 5, views: '500', days: 30 };
|
||||
const FONTS = 'https://fonts.googleapis.com/css2?family=Barlow+Condensed:ital,wght@1,700;1,800&family=Chakra+Petch:wght@500;600;700&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500;700&display=swap';
|
||||
// the daylight look's shared SVG bits (same as common.js)
|
||||
@@ -52,7 +52,7 @@ ${o.ld ? '<script type="application/ld+json">' + JSON.stringify(o.ld) + '</scrip
|
||||
<body>
|
||||
`;
|
||||
}
|
||||
const tail = scripts => '<script src="/assets/common.js?v=' + V.common + '"></script>\n' + scripts.map(s => '<script src="/assets/' + s + '?v=' + V.page + '"></script>').join('\n') + '\n</body>\n</html>\n';
|
||||
const tail = scripts => '<script src="/assets/common.js?v=' + V.common + '"></script>\n<script src="/assets/chat.js?v=' + V.chat + '" defer></script>\n' + scripts.map(s => '<script src="/assets/' + s + '?v=' + V.page + '"></script>').join('\n') + '\n</body>\n</html>\n';
|
||||
const page = (file, o, body, scripts) => fs.writeFileSync(path.join(PUB, file), head(o) + body + tail(scripts));
|
||||
|
||||
// ---------------------------------------------------------------- front page
|
||||
|
||||
Reference in New Issue
Block a user