Compare commits
24 Commits
793354ea80
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b97a4db7ec | |||
| 57d04c97dc | |||
| f028a61d78 | |||
| a8df9686ae | |||
| 856dbcb8d3 | |||
| 1987823e4b | |||
| ffa0d74c70 | |||
| 9bc6e84f2d | |||
| cb2e090782 | |||
| edaf7bb979 | |||
| 42b4e2edc0 | |||
| cbefb29863 | |||
| b49206f642 | |||
| fadcfaa7bf | |||
| 18e9c5d56a | |||
| 00cb51f2b4 | |||
| b64c4cf72f | |||
| 213ee3a32b | |||
| 04ded6822c | |||
| 96d6281e3e | |||
| b6e020e025 | |||
| 7446df2f4f | |||
| 3a6ac0a81e | |||
| ab07ffebe2 |
@@ -1 +1,2 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
|
data/
|
||||||
|
|||||||
+3
-2
@@ -1,10 +1,11 @@
|
|||||||
FROM node:20-alpine
|
FROM node:20-alpine
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json server.js layout.js blog.js programs.js netsites.js ./
|
COPY package.json package-lock.json server.js layout.js blog.js programs.js netsites.js netdeals.js chatbot.js chatcore.js kb.js netkb.js docstore.js legal.js networksso.js my.js iapswitch.js ./
|
||||||
RUN npm ci --omit=dev --no-audit --no-fund
|
RUN npm ci --omit=dev --no-audit --no-fund
|
||||||
COPY content/ ./content/
|
COPY content/ ./content/
|
||||||
COPY public/ ./public/
|
COPY public/ ./public/
|
||||||
ENV NODE_ENV=production PORT=80
|
ENV NODE_ENV=production PORT=80 DATA_DIR=/app/data
|
||||||
|
RUN mkdir -p /app/data
|
||||||
EXPOSE 80
|
EXPOSE 80
|
||||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s CMD wget -qO- http://127.0.0.1/health || exit 1
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s CMD wget -qO- http://127.0.0.1/health || exit 1
|
||||||
CMD ["node", "server.js"]
|
CMD ["node", "server.js"]
|
||||||
|
|||||||
@@ -7,4 +7,7 @@ stackpol.com: every POL payout across the network, stacked. Live app since 2026-
|
|||||||
- Blog: content/blog/<slug>.json, one file per post (title, seoTitle, excerpt, body HTML, cover, tags, publishedAt, updated, faq[]). Same engine as InstantAdPay/LinkSpin blog.js, ported to file storage. Future-dated posts stay hidden until their time. Generators in tools/write_posts_*.py.
|
- Blog: content/blog/<slug>.json, one file per post (title, seoTitle, excerpt, body HTML, cover, tags, publishedAt, updated, faq[]). Same engine as InstantAdPay/LinkSpin blog.js, ported to file storage. Future-dated posts stay hidden until their time. Generators in tools/write_posts_*.py.
|
||||||
- programs.js: program registry (keys match the indexer); game blurbs are InstantAdPay's own.
|
- programs.js: program registry (keys match the indexer); game blurbs are InstantAdPay's own.
|
||||||
- mockup/: the Oct design mockup (artifact https://claude.ai/artifact/1mN4dCYUcbw7EHicCdejM3).
|
- mockup/: the Oct design mockup (artifact https://claude.ai/artifact/1mN4dCYUcbw7EHicCdejM3).
|
||||||
- Standing rule (Marty 2026-11-15): every rebuilt network site is added here when it goes live: a programs.js entry, its /earn/<slug> page (automatic from the entry, plus public/img/<key>.jpg 800x420) and an indexer source for its member payouts (house/company wallets excluded). ViralAdBlitz added 2026-11-15. Next: DownlineHydra, 5xYourTeam.
|
- Standing rule (Marty 2026-11-15): every rebuilt network site is added here when it goes live: a programs.js entry, its /earn/<slug> page (automatic from the entry, plus public/img/<key>.jpg 800x420) and an indexer source for its member payouts (house/company wallets excluded). ViralAdBlitz, 5xYourTeam and DownlineHydra added 2026-11-15.
|
||||||
|
- Site assistant (2026-11-15): chat widget on every page (`public/assets/chat.js` + `chat.css`, loaded from layout.js). `chatbot.js` holds what it knows (CANNED + FACTS from this repo); `chatcore.js`, `kb.js` (kb.json is a MySQL document, see Storage) and `netkb.js` (the shared network knowledge on the hub, signed as `HUB_SITE=stackpol` with `HUB_SECRET`) are the same files as the rebuilt sites. OpenRouter key: Coolify env `OPENROUTER_API_KEY`. No admin KB editing on Stack POL. Test: `node qa/chatbot.test.mjs`.
|
||||||
|
- Storage (Marty 2026-11-16: "they should live in the database"): MySQL, Coolify `stackpol-mysql` yw404lxgfkbb5n9s3pxu1hxk (db `stackpol`, binlog expiry 3 h persisted, in core's hourly dumps). App env `DOCSTORE_URL`; `docstore.js` (same file as LinkSpin, skips unchanged writes) keeps the data documents of DATA_DIR (/app/data, no volume) in table `docs`: `stack-index.json` (the last indexer snapshot minus `at`), `stack-index-at.json` ({at}), `kb.json` (chatbot entries), `netkb-cache.json` (network knowledge cache). Loaded before the server listens, so a deploy serves the last totals at once. The ingest API is unchanged. Without DOCSTORE_URL (local only) they are plain files in DATA_DIR.
|
||||||
|
- My Stack POL (Marty approved 2026-11-19): signed-in member area at /my (my.js), "Sign in" / "My Stack POL" in the header. Network sign-in through the hub only (networksso.js, the shared file, unchanged copy of IAP's): envs HUB_SSO=on, HUB_URL, HUB_SECRET, HUB_SITE=stackpol (the last three already serve netkb). Needs stackpol in the hub's HUB_SSO_SITES. Session = signed cookie sp.sid (7 days, keyed off HUB_SECRET); sign-out writes my-signouts.json (MySQL document) so older cookies stop working. Shows the page link + switch, Pro (IAP's rule via stack-optin.json pro), join links (programs.js), share kit, and the member's own payout rows from the snapshot's `my` block (tools/indexer.py). The switch stays in IAP's stack-optin.json: iapswitch.js calls IAP POST /api/partner/stackpol/switch (spec in the file header) with STACKPOL_SWITCH_KEY; until IAP has that route and both apps have the key, /my links to IAP Promo tools instead. Test: node qa/my.test.mjs.
|
||||||
|
|||||||
@@ -71,6 +71,11 @@ function renderIndex(page, tag) {
|
|||||||
let h = head({ title, desc, path: p, nav: '/blog', noindex: !!tag, jsonld: [{ '@context': 'https://schema.org', '@type': 'Blog', name: 'Stack POL Blog', url: SITE + '/blog', description: desc, publisher: { '@type': 'Organization', name: 'Stack POL', url: SITE } }] });
|
let h = head({ title, desc, path: p, nav: '/blog', noindex: !!tag, jsonld: [{ '@context': 'https://schema.org', '@type': 'Blog', name: 'Stack POL Blog', url: SITE + '/blog', description: desc, publisher: { '@type': 'Organization', name: 'Stack POL', url: SITE } }] });
|
||||||
h += '<section style="padding:40px 0 10px"><p class="kick">' + (tag ? 'Tag: ' + esc(tag) : 'The Stack POL blog') + '</p><h1>Earning POL across the network, <span style="color:var(--gold)">one stack at a time</span></h1><p class="lead">' + esc(desc) + '</p></section>';
|
h += '<section style="padding:40px 0 10px"><p class="kick">' + (tag ? 'Tag: ' + esc(tag) : 'The Stack POL blog') + '</p><h1>Earning POL across the network, <span style="color:var(--gold)">one stack at a time</span></h1><p class="lead">' + esc(desc) + '</p></section>';
|
||||||
h += slice.length ? '<div class="posts">' + slice.map(cardHtml).join('') + '</div>' : '<p class="lead">Nothing published yet. Check back soon.</p>';
|
h += slice.length ? '<div class="posts">' + slice.map(cardHtml).join('') + '</div>' : '<p class="lead">Nothing published yet. Check back soon.</p>';
|
||||||
|
if (!tag && page === 1) { // Guides across the network (2026-11-17): each program's own evergreen Guides section
|
||||||
|
const gs = require('./programs').PROGRAMS.filter(x => x.guides);
|
||||||
|
if (gs.length) h += '<div class="sec-head"><h2>Guides across the network</h2></div><p class="lead" style="max-width:72ch">How each program works, whether it is legit (the contract, the ledger and the split) and the FAQ, each on its own site: '
|
||||||
|
+ gs.map(x => '<a href="' + esc(x.guides) + '" target="_blank" rel="noopener">' + esc(x.n) + '</a>').join(', ') + '.</p>';
|
||||||
|
}
|
||||||
h += spot(ZONES.banner, ZONES.strip);
|
h += spot(ZONES.banner, ZONES.strip);
|
||||||
if (pages > 1) h += '<div class="pager">' + (page > 1 ? '<a href="/blog' + (page - 1 > 1 ? '/page/' + (page - 1) : '') + '">← Newer</a>' : '<span></span>') + (page < pages ? '<a href="/blog/page/' + (page + 1) + '">Older →</a>' : '<span></span>') + '</div>';
|
if (pages > 1) h += '<div class="pager">' + (page > 1 ? '<a href="/blog' + (page - 1 > 1 ? '/page/' + (page - 1) : '') + '">← Newer</a>' : '<span></span>') + (page < pages ? '<a href="/blog/page/' + (page + 1) + '">Older →</a>' : '<span></span>') + '</div>';
|
||||||
return h + tail();
|
return h + tail();
|
||||||
|
|||||||
+89
@@ -0,0 +1,89 @@
|
|||||||
|
// Stack POL'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.
|
||||||
|
// Storage (2026-11-16): kb.json and netkb-cache.json are MySQL documents through docstore.js (DOCSTORE_URL, stackpol-mysql), so
|
||||||
|
// the entries and the cached network set survive a deploy. The OpenRouter key comes from the OPENROUTER_API_KEY env (a Coolify
|
||||||
|
// secret). No admin knowledge-base editing here.
|
||||||
|
//
|
||||||
|
// Every fact below was checked against this repo on KNOWLEDGE_DATE: server.js (the on-page FAQ, the pages, /api/totals, member
|
||||||
|
// stacks only when switched on), programs.js (the programs and their kinds), README.md (the indexer refreshes every 5 minutes;
|
||||||
|
// members are named only when opted in). Stack POL sells nothing and holds nothing.
|
||||||
|
// 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, never quote totals as what someone will earn, never RM Circle.
|
||||||
|
'use strict';
|
||||||
|
const core = require('./chatcore');
|
||||||
|
const { PROGRAMS } = require('./programs');
|
||||||
|
|
||||||
|
const KNOWLEDGE_DATE = '2026-11-20';
|
||||||
|
// Network Weekend (Black Friday to Cyber Monday 2026): live Fri 11-27 00:00 CT to Tue 12-01 00:00 CT (CST = UTC-6); WEEKEND_NOW = test clock
|
||||||
|
const NW_START = Date.parse('2026-11-27T06:00:00Z'), NW_END = Date.parse('2026-12-01T06:00:00Z');
|
||||||
|
const nwNow = () => { const t = process.env.WEEKEND_NOW ? Date.parse(process.env.WEEKEND_NOW) : NaN; return Number.isNaN(t) ? Date.now() : t; };
|
||||||
|
const nwLive = () => { const t = nwNow(); return t >= NW_START && t < NW_END; };
|
||||||
|
const URL_ = String(process.env.SITE_URL || 'https://stackpol.com').replace(/\/+$/, '');
|
||||||
|
const SUPPORT = 'https://instantadpay.com/support';
|
||||||
|
const NAMES = PROGRAMS.map(p => p.n).join(', ');
|
||||||
|
const NOT_INCOME = 'No promise of income is made: the totals are what the whole network has paid so far, and many members earn little or nothing.';
|
||||||
|
|
||||||
|
const CANNED = [
|
||||||
|
{ id: 'support', title: 'Talk to a person, or a problem with my account', q: ['How do I contact support?', 'My payout is not on the ledger', 'I need a real person'], tags: ['support', 'help', 'ticket', 'problem'],
|
||||||
|
re: core.SUPPORT_RE, handoff: true,
|
||||||
|
a: 'Network support handles every network site: open ' + SUPPORT + ', say which program it is about, and include your username, your wallet address and the transaction link if you have one. Marty answers there and by email. Tap "Open network support" below and your question goes with you.' },
|
||||||
|
{ id: 'pro', title: 'Stack POL Pro: what it gives and how it unlocks', q: ['What is Stack POL Pro?', 'What does Pro give me?', 'Why does my Pro say Not yet?'], tags: ['pro', 'stack pol pro', 'banners', 'qr code', 'unlock'],
|
||||||
|
re: /(pro|pro member|premium|upgrade|not yet)/i,
|
||||||
|
a: 'Stack POL Pro puts your own LinkSpin Banner Spins in the ad spots on your Stack POL page, adds your spin links, and shows your QR code; any Stack POL page opened with ?ref=your-username carries your referral. It unlocks once, for good, with an InstantAdPay ad package of $10 or more bought on or after November 9, 2026, when Pro launched (packages bought before then do not unlock it). Your Pro status shows at ' + URL_ + '/my. If you think yours should be on, ask network support with your username.' },
|
||||||
|
{ id: 'my-stack', title: 'My Stack POL: signing in', q: ['How do I sign in to Stack POL?', 'What is My Stack POL?', 'Where are my join links?'], tags: ['sign in', 'my stack pol', 'login', 'join links', 'share kit'],
|
||||||
|
re: /(sign ?in|log ?in|my stack pol|\/my|join links|share kit)/i,
|
||||||
|
a: 'Go to ' + URL_ + '/my and tap "Sign in with your network account": it uses the account you already have on InstantAdPay, with no new password (not signed in there yet, it takes you through the InstantAdPay sign-in and straight back). Inside: your page switch, Pro, your join links for every network site, a share kit with a ready post, banner code, images and your QR code, and your own payouts.' },
|
||||||
|
{ id: 'about', title: 'What is Stack POL?', q: ['What is Stack POL?', 'How does Stack POL work?', 'What is this site?'], tags: ['stack pol', 'overview', 'ledger', 'payouts'],
|
||||||
|
re: /(what('s| is) (stack ?pol|this (site|place))|how does (stack ?pol|this site|it) work)/i,
|
||||||
|
a: 'Stack POL adds up every POL payout from the programs in the network: InstantAdPay, LinkSpin, the other network sites and the games that pay POL. The front page shows everyone combined, every row links to its Polygon transaction, and a member who switches it on gets their own page with their own stack. Stack POL only shows payouts; it sells nothing and holds nothing. ' + NOT_INCOME },
|
||||||
|
{ id: 'numbers', title: 'Where the numbers come from', q: ['Where do the numbers come from?', 'How often does it update?', 'Can I check a payment?'], tags: ['numbers', 'ledger', 'polygonscan', 'update'],
|
||||||
|
re: /(where do the numbers|numbers come from|how often|update[sd]?\b|refresh|check (a |the )?payment|polygonscan|verify)/i,
|
||||||
|
a: 'From each program\'s own payout records and from the network contracts on Polygon, refreshed every 5 minutes. Every row in the ledger (' + URL_ + '/ledger) links to its Polygon transaction, so anyone can check it on Polygonscan.' },
|
||||||
|
{ id: 'income', title: 'Is this income? Will I earn this much?', q: ['Will I earn this much?', 'Is this income?', 'How much can I make?'], tags: ['income', 'earnings', 'promise'],
|
||||||
|
re: /(will i (earn|make|get)|how much (can|will|do) (i|you|people) (earn|make)|is (this|it) income|earn this much|guarantee)/i,
|
||||||
|
a: NOT_INCOME + ' What one member stacks depends on what they do in each program.' },
|
||||||
|
{ id: 'my-page', title: 'Your own Stack POL page', q: ['How do I get my own Stack POL page?', 'Why is my name not on Stack POL?', 'How do I hide my page?'], tags: ['my page', 'opt in', 'username', 'promo tools'],
|
||||||
|
re: /(my (own )?(stack|page)|own (stack )?page|switch on|opt.?in|my name (is )?not|hide my|show my stack)/i,
|
||||||
|
a: 'Join InstantAdPay free, link a wallet, and switch on "Show my Stack POL page" in Promo tools. Your page lives at ' + URL_ + '/your-username and updates every 5 minutes. Members are named on Stack POL only when they switch it on.' },
|
||||||
|
{ id: 'programs', title: 'Which programs are on Stack POL', q: ['Which programs are on Stack POL?', 'Where does the POL come from?', 'Are the games included?'], tags: ['programs', 'games', 'sites', 'earn pages'],
|
||||||
|
re: /(which programs|what programs|programs (are|on)|where does the pol come from|games? (included|on)|\/earn)/i,
|
||||||
|
a: 'The programs on Stack POL: ' + NAMES + '. Each has its own page (for example ' + URL_ + '/earn/viraladblitz) and its own ledger filter, and each pays straight to members\' own wallets on Polygon. See them all at ' + URL_ + '/programs' },
|
||||||
|
{ id: 'start', title: 'How to start', q: ['How do I start?', 'How do I join?', 'Is it free?'], tags: ['join', 'start', 'free', 'instantadpay'],
|
||||||
|
re: /(how (do|can) i (start|join|sign ?up)|\bjoin\b|sign ?up|get started|is (it|this) free|free to join)/i,
|
||||||
|
a: 'Start free on InstantAdPay (https://instantadpay.com/join): one network account works across every network site. What you stack depends on what you do in each program. ' + NOT_INCOME },
|
||||||
|
{ id: 'custody', title: 'Does Stack POL hold my money?', q: ['Does Stack POL hold my money?', 'How do I withdraw from Stack POL?'], tags: ['custody', 'withdraw', 'wallet', 'safe'],
|
||||||
|
re: /(hold (my|the) (money|funds|pol)|withdraw|cash ?out|balance|safe|scam|legit)/i,
|
||||||
|
a: 'No. Stack POL only shows payouts. Every payment goes straight from the program to your own wallet on Polygon, so there is nothing here to withdraw.' },
|
||||||
|
{ id: 'pol', title: 'What is POL?', q: ['What is POL?', 'Is POL the same as MATIC?', 'Which wallet do I need?'], tags: ['pol', 'polygon', 'matic', 'wallet'],
|
||||||
|
re: /(what is pol|\bpol\b|matic|polygon|wallet|safepal|metamask)/i,
|
||||||
|
a: 'POL is the native token of the Polygon network, formerly MATIC. Fees are a fraction of a cent and transfers confirm in seconds, which is why small payouts work on it. To receive payouts, use SafePal or any other crypto wallet on Polygon, and never share your recovery phrase.' },
|
||||||
|
{ id: 'blog', title: 'The blog', q: ['Is there a blog?', 'Where are the guides?'], tags: ['blog', 'guides', 'articles'],
|
||||||
|
re: /\bblog\b|articles?|guides?|rss/i,
|
||||||
|
a: 'The blog at ' + URL_ + '/blog has guides on building in POL across the network, with an RSS feed at ' + URL_ + '/blog/feed.xml.' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const FAQ = [
|
||||||
|
{ id: 'f-network', title: 'Stack POL and the network', source: 'faq', tags: ['network', 'one account'],
|
||||||
|
questions: ['Is Stack POL part of InstantAdPay?', 'Which network sites are there?'],
|
||||||
|
answer: 'Stack POL is the network\'s payout tracker. One network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, DownlineHydra, 5xYourTeam, Stack POL and Earners Corner, and each site\'s member payouts show here.' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const FACTS = () => [
|
||||||
|
'- WHAT IT IS: Stack POL (' + URL_ + ') adds up every POL payout across the network: ' + NAMES + '. Front page = everyone combined (network totals, last 7 days, latest payouts), /programs, /earn/<program> pages, /ledger (filter ?p=), opt-in member pages ' + URL_ + '/<username>, /blog. It sells nothing and holds nothing: every payment goes from the program straight to the member\'s wallet on Polygon.',
|
||||||
|
'- DATA: each program\'s payout records and the network contracts on Polygon, refreshed every 5 minutes; every ledger row links to its Polygon transaction. Members are named only when they switch on "Show my Stack POL page" in InstantAdPay Promo tools (join InstantAdPay free and link a wallet first).',
|
||||||
|
(nwLive() ? '- NETWORK WEEKEND (live now, Black Friday to Cyber Monday, Fri 11-27 to Mon 11-30, midnight to midnight Central): Stack POL sells nothing itself. Its Pro view unlocks with any InstantAdPay package of $10 or more (an existing perk, not a weekend price), so a $10+ InstantAdPay pack this weekend also unlocks Stack POL Pro. Every network deal: https://instantadpay.com/weekend. Ad credits buy advertising, not income.' : null),
|
||||||
|
'- MY STACK POL (' + URL_ + '/my, live 2026-11-19): sign in with the network account (the InstantAdPay account; no new password). Shows the page switch, Pro status, join links for every network site, a share kit (ready post, banner code, images, QR code) and the payouts of that member.',
|
||||||
|
'- STACK POL PRO (it EXISTS; never say there is no Pro or paid tier): own LinkSpin Banner Spins in the page ad spots, own spin links and a QR code on the member page; ?ref=username on any Stack POL page carries their referral. Unlocks once, for good, with ONE InstantAdPay ad package of $10 or more bought on or after 2026-11-09 (Pro launch); packages bought before that date do not count, and several smaller packages do not add up. Status shows on /my as Pro or Not yet. Questions about a missing unlock go to network support.',
|
||||||
|
'- NEVER quote a total as what someone will earn; never state a maximum. ' + NOT_INCOME,
|
||||||
|
'- For how a program pays (prices, splits, rules), use that program\'s own knowledge-base entries and send people to that site. SUPPORT: network support at ' + SUPPORT + '.'
|
||||||
|
].filter(Boolean).join('\n');
|
||||||
|
|
||||||
|
const SITE = {
|
||||||
|
id: 'stackpol', hubSite: 'stackpol', netId: 'stackpol', name: 'Stack POL', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE,
|
||||||
|
dataDir: process.env.DATA_DIR || require('path').join(__dirname, 'data'), canned: CANNED, faq: FAQ, facts: FACTS,
|
||||||
|
intro: 'You are the assistant on Stack POL (' + URL_ + '), the network\'s payout tracker: it adds up every POL payout across the network\'s sites and games, each one checkable on Polygon. Most questions about how to earn belong to a specific program: answer from that program\'s entries and link to it.',
|
||||||
|
quickTopics: ['What is Stack POL?', 'How do I get my own page?', 'What is ViralAdBlitz?', 'How does Downline Banners pay?']
|
||||||
|
};
|
||||||
|
|
||||||
|
function init() { return core.init(SITE); }
|
||||||
|
module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE };
|
||||||
+229
@@ -0,0 +1,229 @@
|
|||||||
|
// 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)
|
||||||
|
// (since 2026-11-16 only a hand-off pattern answers outright; any other pattern hit is checked against step 1b)
|
||||||
|
// 1b. the hub's semantic match by meaning (netkb.route, core2 embeddings): answers with this site's entry when it is sure,
|
||||||
|
// keeps or overrules a pattern hit, and picks the prompt context; fails soft to the old path within NETKB_MATCH_MS
|
||||||
|
// 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, other = [];
|
||||||
|
try {
|
||||||
|
await kb.load();
|
||||||
|
// a question about another network site (named, and this site not named) skips this site's instant answers, except a hand-off
|
||||||
|
other = kb.namesOther(msg, S.hubSite);
|
||||||
|
if (other.length && new RegExp('\\b' + S.name.replace(/[^A-Za-z0-9]+/g, '\\s*') + '\\b', 'i').test(msg)) other = [];
|
||||||
|
hit = await kb.fastPath(msg);
|
||||||
|
if (hit && other.length && !hit.handoff) hit = null;
|
||||||
|
} catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
||||||
|
// a hand-off (support, one person's account problem) always answers from its exact pattern, before anything else
|
||||||
|
if (hit && hit.handoff) return { reply: hit.answer, canned: true, kb: hit.id, handoff: true };
|
||||||
|
// then meaning (2026-11-16, netkb.route): the hub's semantic match over the network KB answers, keeps or overrules the
|
||||||
|
// pattern hit, and picks the prompt context. Hub or model slow or down: null, and the pattern + BM25 path below runs as before.
|
||||||
|
let sem = null;
|
||||||
|
if (kbOk) { try { sem = await netkb.route(msg, { fast: hit, own: await kb.own(), prefer: other }); } catch (e) { sem = null; } }
|
||||||
|
if (sem) hit = sem.hit;
|
||||||
|
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, sem ? { via: sem.via } : {}, 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 = sem && sem.hits.length ? sem.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,31 @@
|
|||||||
|
{
|
||||||
|
"slug": "video-app-income-business-on-your-phone",
|
||||||
|
"title": "A complete business that fits on your phone, and the first video is free",
|
||||||
|
"seoTitle": "Video App Income: A Complete Business on Your Phone, First Video Free",
|
||||||
|
"excerpt": "Video App Income makes short promo videos on your phone for any link you paste, puts each one on a tracked share page, and lets you try it with one free video.",
|
||||||
|
"cover": "/img/vai-open.jpg",
|
||||||
|
"coverAlt": "Video App Income: short videos made on your phone",
|
||||||
|
"tags": [
|
||||||
|
"video app income",
|
||||||
|
"video marketing",
|
||||||
|
"polygon",
|
||||||
|
"getting started"
|
||||||
|
],
|
||||||
|
"publishedAt": "2026-11-21T06:25:00-06:00",
|
||||||
|
"updated": "2026-11-21T06:25:00-06:00",
|
||||||
|
"body": "<p>Most online businesses ask you to build five things before you can start. A page. A video. A way to track clicks. A way to get paid. A reason for anyone to say yes.</p>\n<p>Video App Income puts all five on your phone. It opened this week, and you can try it with one free video before you spend anything.</p>\n<h2>Start with a link</h2>\n<p>Paste a link to whatever you promote. It can be a program you're in, your own website, a store, a blog or a booking page. The app reads the page and writes a short script from what it says. Then it adds a voice, captions that light up word by word, footage and music.</p>\n<p>About a minute and a half later you have a finished vertical video. You never pick up a camera and you never edit anything.</p>\n<h2>Every video gets its own page</h2>\n<p>The video sits on a share page with a headline, your name and one button. The button goes wherever you choose. Send the page with a ready-made message, or hold up the QR code and let someone scan it in person.</p>\n<h2>Know who watched</h2>\n<p>This is the part most people have never had. You can make a link for one person and the page greets them by name. Then you see what they did: whether they opened it, how much they watched and whether they tapped your button. You follow up with the people who showed interest, not the ones who didn't.</p>\n<h2>Pay for what you use</h2>\n<p>Your first video is free, with no card and no purchase. After that a video is 10 credits. A $10 pack is 100 credits, enough for 10 videos. You pay in POL on Polygon, one time. There is no subscription and credits do not expire.</p>\n<h2>The earning side</h2>\n<p>You can use the app only for your own offers and never refer anyone. If you want to share it, here is how that works. Once you've bought credits, you can refer others. When someone you referred buys credits, a smart contract splits the payment in that same transaction: 30% to you, and 8% to each of the five positions above the buyer in the team matrix. It happens again every time they top up. The percentages are written into the contract and nobody can change them, including us. Every purchase and payout is public on the Polygon ledger.</p>\n<h2>Try it</h2>\n<p>Sign in with SafePal or any other crypto wallet, or with your InstantAdPay account. Make your first video free and see what comes back.</p>\n<p><a href=\"https://videoappincome.com/join?ref=martbost\" target=\"_blank\">Make your first video free on Video App Income</a></p>\n<p><a href=\"https://videoappincome.com/m/how-it-works.mp4\" target=\"_blank\">Watch the three-minute walkthrough</a></p>\n<p><em>No income is guaranteed. Most members will earn little or nothing. What you earn depends on your own effort and on purchases made by people you refer. Payouts are in POL, a cryptocurrency whose price changes.</em></p>\n<p>Video App Income also has its own page here, with the payouts its contract has made so far: <a href=\"/earn/video-app-income\">Video App Income on Stack POL</a>.</p>",
|
||||||
|
"faq": [
|
||||||
|
{
|
||||||
|
"q": "Is the first video really free?",
|
||||||
|
"a": "Yes. Your first video is free, with no card and no purchase. After that a video is 10 credits."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"q": "What does a credit cost?",
|
||||||
|
"a": "One credit is 10 cents. A $10 pack is 100 credits, enough for 10 videos. You pay one time in POL on Polygon, and there is no subscription."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"q": "How does the earning side work?",
|
||||||
|
"a": "Once you have bought credits, you can refer others. When someone you referred buys credits, the contract pays 30% to you and 8% to each of the five positions above the buyer, in that same transaction. No income is guaranteed."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
+210
@@ -0,0 +1,210 @@
|
|||||||
|
// Database-backed data documents (Marty 2026-11-13, standing rule: "everything database-driven ... files only for early
|
||||||
|
// prototyping"). Every *.json / *.jsonl data document under DATA_DIR that a module reads or writes with the fs *Sync calls lives
|
||||||
|
// in MySQL instead of on the volume: table `docs` (name = path relative to DATA_DIR, body LONGTEXT, updated_at). The modules keep
|
||||||
|
// their code; install() routes their fs calls on those paths to an in-memory copy that init() loads from MySQL at boot, and every
|
||||||
|
// change is written through to MySQL (coalesced per document, newest body wins, in order, retried until it lands).
|
||||||
|
//
|
||||||
|
// One writer at a time: init() claims the `docs_writer` row; an older app copy still running during a deploy finds the row taken
|
||||||
|
// and stops writing (logged), so it can never put stale data over the new copy's (the 2026-11-13 rotator.json loss).
|
||||||
|
// First boot: a document missing from MySQL is imported from its file, and the file is renamed <name>.imported-<date> (kept, not
|
||||||
|
// read again). Files the volume keeps on purpose: KEEP (rebuildable caches, uploads, images, the geo database, queues read by
|
||||||
|
// listing a folder). The SAME file ships in InstantAdPay and LinkSpin.
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
const KEEP_FILES = new Set(['chain-index.json']); // a rebuildable cache of the blockchain
|
||||||
|
const KEEP_DIRS = ['uploads', 'geo', 'refuel-pending', 'backups', 'marks', 'kits', 'kitimg']; // binary files, or folders read by listing
|
||||||
|
const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, renameSync: fs.renameSync,
|
||||||
|
unlinkSync: fs.unlinkSync, statSync: fs.statSync, appendFileSync: fs.appendFileSync };
|
||||||
|
|
||||||
|
let ROOT = null, pool = null, ME = crypto.randomBytes(8).toString('hex'), ready = false, writer = true;
|
||||||
|
const cache = new Map(); // name -> { body: string, at: ms }
|
||||||
|
const pending = new Map(); // name -> body string | null (delete)
|
||||||
|
const stored = new Map(); // name -> body as last read from or written to MySQL: an unchanged save is not rewritten (2026-11-15: whole-document rewrites filled core with 115 GB of binlogs)
|
||||||
|
let flushing = false, timer = null;
|
||||||
|
const stats = { writes: 0, deletes: 0, refused: 0, errors: 0, imported: 0, lastError: null };
|
||||||
|
|
||||||
|
function nameOf(p) {
|
||||||
|
if (!ROOT || typeof p !== 'string' || !/\.jsonl?$/i.test(p)) return null;
|
||||||
|
const abs = path.resolve(p); if (!abs.startsWith(ROOT + path.sep)) return null;
|
||||||
|
const rel = abs.slice(ROOT.length + 1).split(path.sep).join('/');
|
||||||
|
if (KEEP_FILES.has(rel) || KEEP_DIRS.some(d => rel === d || rel.startsWith(d + '/'))) return null;
|
||||||
|
return rel;
|
||||||
|
}
|
||||||
|
const enoent = p => { const e = new Error("ENOENT: no such file or directory, open '" + p + "'"); e.code = 'ENOENT'; e.errno = -2; e.path = p; return e; };
|
||||||
|
const enc = o => (typeof o === 'string' ? o : o && o.encoding) || null;
|
||||||
|
|
||||||
|
function put(name, body) {
|
||||||
|
cache.set(name, { body, at: Date.now() });
|
||||||
|
if (stored.get(name) === body) { pending.delete(name); return; } // same as what MySQL already holds: nothing to write
|
||||||
|
pending.set(name, body); kick();
|
||||||
|
}
|
||||||
|
function drop(name) { cache.delete(name); pending.set(name, null); kick(); }
|
||||||
|
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}); }, 300); }
|
||||||
|
|
||||||
|
async function flush() {
|
||||||
|
if (!pool || flushing || !pending.size) return;
|
||||||
|
flushing = true;
|
||||||
|
try {
|
||||||
|
for (const [name, body] of [...pending]) {
|
||||||
|
if (pending.get(name) !== body) continue; // replaced while we were busy: the newer body goes next round
|
||||||
|
if (!writer) { pending.delete(name); stats.refused++; continue; }
|
||||||
|
const c = await pool.getConnection();
|
||||||
|
try {
|
||||||
|
await c.beginTransaction();
|
||||||
|
const [[w]] = await c.query('SELECT owner FROM docs_writer WHERE id = 1 FOR UPDATE');
|
||||||
|
if (!w || w.owner !== ME) { await c.rollback(); writer = false; pending.delete(name); stats.refused++; console.error('docstore: another app copy took over writing; this copy stops writing'); continue; }
|
||||||
|
if (body === null) { await c.query('DELETE FROM docs WHERE name = ?', [name]); stats.deletes++; }
|
||||||
|
else { await c.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = VALUES(updated_at)', [name, body, Date.now()]); stats.writes++; }
|
||||||
|
await c.commit();
|
||||||
|
if (body === null) stored.delete(name); else stored.set(name, body);
|
||||||
|
if (pending.get(name) === body) pending.delete(name);
|
||||||
|
} catch (e) { try { await c.rollback(); } catch (x) {} stats.errors++; stats.lastError = String(e.message).slice(0, 200); console.error('docstore write', name, e.message); }
|
||||||
|
finally { c.release(); }
|
||||||
|
}
|
||||||
|
} finally { flushing = false; if (pending.size) setTimeout(() => flush().catch(() => {}), 1000); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Route the fs *Sync calls on data documents. Installed before any module runs; until init() the documents read from disk.
|
||||||
|
function install(dataDir) {
|
||||||
|
if (ROOT) return; ROOT = path.resolve(dataDir);
|
||||||
|
fs.readFileSync = function (p, o) {
|
||||||
|
if (!ready && process.env.DOCSTORE_URL && nameOf(p)) console.error('docstore: read before init', p, new Error().stack.split('\n')[2]);
|
||||||
|
const n = ready ? nameOf(p) : null; if (!n) return O.readFileSync.apply(fs, arguments);
|
||||||
|
const d = cache.get(n); if (!d) throw enoent(p);
|
||||||
|
return enc(o) ? d.body : Buffer.from(d.body, 'utf8');
|
||||||
|
};
|
||||||
|
fs.existsSync = function (p) { const n = ready ? nameOf(p) : null; return n ? cache.has(n) : O.existsSync.apply(fs, arguments); };
|
||||||
|
fs.writeFileSync = function (p, data, o) {
|
||||||
|
const n = ready ? nameOf(p) : null; if (!n) return O.writeFileSync.apply(fs, arguments);
|
||||||
|
const flag = o && typeof o === 'object' ? o.flag : null;
|
||||||
|
const s = Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
|
||||||
|
put(n, flag && flag[0] === 'a' ? ((cache.get(n) || {}).body || '') + s : s);
|
||||||
|
};
|
||||||
|
fs.appendFileSync = function (p, data) {
|
||||||
|
const n = ready ? nameOf(p) : null; if (!n) return O.appendFileSync.apply(fs, arguments);
|
||||||
|
put(n, ((cache.get(n) || {}).body || '') + (Buffer.isBuffer(data) ? data.toString('utf8') : String(data)));
|
||||||
|
};
|
||||||
|
fs.renameSync = function (a, b) {
|
||||||
|
const nb = ready ? nameOf(b) : null; const na = ready ? nameOf(a) : null;
|
||||||
|
if (!nb && !na) return O.renameSync.apply(fs, arguments);
|
||||||
|
let body;
|
||||||
|
if (na) { const d = cache.get(na); if (!d) throw enoent(a); body = d.body; drop(na); }
|
||||||
|
else { body = O.readFileSync.call(fs, a, 'utf8'); try { O.unlinkSync.call(fs, a); } catch (e) {} }
|
||||||
|
if (nb) put(nb, body); else O.writeFileSync.call(fs, b, body);
|
||||||
|
};
|
||||||
|
fs.unlinkSync = function (p) { const n = ready ? nameOf(p) : null; if (!n) return O.unlinkSync.apply(fs, arguments); if (!cache.has(n)) throw enoent(p); drop(n); };
|
||||||
|
fs.statSync = function (p, o) {
|
||||||
|
const n = ready ? nameOf(p) : null; if (!n) return O.statSync.apply(fs, arguments);
|
||||||
|
const d = cache.get(n); if (!d) { if (o && o.throwIfNoEntry === false) return undefined; throw enoent(p); }
|
||||||
|
const size = Buffer.byteLength(d.body, 'utf8'); const t = new Date(d.at);
|
||||||
|
return { size, mtimeMs: d.at, mtime: t, ctime: t, birthtime: t, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connect, claim writing, load every document, import files MySQL does not have yet. Throws if MySQL is unreachable: the app
|
||||||
|
// must not run on an empty copy.
|
||||||
|
async function init(opts) {
|
||||||
|
const url = String(process.env.DOCSTORE_URL || '').trim();
|
||||||
|
if (!url) { console.log('docstore: no DOCSTORE_URL, documents stay files (prototype mode)'); return false; }
|
||||||
|
const mysql = require('mysql2/promise');
|
||||||
|
pool = mysql.createPool({ uri: url, connectionLimit: 6, charset: 'utf8mb4' });
|
||||||
|
await pool.query('CREATE TABLE IF NOT EXISTS docs (name VARCHAR(190) PRIMARY KEY, body LONGTEXT NOT NULL, updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||||
|
await pool.query('CREATE TABLE IF NOT EXISTS docs_writer (id TINYINT PRIMARY KEY, owner VARCHAR(40) NOT NULL, at BIGINT NOT NULL) ENGINE=InnoDB');
|
||||||
|
await pool.query('INSERT INTO docs_writer (id, owner, at) VALUES (1, ?, ?) ON DUPLICATE KEY UPDATE owner = VALUES(owner), at = VALUES(at)', [ME, Date.now()]);
|
||||||
|
const [rows] = await pool.query('SELECT name, body, updated_at FROM docs');
|
||||||
|
for (const r of rows) { cache.set(r.name, { body: r.body, at: Number(r.updated_at) }); stored.set(r.name, r.body); }
|
||||||
|
for (const sp of (opts && opts.splits) || []) await openSplit(sp);
|
||||||
|
// first boot for any document: import its file, then set the file aside
|
||||||
|
const stamp = new Date().toISOString().slice(0, 10);
|
||||||
|
const walk = dir => { let out = []; let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) {} for (const e of ents) { const p = path.join(dir, e.name); if (e.isDirectory()) out = out.concat(walk(p)); else out.push(p); } return out; };
|
||||||
|
for (const p of walk(ROOT)) {
|
||||||
|
const n = nameOf(p); if (!n || cache.has(n)) continue;
|
||||||
|
const body = O.readFileSync.call(fs, p, 'utf8');
|
||||||
|
if (/\.json$/i.test(n) && body.trim()) { try { JSON.parse(body); } catch (e) { throw new Error('docstore: ' + n + ' is not valid JSON; fix or move it before switching to MySQL'); } }
|
||||||
|
await pool.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [n, body, Date.now()]);
|
||||||
|
const [[got]] = await pool.query('SELECT body FROM docs WHERE name = ?', [n]);
|
||||||
|
cache.set(n, { body: got.body, at: Date.now() }); stats.imported++;
|
||||||
|
O.renameSync.call(fs, p, p + '.imported-' + stamp);
|
||||||
|
}
|
||||||
|
for (const sp of (opts && opts.splits) || []) await migrateSplit(sp);
|
||||||
|
ready = true;
|
||||||
|
console.log('docstore: MySQL documents ready,', cache.size, 'documents,', stats.imported, 'imported from files this boot');
|
||||||
|
const shut = () => { flush().catch(() => {}).finally(() => {}); };
|
||||||
|
process.once('beforeExit', shut);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// ---- row tables: an ever-growing array (spin-link clicks) is one row per item, never a rewrite of the whole document ----
|
||||||
|
// spec { doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }. rows(table) gives the loaded items (oldest
|
||||||
|
// first); the module inserts / deletes rows itself and saves its document WITHOUT the field.
|
||||||
|
const ROWS = new Map(); const rowQ = []; let rowBusy = false;
|
||||||
|
async function openSplit(sp) {
|
||||||
|
await pool.query('CREATE TABLE IF NOT EXISTS `' + sp.table + '` (id VARCHAR(64) PRIMARY KEY, ts BIGINT NOT NULL, body MEDIUMTEXT NOT NULL, KEY ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||||
|
const [r] = await pool.query('SELECT body FROM `' + sp.table + '` ORDER BY ts, id');
|
||||||
|
ROWS.set(sp.table, r.map(x => JSON.parse(x.body)));
|
||||||
|
}
|
||||||
|
async function insertMany(table, items, key, ts) {
|
||||||
|
for (let i = 0; i < items.length; i += 500) {
|
||||||
|
const part = items.slice(i, i + 500);
|
||||||
|
await pool.query('INSERT INTO `' + table + '` (id, ts, body) VALUES ? ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [part.map(x => [String(x[key]), Number(x[ts]) || 0, JSON.stringify(x)])]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// first boot: the array still inside the document moves to its table, then the document is saved without it
|
||||||
|
async function migrateSplit(sp) {
|
||||||
|
const d = cache.get(sp.doc); if (!d) return;
|
||||||
|
let obj; try { obj = JSON.parse(d.body); } catch (e) { return; }
|
||||||
|
const arr = Array.isArray(obj[sp.field]) ? obj[sp.field] : null; if (!arr || !arr.length) return;
|
||||||
|
await insertMany(sp.table, arr, sp.key, sp.ts);
|
||||||
|
const [[{ n }]] = await pool.query('SELECT COUNT(*) n FROM `' + sp.table + '`');
|
||||||
|
if (n < arr.length) throw new Error('docstore: ' + sp.table + ' holds ' + n + ' rows after moving ' + arr.length + '; stopping before the document is changed');
|
||||||
|
const seen = new Set((ROWS.get(sp.table) || []).map(x => String(x[sp.key]))); const merged = (ROWS.get(sp.table) || []).concat(arr.filter(x => !seen.has(String(x[sp.key]))));
|
||||||
|
merged.sort((a, b) => (Number(a[sp.ts]) || 0) - (Number(b[sp.ts]) || 0)); ROWS.set(sp.table, merged);
|
||||||
|
obj[sp.field] = []; const body = JSON.stringify(obj);
|
||||||
|
await pool.query('UPDATE docs SET body = ?, updated_at = ? WHERE name = ?', [body, Date.now(), sp.doc]); cache.set(sp.doc, { body, at: Date.now() });
|
||||||
|
console.log('docstore:', arr.length, sp.field, 'moved from', sp.doc, 'to table', sp.table);
|
||||||
|
}
|
||||||
|
function rows(table) { return ROWS.get(table) || null; }
|
||||||
|
function rowOp(op) { if (!pool || !writer) return; rowQ.push(op); if (!rowBusy) runRows(); }
|
||||||
|
async function runRows() {
|
||||||
|
rowBusy = true;
|
||||||
|
try {
|
||||||
|
while (rowQ.length && writer) {
|
||||||
|
const op = rowQ[0];
|
||||||
|
try {
|
||||||
|
if (op.del) await pool.query('DELETE FROM `' + op.table + '` WHERE id IN (?)', [op.ids]);
|
||||||
|
else await pool.query('INSERT INTO `' + op.table + '` (id, ts, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [op.id, op.ts, op.body]);
|
||||||
|
rowQ.shift();
|
||||||
|
} catch (e) { stats.errors++; stats.lastError = String(e.message).slice(0, 200); await new Promise(r => setTimeout(r, 1000)); }
|
||||||
|
}
|
||||||
|
} finally { rowBusy = false; }
|
||||||
|
}
|
||||||
|
const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) });
|
||||||
|
const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); };
|
||||||
|
function isOn() { return ready && !!pool; }
|
||||||
|
// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true.
|
||||||
|
async function claim(key) {
|
||||||
|
if (!pool) return true;
|
||||||
|
await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB');
|
||||||
|
const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]);
|
||||||
|
return r.affectedRows === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SIGTERM during a deploy: write what is pending, then exit
|
||||||
|
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
|
||||||
|
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
|
||||||
|
const names = () => [...cache.keys()]; // every document name (the member erase walks them all, 2026-11-15)
|
||||||
|
// member erase (2026-11-15): count or delete the rows of a row table whose JSON body has `field` (e.g. '$.r') in `values`. Waits
|
||||||
|
// for queued row writes first, so a click queued before the erase cannot land after it.
|
||||||
|
async function rowsWhere(table, field, values, del) {
|
||||||
|
if (!pool || !values.length) return 0;
|
||||||
|
for (let i = 0; i < 100 && (rowQ.length || rowBusy); i++) await new Promise(r => setTimeout(r, 100));
|
||||||
|
const vals = values.map(String); const where = 'CAST(JSON_UNQUOTE(JSON_EXTRACT(body, ?)) AS CHAR) IN (?)';
|
||||||
|
if (!del) { const [[r]] = await pool.query('SELECT COUNT(*) n FROM `' + table + '` WHERE ' + where, [field, vals]); return Number(r.n); }
|
||||||
|
if (!writer) return 0;
|
||||||
|
const [r] = await pool.query('DELETE FROM `' + table + '` WHERE ' + where, [field, vals]);
|
||||||
|
const mem = ROWS.get(table); if (mem) { const k = field.replace(/^\$\./, ''); ROWS.set(table, mem.filter(x => !vals.includes(String(x[k])))); }
|
||||||
|
return Number(r.affectedRows || 0);
|
||||||
|
}
|
||||||
|
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim, names, rowsWhere };
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// The Stack POL page switch, read and written from stackpol.com/my (Marty approved the My Stack POL area 2026-11-19).
|
||||||
|
//
|
||||||
|
// ONE PLACE FOR THE SWITCH. The switch lives in InstantAdPay: its document stack-optin.json { users: { username: true|false },
|
||||||
|
// pro: { username: true } } (an IAP MySQL document), written by IAP's Promo tools > Stack POL toggle (POST /api/my/stackpol). The
|
||||||
|
// Stack POL indexer reads that document every 5 minutes. Stack POL never keeps a second copy: a switch made here is sent to IAP, which
|
||||||
|
// writes the same document with the same code, so the two can never disagree.
|
||||||
|
//
|
||||||
|
// THE INTERFACE IAP NEEDS (not built in IAP yet; until it is, configured() is false and /my links to IAP's Promo tools instead):
|
||||||
|
// POST <IAP_URL>/api/partner/stackpol/switch
|
||||||
|
// Headers: Content-Type: application/json
|
||||||
|
// X-Stack-Ts: milliseconds since 1970 (IAP refuses anything more than 5 minutes from its own clock)
|
||||||
|
// X-Stack-Sig: hex HMAC-SHA256(STACKPOL_SWITCH_KEY, X-Stack-Ts + "\n" + raw body)
|
||||||
|
// Body: { "email": "<the member's email, from their network sign-in>" } read only
|
||||||
|
// { "email": "...", "on": true|false } switch it
|
||||||
|
// IAP does: verify the signature and the time (timingSafeEqual), find the account by email (accounts.byEmail), refuse when there is
|
||||||
|
// none (404) or it has no username (409), then run the SAME code as /api/my/stackpol: so.users[un] = !!on when `on` is given, refresh
|
||||||
|
// so.pro[un] from gamepass.stackProView(email), write stack-optin.json atomically (tmp + rename), and answer
|
||||||
|
// 200 { "on": so.users[un] !== false, "username": un, "pro": !!pv.pro }.
|
||||||
|
// The secret is a new env on BOTH apps, the same value: STACKPOL_SWITCH_KEY (32+ characters). IAP_URL on Stack POL is optional
|
||||||
|
// (default https://instantadpay.com).
|
||||||
|
// Only Stack POL can call it (the key), only for the member signed in on Stack POL (the email comes from their verified hub token),
|
||||||
|
// and it changes nothing but the page switch.
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
const KEY = () => String(process.env.STACKPOL_SWITCH_KEY || '').trim();
|
||||||
|
const BASE = () => String(process.env.IAP_URL || 'https://instantadpay.com').trim().replace(/\/+$/, '');
|
||||||
|
const ROUTE = '/api/partner/stackpol/switch';
|
||||||
|
const configured = () => KEY().length >= 32 && /^https?:\/\/[a-z0-9.:-]+$/i.test(BASE());
|
||||||
|
const sign = (ts, raw) => crypto.createHmac('sha256', KEY()).update(ts + '\n' + raw).digest('hex');
|
||||||
|
|
||||||
|
// -> { ok: true, on, username, pro } or { ok: false, reason }
|
||||||
|
async function call(body, ms) {
|
||||||
|
if (!configured()) return { ok: false, reason: 'off' };
|
||||||
|
if (typeof fetch !== 'function') return { ok: false, reason: 'no fetch' };
|
||||||
|
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||||
|
const ac = new AbortController(); const tm = setTimeout(() => ac.abort(), ms || 3000);
|
||||||
|
try {
|
||||||
|
const r = await fetch(BASE() + ROUTE, { method: 'POST', body: raw, signal: ac.signal, headers: { 'Content-Type': 'application/json', 'X-Stack-Ts': ts, 'X-Stack-Sig': sign(ts, raw), 'User-Agent': 'stackpol-my' } });
|
||||||
|
let j = null; try { j = await r.json(); } catch (e) {}
|
||||||
|
if (r.status !== 200 || !j || typeof j.on !== 'boolean') return { ok: false, reason: 'iap ' + r.status + (j && j.error ? ': ' + String(j.error).slice(0, 120) : '') };
|
||||||
|
const un = String(j.username || '').toLowerCase();
|
||||||
|
return { ok: true, on: j.on, username: /^[a-z0-9_]{3,30}$/.test(un) ? un : null, pro: !!j.pro };
|
||||||
|
} catch (e) { return { ok: false, reason: 'iap unreachable' }; }
|
||||||
|
finally { clearTimeout(tm); }
|
||||||
|
}
|
||||||
|
const get = email => call({ email: String(email || '').toLowerCase() }, 2500);
|
||||||
|
const set = (email, on) => call({ email: String(email || '').toLowerCase(), on: !!on }, 5000);
|
||||||
|
// the deep link to IAP's own toggle (always works, needs no key)
|
||||||
|
const promoUrl = () => BASE() + '/my#promo?s=stackpol';
|
||||||
|
|
||||||
|
module.exports = { configured, get, set, promoUrl, sign, ROUTE };
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
// 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, netVer = '';
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
// does the question name a network site other than this one (hub site id `self`)? Then the home fast path stands aside and the
|
||||||
|
// answer comes from retrieval over the whole network (a "how much" about another site must not get this site's price).
|
||||||
|
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz',
|
||||||
|
downlinehydra: 'DownlineHydra', fivex: '5xYourTeam', stackpol: 'Stack POL', earnerscorner: 'Earners Corner' };
|
||||||
|
function namesOther(query, self) {
|
||||||
|
const q = norm(query); const out = [];
|
||||||
|
const ids = new Set(Object.keys(NAMES).concat(((index && index.sites) || []).map(s => s.site)));
|
||||||
|
for (const id of ids) {
|
||||||
|
if (id === self) continue;
|
||||||
|
const s = ((index && index.sites) || []).find(x => x.site === id) || {};
|
||||||
|
const names = [s.name, NAMES[id], id.length > 3 ? id : ''].concat(ALIASES[id] || []).filter(Boolean).map(norm);
|
||||||
|
if (names.some(n => n.trim() && q.includes(n))) out.push(id);
|
||||||
|
}
|
||||||
|
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 && (!netkb || netkb.version() === netVer)) return cache; // a new network set rebuilds at once
|
||||||
|
const all = await store().all();
|
||||||
|
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); rx.clear(); netVer = netkb ? netkb.version() : '';
|
||||||
|
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, namesOther, 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 } };
|
||||||
@@ -92,6 +92,25 @@ footer.site b{display:block;color:var(--ink);font:700 14px var(--display);margin
|
|||||||
.procta{display:flex;flex-wrap:wrap;gap:12px 16px;align-items:center;border:1px solid var(--violet);border-radius:18px;padding:18px 20px;margin:30px 0;background:linear-gradient(135deg,rgba(130,71,229,.16),transparent)}
|
.procta{display:flex;flex-wrap:wrap;gap:12px 16px;align-items:center;border:1px solid var(--violet);border-radius:18px;padding:18px 20px;margin:30px 0;background:linear-gradient(135deg,rgba(130,71,229,.16),transparent)}
|
||||||
.procta div{flex:1 1 280px;min-width:0}.procta b{display:block;font:800 18px var(--display);margin-bottom:4px}.procta span{color:var(--muted)}
|
.procta div{flex:1 1 280px;min-width:0}.procta b{display:block;font:800 18px var(--display);margin-bottom:4px}.procta span{color:var(--muted)}
|
||||||
@media (max-width:640px){.prorow{grid-template-columns:1fr}.qr{margin:0 auto}}
|
@media (max-width:640px){.prorow{grid-template-columns:1fr}.qr{margin:0 auto}}
|
||||||
|
.myvids{margin:28px 0}.vrow{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,220px));gap:14px}.vcard{position:relative;display:block;aspect-ratio:9/16;max-width:100%;border-radius:16px;overflow:hidden;background:var(--panel);border:1px solid var(--line);color:#fff;text-decoration:none}.vcard img{width:100%;height:100%;object-fit:cover;display:block}.vcard .vplay{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:54px;height:54px;border-radius:50%;background:rgba(20,10,40,.72);display:grid;place-items:center}.vcard b{position:absolute;left:0;right:0;bottom:0;padding:26px 10px 10px;font:700 13px/1.3 var(--body);background:linear-gradient(transparent,rgba(10,5,25,.85))}
|
||||||
|
/* My Stack POL (2026-11-19) */
|
||||||
|
nav.top a.mylink{color:#160b02;background:var(--gold);border-radius:999px;padding:3px 12px;margin-left:2px}nav.top a.mylink:hover,nav.top a.mylink[aria-current]{color:#160b02;background:#ffd27a}
|
||||||
|
.myhero{padding:26px 0 4px}.myhead{display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap}.soform{margin:0}
|
||||||
|
.mynote{border:1px solid var(--line);background:var(--panel);border-radius:12px;padding:10px 14px;margin:14px 0 0;max-width:72ch}.mynote.ok{border-color:rgba(74,222,128,.45)}.mynote.warn{border-color:rgba(255,194,75,.55)}
|
||||||
|
.mygrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px;margin-top:22px}@media (max-width:820px){.mygrid{grid-template-columns:1fr}}
|
||||||
|
.mycard+.tbl{margin-top:14px}.mycard{background:var(--panel);border:1px solid var(--line);border-radius:18px;padding:18px 20px;min-width:0}.mycard h2{font-size:21px}
|
||||||
|
.mct{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:12px}
|
||||||
|
.pill{font:700 12px var(--body);letter-spacing:.08em;text-transform:uppercase;border-radius:999px;padding:4px 11px;flex:none}.pill.on{background:rgba(74,222,128,.16);color:var(--ok)}.pill.off{background:var(--panel-2);color:var(--muted)}
|
||||||
|
.mysub{color:var(--muted);font-size:14px;margin:10px 0 0}.mono{font-family:var(--mono);font-size:12.5px}
|
||||||
|
.cprow{margin:0 0 10px}.cprow label{display:block;font-size:12.5px;color:var(--muted);margin:0 0 4px}
|
||||||
|
.cpbox{display:flex;gap:8px;min-width:0}.cpbox input,.cpbox textarea{flex:1;min-width:0;background:var(--ground);color:var(--ink);border:1px solid var(--line);border-radius:10px;padding:9px 11px;font:500 13px var(--mono);resize:none}
|
||||||
|
.cpb{flex:none;font:700 13px var(--body);color:var(--ink);background:var(--violet);border:0;border-radius:10px;padding:0 14px;cursor:pointer;min-height:38px}.cpb:focus-visible{outline:3px solid var(--violet-hi);outline-offset:2px}
|
||||||
|
.swform{margin:14px 0 6px}.swform .btn{cursor:pointer;border:0;font-size:15px;padding:11px 20px}.swform .btn.sec{border:1px solid var(--line)}.myhead .btn,.myfoot .btn{cursor:pointer;font-size:14px;padding:9px 16px}
|
||||||
|
.jlinks{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}@media (max-width:820px){.jlinks{grid-template-columns:1fr}}
|
||||||
|
.jl{background:var(--panel);border:1px solid var(--line);border-left:4px solid var(--c);border-radius:14px;padding:12px 14px 4px;min-width:0}.jn{display:flex;gap:8px;align-items:baseline;margin-bottom:8px;flex-wrap:wrap}.jn i{width:9px;height:9px;border-radius:3px;background:var(--c);display:inline-block}.jn b{font:700 15px var(--display)}.jn span{color:var(--muted);font-size:12.5px}
|
||||||
|
.kimgs{display:grid;grid-template-columns:1fr 1fr;gap:12px;align-content:start}.kimgs figure{margin:0}.kimgs img{width:100%;border-radius:10px;border:1px solid var(--line);aspect-ratio:1200/630;object-fit:cover;display:block}.kimgs figcaption{font-size:12.5px;color:var(--muted);margin-top:6px}
|
||||||
|
.kqr{display:flex;gap:12px;align-items:center;margin-top:6px}.kqr img{background:#fff;border-radius:10px;padding:6px}.kqr span{font-size:13px;color:var(--muted)}
|
||||||
|
.myfoot{display:flex;gap:16px;align-items:center;flex-wrap:wrap;margin-top:34px}.myfoot form{margin:0}.linkbtn{background:none;border:0;color:var(--violet-hi);font:600 14px var(--body);cursor:pointer;text-decoration:underline;padding:0}
|
||||||
@media (prefers-reduced-motion:reduce){.card,.btn{transition:none}.card:hover{transform:none}}
|
@media (prefers-reduced-motion:reduce){.card,.btn{transition:none}.card:hover{transform:none}}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -118,7 +137,10 @@ function head(o) {
|
|||||||
+ (o.jsonld || []).map(j => '<script type="application/ld+json">' + JSON.stringify(j).replace(/</g, '\\u003c') + '</script>').join('')
|
+ (o.jsonld || []).map(j => '<script type="application/ld+json">' + JSON.stringify(j).replace(/</g, '\\u003c') + '</script>').join('')
|
||||||
+ '</head><body><div class="wrap">'
|
+ '</head><body><div class="wrap">'
|
||||||
+ '<header class="bar"><a class="logo" href="/" aria-label="Stack POL home">' + LOGO + 'Stack POL</a>'
|
+ '<header class="bar"><a class="logo" href="/" aria-label="Stack POL home">' + LOGO + 'Stack POL</a>'
|
||||||
+ '<nav class="top" aria-label="Main">' + [['/', 'Home'], ['/programs', 'Programs'], ['/ledger', 'Ledger'], ['/blog', 'Blog']].map(([h, l]) => '<a href="' + h + '"' + (o.nav === h ? ' aria-current="page"' : '') + '>' + l + '</a>').join('') + '</nav></header>';
|
+ '<nav class="top" aria-label="Main">' + [['/', 'Home'], ['/programs', 'Programs'], ['/ledger', 'Ledger'], ['/blog', 'Blog']].map(([h, l]) => '<a href="' + h + '"' + (o.nav === h ? ' aria-current="page"' : '') + '>' + l + '</a>').join('')
|
||||||
|
// My Stack POL (2026-11-19): pages are cached for everyone, so the label comes from the sp.in cookie (no data in it, set by /my)
|
||||||
|
+ '<a class="mylink" id="spmy" href="/my"' + (o.nav === '/my' ? ' aria-current="page"' : '') + ' rel="nofollow">Sign in</a></nav>'
|
||||||
|
+ '<script>(function(){if(/(?:^|; )sp\\.in=1/.test(document.cookie)){var a=document.getElementById("spmy");if(a)a.textContent="My Stack POL";}})();</script></header>';
|
||||||
}
|
}
|
||||||
// a LinkSpin zone spot. wide = zone for screens 760px and up, narrow = zone below that; only the one that fits is loaded, so a
|
// a LinkSpin zone spot. wide = zone for screens 760px and up, narrow = zone below that; only the one that fits is loaded, so a
|
||||||
// hidden size never counts a view. Zones are on Marty's LinkSpin account, site stackpol.com (created 2026-11-09).
|
// hidden size never counts a view. Zones are on Marty's LinkSpin account, site stackpol.com (created 2026-11-09).
|
||||||
@@ -150,7 +172,7 @@ function personalize(html, who, st) {
|
|||||||
// it on as ?ref=); Earners Corner (nwec) takes none
|
// it on as ?ref=); Earners Corner (nwec) takes none
|
||||||
if (/^https:\/\/linkspin\.app\/r\/nw[a-z]+\?/.test(h) && !/[?&](?:amp;)?s1=/.test(h)) return /\/r\/nwec\?/.test(h) ? m : 'href="' + h + '&s1=' + who + '"';
|
if (/^https:\/\/linkspin\.app\/r\/nw[a-z]+\?/.test(h) && !/[?&](?:amp;)?s1=/.test(h)) return /\/r\/nwec\?/.test(h) ? m : 'href="' + h + '&s1=' + who + '"';
|
||||||
if (/^https:\/\/(instantadpay\.com|linkspin\.app)\//.test(h)) return 'href="' + h.replace(/\/join\/martbost\b/, '/join/' + who).replace(/([?&](?:amp;)?ref=)martbost\b/, '$1' + who).replace(/([?&](?:amp;)?s1=)martbost\b/, '$1' + who) + '"'; // s1 = the member on a LinkSpin network link (nwvbb, 2026-11-15)
|
if (/^https:\/\/(instantadpay\.com|linkspin\.app)\//.test(h)) return 'href="' + h.replace(/\/join\/martbost\b/, '/join/' + who).replace(/([?&](?:amp;)?ref=)martbost\b/, '$1' + who).replace(/([?&](?:amp;)?s1=)martbost\b/, '$1' + who) + '"'; // s1 = the member on a LinkSpin network link (nwvbb, 2026-11-15)
|
||||||
if (/^https:\/\/(downlinebanners\.com|viralbannerblitz\.com|viraladblitz\.com)\//.test(h)) return 'href="' + h.replace(/([?&](?:amp;)?ref=)martbost\b/, '$1' + who) + '"';
|
if (/^https:\/\/(downlinebanners\.com|viralbannerblitz\.com|viraladblitz\.com|viraladsource\.com|yourprogrambuilder\.com|videoappincome\.com|5xyourteam\.com|downlinehydra\.com)\//.test(h)) return 'href="' + h.replace(/([?&](?:amp;)?ref=)martbost\b/, '$1' + who) + '"';
|
||||||
return m;
|
return m;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -165,18 +187,28 @@ function memberLinks(who, st) {
|
|||||||
const links = (st && st.pro && st.pro.links) || []; if (!links.length) return '';
|
const links = (st && st.pro && st.pro.links) || []; if (!links.length) return '';
|
||||||
return '<div class="mylinks"><p class="kick">@' + esc(who) + ' recommends</p><div class="ml">' + links.map(l => '<a class="chip" href="https://' + MEMBER_HOST + '/r/' + esc(l.code) + '" target="_blank" rel="sponsored noopener">' + esc(l.name || 'Open link') + ' →</a>').join('') + '</div></div>';
|
return '<div class="mylinks"><p class="kick">@' + esc(who) + ' recommends</p><div class="ml">' + links.map(l => '<a class="chip" href="https://' + MEMBER_HOST + '/r/' + esc(l.code) + '" target="_blank" rel="sponsored noopener">' + esc(l.name || 'Open link') + ' →</a>').join('') + '</div></div>';
|
||||||
}
|
}
|
||||||
|
// Stack POL Pro (Marty 2026-11-23): the member's LinkSpin Video Spin. One short link that opens a different one of their Social Tube
|
||||||
|
// videos each visit (made on Video App Income); LinkSpin counts the plays. Up to three posters, every one opens the same spin link.
|
||||||
|
function memberVideos(who, st) {
|
||||||
|
const v = st && st.pro && st.pro.video; if (!v || !/^[A-Za-z0-9]{3,20}$/.test(v.code || '')) return '';
|
||||||
|
const url = 'https://' + MEMBER_HOST + '/r/' + v.code, ps = (v.posters || []).filter(p => /^https:\/\/socialtube\.club\//.test(p.poster || '')).slice(0, 3);
|
||||||
|
const a = inner => '<a class="vcard" href="' + url + '" target="_blank" rel="noopener">' + inner + '</a>';
|
||||||
|
const play = '<span class="vplay" aria-hidden="true"><svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg></span>';
|
||||||
|
const cards = ps.length ? ps.map(p => a('<img src="' + esc(p.poster) + '" alt="' + esc(p.label || 'Video') + '" loading="lazy">' + play + (p.label ? '<b>' + esc(p.label) + '</b>' : ''))).join('') : a(play + '<b>' + esc(v.name || 'Watch a video') + '</b>');
|
||||||
|
return '<div class="myvids"><div class="sec-head"><h2>Watch @' + esc(who) + '\'s videos</h2><p>' + (v.count > 1 ? v.count + ' short videos. Each tap opens a different one.' : 'A short video, made on a phone.') + '</p></div><div class="vrow">' + cards + '</div></div>';
|
||||||
|
}
|
||||||
function tail(extra) {
|
function tail(extra) {
|
||||||
const year = new Date().getFullYear();
|
const year = new Date().getFullYear();
|
||||||
return '<footer class="site"><div><b>Stack POL</b>Every POL payout across the network, stacked in one place and checkable on Polygon.</div>'
|
return '<footer class="site"><div><b>Stack POL</b>Every POL payout across the network, stacked in one place and checkable on Polygon.</div>'
|
||||||
+ '<div><b>Explore</b><a href="/programs">All programs</a><a href="/ledger">Live ledger</a><a href="/blog">Blog</a><a href="/blog/feed.xml">RSS feed</a><a href="https://instantadpay.com/games" rel="noopener">All games</a><a href="https://instantadpay.com/support" rel="noopener">Support</a></div>'
|
+ '<div><b>Explore</b><a href="/programs">All programs</a><a href="/ledger">Live ledger</a><a href="/blog">Blog</a><a href="/blog/feed.xml">RSS feed</a><a href="https://instantadpay.com/games" rel="noopener">All games</a><a href="https://instantadpay.com/support" rel="noopener">Support</a><a href="/terms">Terms</a><a href="/disclaimer">Earnings disclaimer</a><a href="/privacy">Privacy</a></div>'
|
||||||
// Part of the network (Marty 2026-11-14 trust pack): the list comes from the hub (netsites.js, cached), built-in copy if not
|
// Part of the network (Marty 2026-11-14 trust pack): the list comes from the hub (netsites.js, cached), built-in copy if not
|
||||||
+ '<div><b>Part of the network</b><span style="display:block;margin-bottom:4px">One account across the network</span>' + netsites.list().map(s => (s.id === 'stackpol' || /stackpol\.com/.test(s.url))
|
+ '<div><b>Part of the network</b><span style="display:block;margin-bottom:4px">One account across the network</span>' + netsites.list().map(s => (s.id === 'stackpol' || /stackpol\.com/.test(s.url))
|
||||||
? '<span aria-current="page" style="display:block;margin:3px 0;color:var(--ink);font-weight:600">' + esc(s.name) + ' (you are here)</span>'
|
? '<span aria-current="page" style="display:block;margin:3px 0;color:var(--ink);font-weight:600">' + esc(s.name) + ' (you are here)</span>'
|
||||||
: '<a href="' + esc(netsites.tracked(s.id, 'stackpol') || s.url) + '" rel="noopener nofollow">' + esc(s.name) + '</a>').join('') + '</div>'
|
: '<a href="' + esc(netsites.tracked(s.id, 'stackpol') || s.url) + '" rel="noopener nofollow">' + esc(s.name) + '</a>').join('') + '</div>'
|
||||||
+ '<div><b>Honest numbers</b>Totals are the combined payouts of everyone in the network, read from each program\'s payout records and the Polygon chain. One member\'s results are not a promise of yours. Cryptocurrency involves risk.</div></footer>'
|
+ '<div><b>Honest numbers</b>Totals are the combined payouts of everyone in the network, read from each program\'s payout records and the Polygon chain. One member\'s results are not a promise of yours. Cryptocurrency involves risk.</div></footer>'
|
||||||
+ '<p class="disc">© ' + year + ' Stack POL by TrustClickz, 615 Green Valley Drive, Moody, AL 35004. Part of the Crypto Team Build Network. Stack POL shows payouts; it does not hold, invest or pay out anyone\'s money.</p>'
|
+ '<p class="disc">© ' + year + ' Stack POL by TrustClickz. Part of the Crypto Team Build Network. Stack POL shows payouts; it does not hold, invest or pay out anyone\'s money.</p>'
|
||||||
// PolHunter mission (Marty 2026-11-10): silent unless a hunter arrives with their own #ph token; the code lands on one of the
|
// PolHunter mission (Marty 2026-11-10): silent unless a hunter arrives with their own #ph token; the code lands on one of the
|
||||||
// program cards (3 slots, which one rotates per hunter per day)
|
// program cards (3 slots, which one rotates per hunter per day)
|
||||||
+ '</div>' + (extra || '') + SPOT_JS + '<script src="https://polhunter.com/embed.js" data-slots="3" data-selector=".card" async></script></body></html>';
|
+ '</div>' + (extra || '') + SPOT_JS + '<script src="https://polhunter.com/embed.js" data-slots="3" data-selector=".card" async></script><script src="/assets/chat.js?v=hide1" defer></script><script src="/assets/netweekend.js?v=20261117" data-site="stackpol" defer></script></body></html>';
|
||||||
}
|
}
|
||||||
module.exports = { SITE, esc, head, tail, OG, V, ZONES, spot, personalize, memberLinks, proCta, MEMBER_HOST };
|
module.exports = { SITE, esc, head, tail, OG, V, ZONES, spot, personalize, memberLinks, memberVideos, proCta, MEMBER_HOST };
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
'use strict';
|
||||||
|
// Terms, Privacy and Earnings disclaimer pages (2026-11-17 network tidy-up, same structure as the other network sites).
|
||||||
|
// Operator is named TrustClickz only: no street address on site pages (Marty 2026-11-16).
|
||||||
|
const { head, tail } = require('./layout');
|
||||||
|
|
||||||
|
const UPDATED = 'November 17, 2026';
|
||||||
|
const SUPPORT = '<a href="https://instantadpay.com/support" rel="noopener">network support</a> (TrustClickz)';
|
||||||
|
const sec = (h, ...ps) => '<h2>' + h + '</h2>' + ps.map(p => '<p>' + p + '</p>').join('');
|
||||||
|
|
||||||
|
const PAGES = {
|
||||||
|
'/terms': {
|
||||||
|
title: 'Terms and Conditions | Stack POL', h1: 'Stack POL Terms and Conditions', lead: 'The rules for using Stack POL, in plain English.',
|
||||||
|
desc: 'The terms for using stackpol.com, the public POL payout ledger of the network.',
|
||||||
|
body: [
|
||||||
|
sec('Who we are', 'Stack POL (stackpol.com) is run by TrustClickz. It is part of the network: one network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, ViralAdSource, DownlineHydra, 5xYourTeam, Stack POL and Earners Corner. By using Stack POL you agree to these terms.'),
|
||||||
|
sec('What Stack POL is', 'Stack POL is a public, read-only ledger. It collects the POL payouts made by the programs in the network from each program\'s payout records and the Polygon blockchain, adds them up, and links every row to its transaction on Polygonscan. It also has program pages, a blog and an assistant that answers questions about the network.'),
|
||||||
|
sec('Stack POL does not hold money', 'Stack POL does not sell anything, take payments, hold funds, invest for anyone or pay anyone. Every payout shown was made by the program named on the row. Questions about a payout go to that program.'),
|
||||||
|
sec('Member pages', 'A member\'s own Stack POL page is off until the member switches it on in InstantAdPay Promo tools. A Pro page (your banners, links and QR code) is unlocked through an InstantAdPay ad package, bought and governed on InstantAdPay under its terms. You can ask for your page to be switched off at any time.'),
|
||||||
|
sec('Accuracy', 'We work to keep the totals correct and refresh them every few minutes, but they can be late or incomplete, and a program may change or stop. The Polygon blockchain is the record that counts: check any row there.'),
|
||||||
|
sec('Nothing is promised', 'The numbers show what has been paid to members in the past. They are not a promise, forecast or typical result of what you will receive. Read the <a href="/disclaimer">Earnings Disclaimer</a>.'),
|
||||||
|
sec('Crypto risk', 'The price of POL moves. The dollar value of a payout can be higher or lower later than when it was paid. Blockchain transactions are final. You are responsible for your own wallet and its recovery phrase; never share it with anyone. We will never ask for it.'),
|
||||||
|
sec('Links and ads', 'Stack POL links to the network programs and carries network ad zones and member banners. Those sites and ads are run by others under their own terms. We are not responsible for third-party websites.'),
|
||||||
|
sec('Fair use', 'Do not try to break, overload or scrape the site at a rate that harms it. The public data feeds may be rate limited.'),
|
||||||
|
sec('The service', 'The site is provided as it is. We may change features or these terms; changes apply from the date they are posted here.'),
|
||||||
|
sec('Limits', 'As far as the law allows, we are not responsible for losses caused by the blockchain, your wallet, the price of POL, the programs listed, third-party websites, or events outside our control. These terms are governed by the laws of the State of Alabama, USA.'),
|
||||||
|
sec('Contact', 'Questions, problems or a request about your data: ' + SUPPORT + '.')
|
||||||
|
]
|
||||||
|
},
|
||||||
|
'/privacy': {
|
||||||
|
title: 'Privacy Policy | Stack POL', h1: 'Stack POL Privacy Policy', lead: 'What Stack POL keeps about you, why, and for how long.',
|
||||||
|
desc: 'What stackpol.com keeps about visitors and members.',
|
||||||
|
body: [
|
||||||
|
sec('Who we are', 'Stack POL is run by TrustClickz.'),
|
||||||
|
sec('What we show', 'Payout rows from the network programs: the program, the amount in POL, the date, the transaction and the receiving member\'s network username or a shortened wallet. This information is already public on the Polygon blockchain or in the program\'s own public ledger. A member page appears only after the member switches it on.'),
|
||||||
|
sec('What we keep', 'Stack POL has no accounts and no sign-in, and it does not store your email. Questions you ask the site assistant are answered and not stored with anything that identifies you; your internet address is held in memory for a short time only to limit how often the assistant can be asked.'),
|
||||||
|
sec('Cookies', 'Stack POL sets no cookies of its own. Pages and embeds from other services may set their own.'),
|
||||||
|
sec('Who else sees data', 'The Polygon blockchain: every payout is public there, by its nature. Services the pages load: Google Fonts, LinkSpin network ad zones and member banners, the PolHunter mission script and the network hub\'s shared assistant knowledge. We do not sell personal data.'),
|
||||||
|
sec('Your choices', 'You can switch your member page off in InstantAdPay Promo tools or ask us to remove it. Records on the blockchain cannot be removed by anyone.'),
|
||||||
|
sec('Contact', 'Questions, problems or a request about your data: ' + SUPPORT + '.')
|
||||||
|
]
|
||||||
|
},
|
||||||
|
'/disclaimer': {
|
||||||
|
title: 'Earnings Disclaimer | Stack POL', h1: 'Stack POL Earnings Disclaimer', lead: 'Real payouts, not promises.',
|
||||||
|
desc: 'The numbers on stackpol.com show past payouts, not a promise of results.',
|
||||||
|
body: [
|
||||||
|
sec('What the numbers are', 'Every total, ledger row and member page on Stack POL shows what the programs in the network really paid in the past, read from their payout records and the Polygon blockchain. They are combined across everyone in the network.'),
|
||||||
|
sec('Not a promise', 'None of it is a promise, forecast or typical result of what you will receive. One member\'s results are not a promise of yours. Many people receive nothing or less than they spend. Your results depend on the program, what you do and other people\'s free choices.'),
|
||||||
|
sec('Not advice', 'Stack POL is not financial, investment or tax advice, and listing a program is not a recommendation to spend money in it. Read each program\'s own terms and earnings disclaimer before you buy anything.'),
|
||||||
|
sec('Prices and taxes', 'Payouts are in POL, whose price moves, so their dollar value can change. You are responsible for any taxes on what you receive where you live.'),
|
||||||
|
sec('Who to ask', 'TrustClickz. ' + SUPPORT.replace('network support', 'Network support').replace(' (TrustClickz)', '') + '.')
|
||||||
|
]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function render(p) {
|
||||||
|
const d = PAGES[p]; if (!d) return null;
|
||||||
|
return head({ title: d.title, desc: d.desc, path: p })
|
||||||
|
+ '<div class="bl"><article style="padding:28px 0 10px"><p class="kick">Last updated ' + UPDATED + '</p><h1>' + d.h1 + '</h1><p class="lead">' + d.lead + '</p>'
|
||||||
|
+ d.body.join('') + '</article></div>' + tail();
|
||||||
|
}
|
||||||
|
module.exports = { render, PATHS: Object.keys(PAGES) };
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
// My Stack POL (Marty approved 2026-11-19: "why is there no login to get to their links and other stuff"). The signed-in member area
|
||||||
|
// at /my. Sign-in is the network sign-in through the hub (networksso.js, the same file as every rebuilt site): no passwords, no local
|
||||||
|
// accounts. Public pages, the ledger, totals and the blog never need it.
|
||||||
|
//
|
||||||
|
// Session: a signed cookie sp.sid ("v1.<base64url JSON {e, w, n, iat, exp}>.<HMAC-SHA256>", 7 days, HttpOnly, SameSite=Lax) keyed off
|
||||||
|
// HUB_SECRET, so there is no session table to lose. Sign out ends every Stack POL session of that member: my-signouts.json
|
||||||
|
// { sha256(email): ms } (a MySQL document through docstore.js) refuses any cookie issued before it. sp.in=1 (not HttpOnly, no data)
|
||||||
|
// only tells the header to say "My Stack POL" instead of "Sign in" on cached public pages.
|
||||||
|
// Who the member is here: their IAP username (what stackpol.com/<username> and the ledger use). IAP's own answer when the switch
|
||||||
|
// interface is on (iapswitch.js), else the wallet their network sign-in carries matched against the indexer's wallet list, else their
|
||||||
|
// network username.
|
||||||
|
// What /my shows comes from the last indexer snapshot (IDX.my, see tools/indexer.py): their own payout rows and totals exactly as the
|
||||||
|
// ledger has them, their page switch, Pro (IAP's rule, mirrored in stack-optin.json pro), and their join links (programs.js, the same
|
||||||
|
// links their public page uses).
|
||||||
|
// The switch: iapswitch.js. A switch made here is also remembered in my-switch.json { username: { on, at } } until the next snapshot
|
||||||
|
// (newer than `at`) carries IAP's answer, so a switch-off hides the public page at once, not 5 minutes later.
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const iapswitch = require('./iapswitch');
|
||||||
|
|
||||||
|
let D = null; // { idx(), PROGRAMS, BY_KEY, head, tail, esc, fmt, fmtInt, when, ledgerRows, tableHead, SITE, dataDir, qr }
|
||||||
|
const AGE = 7 * 86400; // seconds
|
||||||
|
const NAME_RE = /^[a-z0-9_]{3,30}$/;
|
||||||
|
const WALLET_RE = /^0x[0-9a-f]{40}$/;
|
||||||
|
const BOOT_KEY = crypto.randomBytes(32); // local runs without HUB_SECRET: sessions last until a restart
|
||||||
|
const skey = () => { const h = String(process.env.HUB_SECRET || '').trim(); return h.length >= 32 ? crypto.createHmac('sha256', h).update('stackpol.session.v1').digest() : BOOT_KEY; };
|
||||||
|
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||||
|
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||||
|
const mac = s => crypto.createHmac('sha256', skey()).update('spsess.v1.' + s).digest();
|
||||||
|
const ehash = e => crypto.createHash('sha256').update(String(e || '').toLowerCase()).digest('hex');
|
||||||
|
const isProd = () => /^https:/.test(D ? D.SITE : '');
|
||||||
|
const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (isProd() ? '; Secure' : '');
|
||||||
|
|
||||||
|
function init(deps) { D = deps; }
|
||||||
|
function cookies(req) {
|
||||||
|
const out = {};
|
||||||
|
for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// ---- documents (MySQL through docstore, files in DATA_DIR locally) ----
|
||||||
|
const docPath = n => path.join(D.dataDir, n);
|
||||||
|
function readDoc(n) { try { return JSON.parse(fs.readFileSync(docPath(n), 'utf8')) || {}; } catch (e) { return {}; } }
|
||||||
|
function writeDoc(n, o) { const f = docPath(n); fs.writeFileSync(f + '.tmp', JSON.stringify(o)); fs.renameSync(f + '.tmp', f); }
|
||||||
|
|
||||||
|
// ---- session ----
|
||||||
|
function mintSession(o) {
|
||||||
|
const now = Date.now();
|
||||||
|
const t = { e: String(o.email || '').toLowerCase(), iat: now, exp: now + AGE * 1000 };
|
||||||
|
if (o.wallet && WALLET_RE.test(String(o.wallet).toLowerCase())) t.w = String(o.wallet).toLowerCase();
|
||||||
|
if (o.name && /^[A-Za-z0-9_.-]{1,40}$/.test(String(o.name))) t.n = String(o.name);
|
||||||
|
const body = b64u(JSON.stringify(t));
|
||||||
|
return ck('sp.sid', 'v1.' + body + '.' + b64u(mac(body)), AGE, true);
|
||||||
|
}
|
||||||
|
// -> { email, address, name, iat } or null
|
||||||
|
function session(req) {
|
||||||
|
const m = /^v1\.([A-Za-z0-9_-]{10,1500})\.([A-Za-z0-9_-]{43})$/.exec(cookies(req)['sp.sid'] || '');
|
||||||
|
if (!m) return null;
|
||||||
|
const want = mac(m[1]), got = unb64u(m[2]);
|
||||||
|
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return null;
|
||||||
|
let t; try { t = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return null; }
|
||||||
|
if (!t || !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(t.e || '')) || !(Number(t.exp) > Date.now())) return null;
|
||||||
|
const out = Number(readDoc('my-signouts.json')[ehash(t.e)] || 0);
|
||||||
|
if (Number(t.iat) <= out) return null; // signed out after this cookie was made
|
||||||
|
return { email: t.e, address: t.w || null, name: t.n || null, iat: Number(t.iat) };
|
||||||
|
}
|
||||||
|
function signOut(email) {
|
||||||
|
const so = readDoc('my-signouts.json'); so[ehash(email)] = Date.now(); writeDoc('my-signouts.json', so);
|
||||||
|
}
|
||||||
|
const clearCookies = () => [ck('sp.sid', '', 0, true), ck('sp.in', '', 0, false)];
|
||||||
|
|
||||||
|
// ---- who and what ----
|
||||||
|
let wIdx = { of: null, map: new Map() };
|
||||||
|
function walletUser(w) {
|
||||||
|
const idx = D.idx(); if (!idx || !w) return null;
|
||||||
|
if (wIdx.of !== idx) { const map = new Map(); for (const [un, m] of Object.entries((idx.my && idx.my.members) || {})) for (const a of m.wallets || []) if (!map.has(a)) map.set(a, un); wIdx = { of: idx, map }; }
|
||||||
|
return wIdx.map.get(String(w).toLowerCase()) || null;
|
||||||
|
}
|
||||||
|
// the switch made on /my that the snapshot has not caught up with yet (null when the snapshot is newer)
|
||||||
|
function pendingSwitch(un) {
|
||||||
|
const x = readDoc('my-switch.json')[un]; const idx = D.idx();
|
||||||
|
if (!x || typeof x.on !== 'boolean') return null;
|
||||||
|
if (idx && Number(idx.at) > Number(x.at)) return null;
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
// a public page the member switched off here: hidden before the next snapshot shows it (server.js asks)
|
||||||
|
const hiddenNow = un => { const x = pendingSwitch(un); return !!(x && x.on === false); };
|
||||||
|
|
||||||
|
async function view(s) {
|
||||||
|
const idx = D.idx() || {}; const my = idx.my || {};
|
||||||
|
const live = iapswitch.configured() ? await iapswitch.get(s.email) : { ok: false, reason: 'off' };
|
||||||
|
const byName = s.name && NAME_RE.test(String(s.name).toLowerCase()) ? String(s.name).toLowerCase() : null;
|
||||||
|
const un = (live.ok && live.username) || walletUser(s.address) || byName;
|
||||||
|
if (!un) return { un: null, live };
|
||||||
|
const m = (my.members || {})[un] || null;
|
||||||
|
const stack = (idx.stacks || {})[un] || null;
|
||||||
|
const pend = pendingSwitch(un);
|
||||||
|
const explicit = (my.switch || {})[un];
|
||||||
|
const on = live.ok ? live.on : pend ? pend.on : explicit !== false;
|
||||||
|
const pro = live.ok ? live.pro : (my.pro || []).includes(un) || !!(stack && stack.pro);
|
||||||
|
const pageLive = on && !!stack && !(pend && pend.on === false);
|
||||||
|
return { un, m, stack, on, pro, pageLive, live, pend, wallets: m && m.wallets && m.wallets.length ? m.wallets : (s.address ? [s.address] : []) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the page ----
|
||||||
|
const COPY_JS = '<script>(function(){document.querySelectorAll("[data-copy]").forEach(function(b){b.addEventListener("click",function(){var t=document.getElementById(b.getAttribute("data-copy"));if(!t)return;var v=t.value||t.textContent;var done=function(){var o=b.textContent;b.textContent="Copied";setTimeout(function(){b.textContent=o;},1600);};if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(v).then(done,function(){t.select&&t.select();document.execCommand("copy");done();});}else{t.select&&t.select();document.execCommand("copy");done();}});});})();</script>';
|
||||||
|
const copyRow = (id, value, label) => '<div class="cprow">' + (label ? '<label for="' + id + '">' + D.esc(label) + '</label>' : '') + '<div class="cpbox"><input id="' + id + '" type="text" readonly value="' + D.esc(value) + '" spellcheck="false"><button type="button" class="cpb" data-copy="' + id + '">Copy</button></div></div>';
|
||||||
|
|
||||||
|
function signedOutPage(q) {
|
||||||
|
let h = D.head({ title: 'My Stack POL: Sign In | Stack POL', desc: 'Sign in with your network account to see your Stack POL page, your join links and your own payouts.', path: '/my', nav: '/my', noindex: true });
|
||||||
|
h += '<section class="myhero"><p class="kick">My Stack POL</p><h1>Your page, your links, your payouts</h1>'
|
||||||
|
+ '<p class="lead">Sign in with the account you already use across the network (InstantAdPay, LinkSpin and the rest). No new password, nothing to set up.</p>';
|
||||||
|
if (q.out) h += '<p class="mynote ok">You are signed out of Stack POL.</p>';
|
||||||
|
if (q.signin === 'none') h += '<p class="mynote">This browser is not signed in anywhere in the network yet. Sign in on InstantAdPay and it brings you straight back here.</p>';
|
||||||
|
h += '<div class="cta"><a class="btn" href="/sso/start?mode=go&to=%2Fmy" rel="nofollow">Sign in with your network account</a>'
|
||||||
|
+ '<a class="btn sec" href="https://instantadpay.com/my?return=stackpol&to=%2Fmy" rel="nofollow noopener">Sign in on InstantAdPay</a></div>'
|
||||||
|
+ '<p class="fine" style="max-width:60ch;margin-top:16px">New here? <a href="https://instantadpay.com/join/martbost?src=stackpol" rel="noopener">Join InstantAdPay free</a>. Your Stack POL page lives at stackpol.com/your-username once your first payout lands.</p></section>';
|
||||||
|
return h + D.tail();
|
||||||
|
}
|
||||||
|
|
||||||
|
function memberPage(s, v, q) {
|
||||||
|
const { esc, fmt, fmtInt, PROGRAMS, BY_KEY } = D;
|
||||||
|
let h = D.head({ title: 'My Stack POL | Stack POL', desc: 'Your Stack POL page, join links, share kit and payouts.', path: '/my', nav: '/my', noindex: true });
|
||||||
|
const un = v.un;
|
||||||
|
h += '<section class="myhero"><div class="myhead"><div class="who"><span class="av">' + esc((un || s.email)[0].toUpperCase()) + '</span><div><b>' + (un ? '@' + esc(un) : 'Signed in') + '</b><span>Signed in with your network account</span></div></div>'
|
||||||
|
+ '<form method="post" action="/api/my/signout" class="soform"><button class="btn sec" type="submit">Sign out</button></form></div>';
|
||||||
|
if (q.sw === 'err') h += '<p class="mynote warn">That switch did not go through. InstantAdPay did not answer; nothing changed. Try again in a minute, or use the switch in InstantAdPay Promo tools.</p>';
|
||||||
|
if (q.sw === 'ok') h += '<p class="mynote ok">Saved in InstantAdPay. Your page ' + (v.on ? 'is switched on' : 'is switched off') + '.</p>';
|
||||||
|
h += '</section>';
|
||||||
|
if (!un) {
|
||||||
|
h += '<section class="mycard"><h2>Pick a username first</h2><p class="lead">Your Stack POL page lives at stackpol.com/your-username, the username on your InstantAdPay account. This account does not have one we can see yet.</p><div class="cta"><a class="btn" href="https://instantadpay.com/my" rel="noopener">Open InstantAdPay</a></div></section>';
|
||||||
|
return h + D.tail();
|
||||||
|
}
|
||||||
|
const pageUrl = D.SITE + '/' + un;
|
||||||
|
const m = v.m;
|
||||||
|
// 1. the page and its switch
|
||||||
|
h += '<div class="mygrid"><section class="mycard"><div class="mct"><h2>Your Stack POL page</h2><span class="pill ' + (v.on ? 'on' : 'off') + '">' + (v.on ? 'On' : 'Off') + '</span></div>';
|
||||||
|
h += copyRow('pageurl', pageUrl);
|
||||||
|
if (v.pageLive) h += '<p class="mysub">Live now. <a href="/' + esc(un) + '" target="_blank" rel="noopener">Open your page</a></p>';
|
||||||
|
else if (!v.on) h += '<p class="mysub">Switched off: stackpol.com/' + esc(un) + ' shows "not switched on" and the ledger lists your payouts without a link.</p>';
|
||||||
|
else if (!m) h += '<p class="mysub">Switched on. Your page goes live with your first payout on the ledger.</p>';
|
||||||
|
else h += '<p class="mysub">Switched on. Your page shows on the next ledger refresh (every 5 minutes).</p>';
|
||||||
|
if (iapswitch.configured()) {
|
||||||
|
h += '<form method="post" action="/api/my/switch" class="swform"><input type="hidden" name="on" value="' + (v.on ? '0' : '1') + '"><button class="btn' + (v.on ? ' sec' : '') + '" type="submit">' + (v.on ? 'Switch my page off' : 'Switch my page on') + '</button></form>'
|
||||||
|
+ '<p class="fine">This is the same switch as InstantAdPay Promo tools > Stack POL. Change it in either place.' + (v.live.ok ? '' : ' (InstantAdPay did not answer just now; the state shown is from the last ledger refresh.)') + '</p>';
|
||||||
|
} else {
|
||||||
|
h += '<div class="cta" style="margin-top:12px"><a class="btn sec" href="' + esc(iapswitch.promoUrl()) + '" rel="noopener">Change it in InstantAdPay</a></div><p class="fine">The switch lives in InstantAdPay Promo tools > Stack POL. The state shown is from the last ledger refresh.</p>';
|
||||||
|
}
|
||||||
|
h += '</section>';
|
||||||
|
// 2. Pro
|
||||||
|
h += '<section class="mycard"><div class="mct"><h2>Stack POL Pro</h2><span class="pill ' + (v.pro ? 'on' : 'off') + '">' + (v.pro ? 'Pro' : 'Not yet') + '</span></div>';
|
||||||
|
if (v.pro) {
|
||||||
|
const pr = v.stack && v.stack.pro;
|
||||||
|
h += '<p class="mysub">Your page shows your own LinkSpin Banner Spins in the ad spots and your spin links, with your QR code. Any page opened with ?ref=' + esc(un) + ' carries your referral.</p>';
|
||||||
|
if (pr) h += '<p class="mysub">On your page now: ' + fmtInt((pr.spins || []).length) + ' Banner Spin' + ((pr.spins || []).length === 1 ? '' : 's') + ', ' + fmtInt((pr.links || []).length) + ' spin link' + ((pr.links || []).length === 1 ? '' : 's') + '. <a href="https://linkspin.app/my" rel="noopener">Manage them in LinkSpin</a></p>';
|
||||||
|
if (pr) h += pr.video ? '<p class="mysub">Your videos: the Video Spin "' + esc(pr.video.name) + '" (' + fmtInt(pr.video.count) + ' video' + (pr.video.count === 1 ? '' : 's') + ') shows on your page. <a href="https://linkspin.app/links" rel="noopener">Change it in LinkSpin</a></p>'
|
||||||
|
: '<p class="mysub">No videos on your page yet. Make a video on Video App Income (the first one is free), then add it to a Video Spin in LinkSpin and it shows here. <a href="https://videoappincome.com/join?ref=' + esc(un) + '" rel="noopener">Make your first video</a></p>';
|
||||||
|
h += copyRow('refurl', D.SITE + '/?ref=' + un, 'Any Stack POL page with your referral');
|
||||||
|
} else {
|
||||||
|
h += '<p class="mysub">Pro unlocks one time with any InstantAdPay ad package of $10 or more: your banners in the ad spots, your links and your QR code on your page.</p><div class="cta" style="margin-top:12px"><a class="btn sec" href="https://instantadpay.com/my#promo?s=stackpol" rel="noopener">See Pro in InstantAdPay</a></div>';
|
||||||
|
}
|
||||||
|
h += '</section></div>';
|
||||||
|
// 3. join links
|
||||||
|
h += '<div class="sec-head"><h2>Your join links</h2><p>The same links your public page uses. Each one credits you.</p></div><div class="jlinks">'
|
||||||
|
+ PROGRAMS.map((p, i) => '<div class="jl" style="--c:' + p.c + '"><div class="jn"><i></i><b>' + esc(p.n) + '</b><span>' + esc(p.kind) + '</span></div>' + copyRow('j' + i, p.join(un)) + '</div>').join('') + '</div>';
|
||||||
|
// 4. share kit
|
||||||
|
const share = 'Every POL payout I have stacked across the network, each one a Polygon transaction you can check: ' + pageUrl;
|
||||||
|
h += '<div class="sec-head"><h2>Share kit</h2><p>Your page link, a ready post and the Stack POL images.</p></div><div class="mygrid">';
|
||||||
|
h += '<section class="mycard">' + copyRow('kurl', pageUrl, 'Your page') + '<div class="cprow"><label for="kpost">A ready post</label><div class="cpbox"><textarea id="kpost" readonly rows="3">' + esc(share) + '</textarea><button type="button" class="cpb" data-copy="kpost">Copy</button></div></div>'
|
||||||
|
+ copyRow('kembed', '<a href="' + pageUrl + '"><img src="' + D.SITE + '/og-stackpol-1200x630.jpg" width="600" height="315" alt="Stack POL: every POL payout, stacked"></a>', 'Banner code for a site or blog')
|
||||||
|
+ (v.pro && D.qr ? '<div class="kqr"><img src="/qr/' + esc(un) + '.svg" alt="QR code for your page" width="120" height="120"><span>Your QR code. <a href="/qr/' + esc(un) + '.svg" download="stackpol-' + esc(un) + '-qr.svg">Download</a></span></div>' : '') + '</section>';
|
||||||
|
h += '<section class="mycard kimgs">' + [['/og-stackpol-1200x630.jpg', 'Share image 1200x630', 'stackpol-share-1200x630.jpg'], ['/stackpol-hero-poster.jpg', 'Coin stack still', 'stackpol-coins.jpg']]
|
||||||
|
.map(([src, label, fn]) => '<figure><img src="' + src + '" alt="' + esc(label) + '" loading="lazy"><figcaption>' + esc(label) + ' <a href="' + src + '" download="' + fn + '">Download</a></figcaption></figure>').join('') + '</section></div>';
|
||||||
|
// 5. payouts
|
||||||
|
h += '<div class="sec-head"><h2>Your payouts</h2><p>From the Stack POL ledger, your wallet' + (v.wallets.length === 1 ? '' : 's') + ' only.' + (D.idx() && D.idx().at ? ' Refreshed ' + D.when(D.idx().at) + '.' : '') + '</p></div>';
|
||||||
|
if (!m) {
|
||||||
|
h += '<section class="mycard"><p class="lead" style="margin:0">No payouts on the ledger for @' + esc(un) + ' yet. Payouts from any program in the network show here within 5 minutes of landing in your wallet.</p></section>';
|
||||||
|
} else {
|
||||||
|
const ps = PROGRAMS.filter(p => m.byProg[p.k]).sort((a, b) => m.byProg[b.k].pol - m.byProg[a.k].pol);
|
||||||
|
h += '<section class="mycard"><div class="total"><span class="n">' + fmt(m.total) + '</span><span class="u">POL</span></div><div class="stats"><div><b>' + fmtInt(m.payments) + '</b><span>payments</span></div><div><b>' + fmtInt(ps.length) + '</b><span>programs</span></div>'
|
||||||
|
+ (m.since ? '<div><b>' + new Date(m.since).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'America/Chicago' }) + '</b><span>first payout</span></div>' : '') + '</div>'
|
||||||
|
+ '<div class="keys">' + ps.map(p => '<span style="--c:' + p.c + '"><i></i>' + esc(p.n) + ' <b>' + fmt(m.byProg[p.k].pol) + '</b></span>').join('') + '</div>'
|
||||||
|
+ (v.wallets.length ? '<p class="mysub" style="margin-top:12px">Wallet' + (v.wallets.length === 1 ? '' : 's') + ': ' + v.wallets.map(w => '<a class="mono" href="https://polygonscan.com/address/' + esc(w) + '" target="_blank" rel="noopener">' + esc(w.slice(0, 6) + '…' + w.slice(-4)) + ' ↗</a>').join(' ') + '</p>' : '') + '</section>';
|
||||||
|
const rows = m.rows || [];
|
||||||
|
h += D.tableHead(false) + D.ledgerRows(rows, false) + '</tbody></table></div>';
|
||||||
|
if (rows.length < m.payments) h += '<p class="fine" style="margin-top:8px">Showing your latest ' + fmtInt(rows.length) + ' of ' + fmtInt(m.payments) + ' payments. Every one is on Polygonscan under your wallet.</p>';
|
||||||
|
}
|
||||||
|
h += '<div class="myfoot"><form method="post" action="/api/my/signout"><button class="btn sec" type="submit">Sign out</button></form><form method="post" action="/api/my/signout"><input type="hidden" name="everywhere" value="1"><button class="linkbtn" type="submit">Sign out of the whole network</button></form></div>';
|
||||||
|
return h + D.tail(COPY_JS);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function render(req, q) {
|
||||||
|
const s = session(req);
|
||||||
|
if (!s) return { body: signedOutPage(q), set: cookies(req)['sp.in'] ? clearCookies() : [] };
|
||||||
|
const v = await view(s);
|
||||||
|
return { body: memberPage(s, v, q), set: cookies(req)['sp.in'] === '1' ? [] : [ck('sp.in', '1', AGE, false)] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/my/switch (form: on=1|0). -> { ok, on } or { ok: false, reason }
|
||||||
|
async function doSwitch(s, on) {
|
||||||
|
if (!iapswitch.configured()) return { ok: false, reason: 'off' };
|
||||||
|
const r = await iapswitch.set(s.email, on);
|
||||||
|
if (!r.ok) return r;
|
||||||
|
const un = r.username; if (!un) return { ok: false, reason: 'no username' };
|
||||||
|
const doc = readDoc('my-switch.json'); doc[un] = { on: r.on, at: Date.now() }; writeDoc('my-switch.json', doc);
|
||||||
|
return { ok: true, on: r.on, username: un };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, session, mintSession, signOut, clearCookies, render, doSwitch, hiddenNow, view, cookies, NAME_RE };
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
// Network deals for this site's "Network Weekend" ribbon (Marty 2026-11-17). One source: the hub's public GET /v1/network-deals
|
||||||
|
// (HUB_URL). Cached 2 minutes, refreshed in the background, never waits on a slow hub (2.5 s timeout); hub down = no ribbon.
|
||||||
|
// The same file lives in every network site. Never RM Circle, never the games (the hub list never names them).
|
||||||
|
// The page (/assets/netweekend.js) switches the ribbon on and off by its own clock at startsAt / endsAt, so a cached copy never
|
||||||
|
// shows early or late. setLocal(fn) lets a site rewrite its own deal line from live data (for example a price read from chain),
|
||||||
|
// so the ribbon never shows a number the contract does not charge: fn(deal) returns the deal, a changed copy, or null to drop it.
|
||||||
|
const TTL = 2 * 60 * 1000;
|
||||||
|
let cache = { at: 0, body: { events: [] } };
|
||||||
|
let inflight = null;
|
||||||
|
let local = null;
|
||||||
|
|
||||||
|
const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, '');
|
||||||
|
const safeUrl = u => (/^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(u || '')) ? String(u) : '');
|
||||||
|
const str = (v, n) => String(v == null ? '' : v).slice(0, n || 300);
|
||||||
|
function clean(j) {
|
||||||
|
if (!j || !Array.isArray(j.events)) return null;
|
||||||
|
return { events: j.events.slice(0, 5).filter(e => e && e.id && !Number.isNaN(Date.parse(e.startsAt)) && !Number.isNaN(Date.parse(e.endsAt))).map(e => ({
|
||||||
|
id: str(e.id, 60), name: str(e.name, 60), tagline: str(e.tagline, 160), url: safeUrl(e.url), startsAt: e.startsAt, endsAt: e.endsAt,
|
||||||
|
days: e.days && typeof e.days === 'object' ? Object.fromEntries(Object.entries(e.days).slice(0, 20).map(([k, v]) => [str(k, 10), str(v, 40)])) : {},
|
||||||
|
deals: (Array.isArray(e.deals) ? e.deals : []).slice(0, 40).map(d => {
|
||||||
|
const x = { site: str(d.site, 30), name: str(d.name, 80), url: safeUrl(d.url), text: str(d.text), endsAt: Number.isNaN(Date.parse(d.endsAt)) ? e.endsAt : d.endsAt };
|
||||||
|
if (d.note) x.note = str(d.note, 120);
|
||||||
|
if (d.byDay && typeof d.byDay === 'object') x.byDay = Object.fromEntries(Object.entries(d.byDay).slice(0, 20).map(([k, v]) => [str(k, 10), str(v)]));
|
||||||
|
return x;
|
||||||
|
})
|
||||||
|
})) };
|
||||||
|
}
|
||||||
|
function refresh() {
|
||||||
|
if (inflight || process.env.NETWORK_DEALS_HUB === '0') return inflight;
|
||||||
|
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500);
|
||||||
|
inflight = fetch(hubUrl() + '/v1/network-deals', { signal: ac.signal })
|
||||||
|
.then(r => (r.ok ? r.json() : null))
|
||||||
|
.then(j => { const b = clean(j); if (b) cache = { at: Date.now(), body: b }; else cache.at = Date.now(); })
|
||||||
|
.catch(() => { cache.at = Date.now() - TTL + 30 * 1000; }) // hub down: try again in 30 s, keep the last good copy
|
||||||
|
.finally(() => { clearTimeout(t); inflight = null; });
|
||||||
|
return inflight;
|
||||||
|
}
|
||||||
|
function current() { if (Date.now() - cache.at > TTL) refresh(); return cache.body; }
|
||||||
|
function setLocal(fn) { local = typeof fn === 'function' ? fn : null; }
|
||||||
|
function withLocal(body, self) {
|
||||||
|
if (!local) return body;
|
||||||
|
return { events: body.events.map(e => Object.assign({}, e, { deals: e.deals.map(d => {
|
||||||
|
if (d.site !== self) return d;
|
||||||
|
try { const r = local(Object.assign({}, d)); return r === undefined ? d : r; } catch (err) { return d; }
|
||||||
|
}).filter(Boolean) })) };
|
||||||
|
}
|
||||||
|
// GET /api/network-deals: public, short cache, the same answer on every page. self = this site's network id (NETWORK_SITE_ID).
|
||||||
|
async function handle(req, res, self) {
|
||||||
|
if (!cache.at) { try { await refresh(); } catch (e) {} } // first ask after a boot waits for the hub once (2.5 s cap)
|
||||||
|
const me = String(self || process.env.NETWORK_SITE_ID || '').trim().toLowerCase();
|
||||||
|
const body = Object.assign({ self: me }, withLocal(current(), me));
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=60', 'X-Content-Type-Options': 'nosniff' });
|
||||||
|
res.end(JSON.stringify(body));
|
||||||
|
}
|
||||||
|
module.exports = { current, handle, refresh, setLocal, clean, _set: b => { cache = { at: Date.now(), body: clean(b) || { events: [] } }; } };
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// SEMANTIC MATCHING (Marty 2026-11-16): the hub matches a question by meaning against the whole network KB with the free core2
|
||||||
|
// embeddings model (POST HUB_URL/v1/kb/match). match() asks it with a strict timeout (NETKB_MATCH_MS, default 1500) and fails
|
||||||
|
// soft: an error or a timeout answers null and the next MATCH_PAUSE_MS skip the hub, so the chat never waits on a slow model and
|
||||||
|
// the site's own BM25 retrieval (kb.js) answers as before. route() turns a match into the chatbot's decision:
|
||||||
|
// - this site's own entry, raw score >= SEM.answer with a clear lead (or the instant-answer pattern agrees): the answer itself
|
||||||
|
// - the instant-answer pattern hit kept when the match agrees (its entry within SEM.agree of the top), or when the match has
|
||||||
|
// no idea (top below SEM.unsure); this site's own entries rank first unless another site is named or clearly closer
|
||||||
|
// - otherwise no instant answer (the regex is overruled by meaning); the entries >= SEM.context feed the AI prompt
|
||||||
|
// suggest() gives the support desk's new-ticket form the closest help answers (KB entries only) the same way, BM25 as the fallback.
|
||||||
|
// Off with NETKB_MATCH=0. Thresholds measured on bge-large-en-v1.5 over the network KB (2026-11-16). Tests: qa/netkb-semantic.test.mjs
|
||||||
|
// 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, timeoutMs) {
|
||||||
|
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(timeoutMs || 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 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- semantic matching (2026-11-16)
|
||||||
|
const SEM = { answer: Number(process.env.NETKB_SEM_ANSWER) || 0.84, margin: 0.02, context: Number(process.env.NETKB_SEM_CONTEXT) || 0.68, unsure: 0.70, band: 0.08, away: 0.06, agree: 0.10, floor: 0.60 };
|
||||||
|
const MATCH_PAUSE_MS = 30000;
|
||||||
|
let matchDownUntil = 0;
|
||||||
|
const mstats = { matches: 0, matchErrors: 0, matchSkipped: 0, matchLastMs: 0, matchLastError: null, semAnswer: 0, semAgree: 0, semRegex: 0, semVeto: 0, semContext: 0 };
|
||||||
|
const matchOn = () => enabled() && process.env.NETKB_MATCH !== '0';
|
||||||
|
// -> the hub's answer {confidence, margin, hits: [{site, id, title, answer, score, boosted, home}]} or null (off, down, slow)
|
||||||
|
async function match(q, o) {
|
||||||
|
o = o || {};
|
||||||
|
if (!matchOn()) return null;
|
||||||
|
if (Date.now() < matchDownUntil) { mstats.matchSkipped++; return null; }
|
||||||
|
const t0 = Date.now();
|
||||||
|
try {
|
||||||
|
const body = { q: String(q || '').slice(0, 600), k: o.k || 6 };
|
||||||
|
if (o.prefer && o.prefer.length) body.prefer = o.prefer;
|
||||||
|
if (o.only && o.only.length) body.only = o.only;
|
||||||
|
const r = await call('POST', '/v1/kb/match', body, undefined, o.timeoutMs || Number(process.env.NETKB_MATCH_MS) || 1500);
|
||||||
|
mstats.matchLastMs = Date.now() - t0;
|
||||||
|
if (r.status !== 200 || !r.body || !Array.isArray(r.body.hits)) throw new Error('match ' + r.status + ' ' + ((r.body && r.body.error) || ''));
|
||||||
|
mstats.matches++;
|
||||||
|
return r.body;
|
||||||
|
} catch (e) { mstats.matchErrors++; mstats.matchLastError = e.message; matchDownUntil = Date.now() + MATCH_PAUSE_MS; return null; }
|
||||||
|
}
|
||||||
|
// msg + { fast: the instant-answer pattern hit (or null), own: this site's entries, prefer: [site ids the question names] }
|
||||||
|
// -> null (no match: the caller keeps its old path) or { via, hit: own entry to answer with | null, hits: [{entry, score}] for the prompt }
|
||||||
|
async function route(msg, o) {
|
||||||
|
o = o || {};
|
||||||
|
// a question that names another site but asks about "here" is about this site (e.g. "I am on InstantAdPay, does my team carry over here?")
|
||||||
|
const prefer = (o.prefer || []).length && !/\b(here|this site|this one)\b/i.test(msg) ? o.prefer : [];
|
||||||
|
const m = await match(msg, { k: 8, prefer });
|
||||||
|
if (!m) return null;
|
||||||
|
const me = siteName();
|
||||||
|
const own = new Map((o.own || []).map(e => [String(e.id), e]));
|
||||||
|
const rem = new Map(remote().map(e => [e.id, e]));
|
||||||
|
const all = m.hits.map(h => ({ entry: h.site === me ? own.get(String(h.id)) : rem.get(h.site + ':' + h.id), score: Number(h.score) || 0, home: h.site === me })).filter(h => h.entry);
|
||||||
|
let hits = all;
|
||||||
|
const named = prefer.length > 0, fast = o.fast || null;
|
||||||
|
if (!named) { // home-site first: this site's own entries lead; another site's ride behind them only when clearly closer (a thing only that site has)
|
||||||
|
const mine = hits.filter(h => h.home && h.score >= SEM.context);
|
||||||
|
const homeTop = mine.length ? mine[0].score : 0;
|
||||||
|
hits = mine.concat(hits.filter(h => !h.home && h.score >= homeTop + SEM.away));
|
||||||
|
}
|
||||||
|
const top = hits[0];
|
||||||
|
const ctx = top ? hits.filter(h => h.score >= SEM.context && (h.score >= top.score - SEM.band || !h.home)).map(h => ({ entry: h.entry, score: Math.round(h.score * 1000) / 1000 })) : [];
|
||||||
|
const out = (via, hit) => { mstats['sem' + via[0].toUpperCase() + via.slice(1)]++; return { via, hit, hits: ctx, confidence: top ? top.score : 0 }; };
|
||||||
|
if (top && top.home && !named && top.score >= SEM.answer && (Number(m.margin) >= SEM.margin || (fast && String(fast.id) === String(top.entry.id)))) return out('answer', top.entry);
|
||||||
|
if (fast) {
|
||||||
|
const best = all.length ? all[0].score : 0;
|
||||||
|
if (all.some(h => h.home && String(h.entry.id) === String(fast.id) && h.score >= SEM.floor && h.score >= best - SEM.agree)) return out('agree', fast);
|
||||||
|
if (!top || top.score < SEM.unsure) return out('regex', fast);
|
||||||
|
return out('veto', null);
|
||||||
|
}
|
||||||
|
return out('context', null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// support desk suggestions (2026-11-16): the help answers closest to what a signed-in member is typing into a new ticket.
|
||||||
|
// Knowledge-base entries only (published answers, including the ones written from past tickets), never anyone's ticket text.
|
||||||
|
// text + { own: this site's entries, fallback: async q => [{entry}] (BM25) when the hub is slow or down, max }
|
||||||
|
const SUGGEST_MIN = Number(process.env.NETKB_SUGGEST_MIN) || 0.70;
|
||||||
|
const NOT_SUGGESTED = /(^|[-:])support$|^c-refund$/; // the "contact support" entry is no help on the support form itself
|
||||||
|
function suggestItem(e, home, score) {
|
||||||
|
return { id: String(e.id), title: e.title, answer: String(e.answer || '').slice(0, 900), site: home ? '' : (e.siteName || e.site || ''),
|
||||||
|
link: home ? (e.link || '') : (e.go || e.siteUrl || ''), fromTicket: !!(home && e.source === 'ticket'), score: score == null ? null : Math.round(score * 1000) / 1000 };
|
||||||
|
}
|
||||||
|
async function suggest(text, o) {
|
||||||
|
o = o || {};
|
||||||
|
const q = String(text || '').replace(/\s+/g, ' ').trim().slice(0, 600);
|
||||||
|
if (q.replace(/[^A-Za-z0-9]/g, '').length < 10) return { items: [], via: 'short' };
|
||||||
|
const me = siteName(); const own = new Map((o.own || []).map(e => [String(e.id), e]));
|
||||||
|
const keep = (e, home) => e && !(home && e.handoff) && !NOT_SUGGESTED.test(String(e.id));
|
||||||
|
let items = [], via = 'none';
|
||||||
|
const m = await match(q, { k: 8, timeoutMs: o.timeoutMs || 2000 });
|
||||||
|
if (m) {
|
||||||
|
via = 'semantic'; const top = m.hits.length ? Number(m.hits[0].score) : 0; const rem = new Map(remote().map(e => [e.id, e]));
|
||||||
|
for (const h of m.hits) {
|
||||||
|
if (h.score < SUGGEST_MIN || h.score < top - 0.08) continue;
|
||||||
|
const home = h.site === me; const e = home ? own.get(String(h.id)) : rem.get(h.site + ':' + h.id);
|
||||||
|
if (keep(e, home)) items.push(suggestItem(e, home, h.score));
|
||||||
|
}
|
||||||
|
} else if (typeof o.fallback === 'function') {
|
||||||
|
via = 'bm25';
|
||||||
|
try { for (const x of (await o.fallback(q)) || []) { const e = x && x.entry; const home = !!e && !e.site; if (keep(e, home)) items.push(suggestItem(e, home, null)); } } catch (e) {}
|
||||||
|
}
|
||||||
|
return { items: items.slice(0, o.max || 3), via };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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, semantic: matchOn(), sem: SEM }, stats, mstats); }
|
||||||
|
function _set(m) { merged = m; } // tests
|
||||||
|
|
||||||
|
const version = () => merged.version || '';
|
||||||
|
function _matchReset() { matchDownUntil = 0; } // tests
|
||||||
|
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, match, route, suggest, SEM, _set, _matchReset };
|
||||||
+6
-1
@@ -8,6 +8,11 @@ const FALLBACK = [
|
|||||||
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' },
|
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' },
|
||||||
{ id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' },
|
{ id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' },
|
||||||
{ id: 'viraladblitz', name: 'ViralAdBlitz', url: 'https://viraladblitz.com' },
|
{ id: 'viraladblitz', name: 'ViralAdBlitz', url: 'https://viraladblitz.com' },
|
||||||
|
{ id: 'viraladsource', name: 'ViralAdSource', url: 'https://viraladsource.com' },
|
||||||
|
{ id: 'yourprogrambuilder', name: 'YourProgramBuilder', url: 'https://yourprogrambuilder.com' },
|
||||||
|
{ id: 'videoappincome', name: 'Video App Income', url: 'https://videoappincome.com' },
|
||||||
|
{ id: 'fivex', name: '5xYourTeam', url: 'https://5xyourteam.com' },
|
||||||
|
{ id: 'downlinehydra', name: 'DownlineHydra', url: 'https://downlinehydra.com' },
|
||||||
{ id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
|
{ id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
|
||||||
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }
|
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }
|
||||||
];
|
];
|
||||||
@@ -37,7 +42,7 @@ function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list;
|
|||||||
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
|
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
|
||||||
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
|
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
|
||||||
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
|
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
|
||||||
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', viraladblitz: 'nwvab', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', viraladblitz: 'nwvab', viraladsource: 'nwvas', yourprogrambuilder: 'nwypb', fivex: 'nw5x', downlinehydra: 'nwdh', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
||||||
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
|
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
|
||||||
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||||
function selfId(req, l) {
|
function selfId(req, l) {
|
||||||
|
|||||||
+452
@@ -0,0 +1,452 @@
|
|||||||
|
// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each
|
||||||
|
// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes.
|
||||||
|
//
|
||||||
|
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
|
||||||
|
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
|
||||||
|
// sets the loop guard (nsso.tried, 2 minutes) and sends the browser to P.
|
||||||
|
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
|
||||||
|
// P mints a token bound to R, the state and the email, and sends the browser
|
||||||
|
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
|
||||||
|
// 3. R GET /sso/in?t=<token> R checks signature, audience, expiry (60 s), the state against its cookie
|
||||||
|
// (so nobody can push their own token into someone else's browser), and spends
|
||||||
|
// the nonce (a second use is refused). The email must already be a member
|
||||||
|
// here; then R makes an ordinary session and redirects to the relative path.
|
||||||
|
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
|
||||||
|
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
|
||||||
|
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
|
||||||
|
// stops a second bounce for 2 minutes (30 until 2026-11-15, when it blocked Marty's silent sign-in on LinkSpin), signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
|
||||||
|
// bots and non-page fetches never bounce.
|
||||||
|
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
|
||||||
|
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
|
||||||
|
//
|
||||||
|
// Wallet sites (Downline Banners, 2026-11-13, Marty: "sign in once and be logged into all these sites"). Downline Banners has no email
|
||||||
|
// accounts; its members are wallets. IAP and LinkSpin list it under `wallets: { bannerline: base }` and vouch one way: /go/bannerline
|
||||||
|
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
|
||||||
|
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
|
||||||
|
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
|
||||||
|
//
|
||||||
|
// THE HUB AS THE PROVIDER (Marty approved 2026-11-15; off unless HUB_SSO=on, with HUB_URL, HUB_SECRET (32+) and HUB_SITE or C.hubSite).
|
||||||
|
// The network hub keeps one network sign-in per browser in its own cookie (7 days, renewed on use). With it on:
|
||||||
|
// /sso/start asks the hub (GET <hub>/sso/check?site=<HUB_SITE>&st&to&m) instead of one other site; the hub answers
|
||||||
|
// /sso/in?h=<token> ("h1." token, HMAC-SHA256 with this site's HUB_SECRET under 'hubsso.v1.', iss 'hub', aud = this site,
|
||||||
|
// 60 s, single use, bound to the state cookie) or /sso/in?none=1&hub=1, and then the old pairwise path is tried once as the
|
||||||
|
// fallback (until every site is switched).
|
||||||
|
// Push: a signed-in member's page load (a real top-level navigation only) with no matching nsso.hp cookie goes once through
|
||||||
|
// <hub>/sso/set?site&t=<this site's token for the member> and straight back, so signing in on any site signs in the hub.
|
||||||
|
// Only when the hub answered /health in the last 2 minutes: a hub that is down never takes a page with it.
|
||||||
|
// Activity (Marty 2026-11-15, DownlineHydra "Wake it", the CRM score): a signed-in member's page load pings POST <hub>/v1/activity
|
||||||
|
// {email|wallet, kind 'visit'} at most once per member per day, fire and forget (HUB_URL + HUB_SECRET; HUB_ACTIVITY=0 turns it off).
|
||||||
|
// signOutEverywhere(session): POST <hub>/v1/sso/signout; the hub ends every hub sign-in of that person and tells hooked sites.
|
||||||
|
//
|
||||||
|
// ONE SITES LIST + THE WAY BACK (Marty 2026-11-17: "I logged in to Instant Ad Pay from Viral Ad Source, and it never had a return
|
||||||
|
// path back"). Before, each provider (IAP, LinkSpin) kept its own hand-written `wallets` list; a site missing from it (5xYourTeam
|
||||||
|
// 11-15, ViralAdSource 11-17) was refused at /sso/check and the member was dropped on the provider's dashboard with no way back.
|
||||||
|
// Sites list: a provider also knows every site in the hub's public GET <hub>/v1/sso-sites (HUB_SSO_SITES there; the same list the
|
||||||
|
// hub signs in for). Read at start, every 5 minutes, and once more (2 s at most) when an unknown site asks. Hand-written entries win.
|
||||||
|
// Return links: any provider page with ?return=<site>&to=/path (a known site only, never an open redirect) remembers the way back
|
||||||
|
// in nsso.ret (1 day) and reloads without the two parameters. Signed in already: straight back. After the email-code sign-in (and
|
||||||
|
// after the username step for a new account) the provider's dashboard goes to /sso/resume, which finishes it: /go/<site>?to=/path.
|
||||||
|
// No wallet yet (a wallet site needs one): with C.walletPath the member goes to the provider's wallet step first (nsso.wait), and
|
||||||
|
// afterWallet(req) gives the wallet-link answer its next hop, /sso/resume. The same holds for a deliberate tap (nsso.back).
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim();
|
||||||
|
const enabled = () => SECRET().length >= 32;
|
||||||
|
const TTL = 60 * 1000; // token life
|
||||||
|
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
||||||
|
const STATE_AGE = 300; // seconds: the state cookie
|
||||||
|
const GO_STATE_AGE = 3600; // seconds: the state cookie on a deliberate tap (time to sign in, pick a username and link a wallet on the provider first; 20 minutes until 2026-11-17)
|
||||||
|
const BACK_AGE = 3600; // seconds: the provider remembers an unfinished deliberate check while the member signs in (20 minutes until 2026-11-17)
|
||||||
|
const RET_AGE = 86400; // seconds: a ?return=<site> link remembers the way back (2026-11-17)
|
||||||
|
const TRIED_AGE = 120; // seconds: one silent check per browser per 2 minutes (loop guard only; 30 minutes until 2026-11-15)
|
||||||
|
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
|
||||||
|
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
||||||
|
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', fivex: '5xYourTeam' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15); fivex = 5xYourTeam (2026-11-15)
|
||||||
|
const WALLET_RE = /^0x[0-9a-f]{40}$/;
|
||||||
|
const PUSH_AGE = 6 * 86400; // seconds: this browser's member is signed in on the hub (the hub's own sign-in lasts 7 days)
|
||||||
|
const HUB_BASE = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||||
|
const HUB_KEY = () => String(process.env.HUB_SECRET || '').trim();
|
||||||
|
const HUB_NAME = () => String(process.env.HUB_SITE || (C && (C.hubSite || C.self)) || '').trim().toLowerCase();
|
||||||
|
const hubCreds = () => /^https?:\/\/[a-z0-9.:-]+$/i.test(HUB_BASE()) && HUB_KEY().length >= 32 && /^[a-z0-9_-]{1,64}$/.test(HUB_NAME());
|
||||||
|
const hubOn = () => String(process.env.HUB_SSO || '').trim().toLowerCase() === 'on' && hubCreds();
|
||||||
|
let hubSeen = 0, hubChecked = 0, hubAsking = null; // last good /health answer, last time we asked
|
||||||
|
// true when the hub answered /health in the last 2 minutes. Asked at most once a minute; while the answer is unknown (first use, or
|
||||||
|
// the last good answer is old) the caller waits for that one question (2 s at most), so a hub that is down costs one page 2 s a minute.
|
||||||
|
async function hubUp() {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - hubChecked >= 60000 && !hubAsking && typeof fetch === 'function') {
|
||||||
|
hubChecked = now;
|
||||||
|
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, 2000);
|
||||||
|
hubAsking = fetch(HUB_BASE() + '/health', { signal: ac ? ac.signal : undefined }).then(r => { if (r.ok) hubSeen = Date.now(); }).catch(() => {}).finally(() => { clearTimeout(tm); hubAsking = null; });
|
||||||
|
}
|
||||||
|
if (hubAsking && Date.now() - hubSeen >= 120000) await hubAsking;
|
||||||
|
return Date.now() - hubSeen < 120000;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the hub's sign-in sites {site: base} (2026-11-17): providers answer every site the hub knows, not only their hand-written list
|
||||||
|
let hubSites = {}, hubSitesAt = 0, hubSitesAsking = null;
|
||||||
|
const SITE_RE = /^[a-z0-9_-]{1,64}$/, BASE_RE = /^https?:\/\/[a-z0-9.:-]+$/i;
|
||||||
|
function loadHubSites() {
|
||||||
|
if (hubSitesAsking) return hubSitesAsking;
|
||||||
|
if (!BASE_RE.test(HUB_BASE()) || typeof fetch !== 'function' || String(process.env.NSSO_HUB_SITES || '') === '0') return Promise.resolve();
|
||||||
|
hubSitesAt = Date.now();
|
||||||
|
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, 2000);
|
||||||
|
hubSitesAsking = fetch(HUB_BASE() + '/v1/sso-sites', { signal: ac ? ac.signal : undefined }).then(r => (r.ok ? r.json() : null)).then(j => {
|
||||||
|
if (!j || !j.sites || typeof j.sites !== 'object') return;
|
||||||
|
const out = {}; for (const [k, v] of Object.entries(j.sites)) { const b = String(v || '').replace(/\/+$/, ''); if (SITE_RE.test(k) && BASE_RE.test(b)) out[k] = b; }
|
||||||
|
hubSites = out;
|
||||||
|
}).catch(() => {}).finally(() => { clearTimeout(tm); hubSitesAsking = null; });
|
||||||
|
return hubSitesAsking;
|
||||||
|
}
|
||||||
|
const freshSites = () => { if (C && C.wallet && Date.now() - hubSitesAt > 5 * 60 * 1000) loadHubSites(); };
|
||||||
|
|
||||||
|
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
|
||||||
|
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() }, walletPath?: the provider's wallet step }
|
||||||
|
|
||||||
|
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||||
|
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||||
|
const mac = s => crypto.createHmac('sha256', SECRET()).update('nsso.v1.' + s).digest();
|
||||||
|
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
||||||
|
const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || '');
|
||||||
|
|
||||||
|
// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters.
|
||||||
|
function safePath(to, dflt) {
|
||||||
|
const d = dflt == null ? '/' : dflt;
|
||||||
|
const s = String(to == null ? '' : to);
|
||||||
|
if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d;
|
||||||
|
try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function mint(o) {
|
||||||
|
const now = o.now || Date.now();
|
||||||
|
const t = { iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
|
||||||
|
if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
|
||||||
|
if (o.name) t.name = String(o.name).slice(0, 40);
|
||||||
|
const body = b64u(JSON.stringify(t));
|
||||||
|
return 'v1.' + body + '.' + b64u(mac(body));
|
||||||
|
}
|
||||||
|
|
||||||
|
// -> { ok, email, to, n, exp } or { error: reason }
|
||||||
|
function verify(tok, o) {
|
||||||
|
if (!enabled()) return { error: 'off' };
|
||||||
|
const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
|
||||||
|
if (!m) return { error: 'malformed' };
|
||||||
|
const want = mac(m[1]), got = unb64u(m[2]);
|
||||||
|
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
|
||||||
|
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
|
||||||
|
const now = (o && o.now) || Date.now();
|
||||||
|
if (!p || p.aud !== o.aud || ![].concat(o.iss).includes(p.iss)) return { error: 'audience' };
|
||||||
|
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
|
||||||
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
|
||||||
|
const st = String((o && o.st) || '');
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
|
||||||
|
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
|
||||||
|
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
|
||||||
|
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// hub tokens ("h1.", the hub's format): mint for the hub (push), verify from the hub (sign-in)
|
||||||
|
const hmacHub = x => crypto.createHmac('sha256', HUB_KEY()).update('hubsso.v1.' + x).digest();
|
||||||
|
function mintHub(o) {
|
||||||
|
const now = o.now || Date.now();
|
||||||
|
const t = { iss: HUB_NAME(), aud: 'hub', to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
|
||||||
|
if (o.email) t.email = String(o.email).trim().toLowerCase(); else if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
|
||||||
|
const body = b64u(JSON.stringify(t));
|
||||||
|
return 'h1.' + body + '.' + b64u(hmacHub(body));
|
||||||
|
}
|
||||||
|
function verifyHub(tok, o) {
|
||||||
|
if (!hubCreds()) return { error: 'off' };
|
||||||
|
const m = /^h1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
|
||||||
|
if (!m) return { error: 'malformed' };
|
||||||
|
const want = hmacHub(m[1]), got = unb64u(m[2]);
|
||||||
|
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
|
||||||
|
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
|
||||||
|
const now = (o && o.now) || Date.now();
|
||||||
|
if (!p || p.iss !== 'hub' || p.aud !== HUB_NAME()) return { error: 'audience' };
|
||||||
|
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
|
||||||
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
|
||||||
|
const st = String((o && o.st) || '');
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
|
||||||
|
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
|
||||||
|
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
|
||||||
|
return { ok: true, iss: 'hub', email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||||
|
}
|
||||||
|
// a signed /v1 call to the hub (the scheme every site already uses): hex HMAC-SHA256(HUB_SECRET, ts + newline + body)
|
||||||
|
async function hubCall(route, body, ms) {
|
||||||
|
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
|
||||||
|
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, ms || 5000);
|
||||||
|
try {
|
||||||
|
const r = await fetch(HUB_BASE() + route, { method: 'POST', body: raw, signal: ac ? ac.signal : undefined, headers: { 'Content-Type': 'application/json', 'X-Hub-Site': HUB_NAME(), 'X-Hub-Ts': ts, 'X-Hub-Sig': crypto.createHmac('sha256', HUB_KEY()).update(ts + '\n' + raw).digest('hex') } });
|
||||||
|
let j = null; try { j = await r.json(); } catch (e) {}
|
||||||
|
return { status: r.status, json: j };
|
||||||
|
} finally { clearTimeout(tm); }
|
||||||
|
}
|
||||||
|
const who = s => (s && s.email ? { email: String(s.email).toLowerCase() } : s && s.address && WALLET_RE.test(String(s.address).toLowerCase()) ? { wallet: String(s.address).toLowerCase() } : null);
|
||||||
|
const pushTag = w => b64u(crypto.createHmac('sha256', HUB_KEY()).update('push.' + (w.email || w.wallet)).digest()).slice(0, 22);
|
||||||
|
// once per member per day (memory; a restart may ping once more, the hub counts a visit once per 10 minutes anyway)
|
||||||
|
const pinged = new Map(); let pingDay = '';
|
||||||
|
function activity(w) {
|
||||||
|
if (String(process.env.HUB_ACTIVITY || '') === '0' || !hubCreds() || typeof fetch !== 'function') return;
|
||||||
|
const day = new Date().toISOString().slice(0, 10); if (day !== pingDay) { pinged.clear(); pingDay = day; }
|
||||||
|
const k = w.email || w.wallet; if (pinged.has(k)) return; pinged.set(k, 1);
|
||||||
|
hubCall('/v1/activity', Object.assign({ kind: 'visit' }, w), 5000).then(r => { if (r.status >= 500) pinged.delete(k); }).catch(() => { pinged.delete(k); });
|
||||||
|
}
|
||||||
|
// a signed-in request the site already answers (2026-11-16, Marty: "LinkSpin never reports activity"): /api/me, the dashboard
|
||||||
|
// heartbeat (/api/my/ping) and the admin portal call this, so a Control Room tab kept open for days, a browser that sends no
|
||||||
|
// Sec-Fetch headers and a wallet-only session still count the day's visit. The page-load ping in page() only sees full navigations.
|
||||||
|
// s = {email} and/or {address}. Same once-a-day rule as page(). -> true when a ping was due or already sent today.
|
||||||
|
function seen(s) {
|
||||||
|
try {
|
||||||
|
if (!C || !hubCreds()) return false;
|
||||||
|
const w = who(s && s.email ? s : s && s.address ? { address: s.address } : null); if (!w) return false;
|
||||||
|
activity(w); return true;
|
||||||
|
} catch (e) { return false; }
|
||||||
|
}
|
||||||
|
// a real top-level page load of a page (never an API call, an asset, a fetch, a bot or one of our own hops)
|
||||||
|
function pageLoad(req, p) {
|
||||||
|
if (req.method !== 'GET' || isBot(req)) return false;
|
||||||
|
if (req.headers['sec-fetch-dest'] !== 'document' || (req.headers['sec-fetch-mode'] && req.headers['sec-fetch-mode'] !== 'navigate')) return false;
|
||||||
|
if (/^\/(sso|api|go|assets|art|img|fonts|uploads|admin)(\/|$)/.test(p)) return false;
|
||||||
|
return !/\.[a-z0-9]{1,5}$/i.test(p);
|
||||||
|
}
|
||||||
|
async function signOutEverywhere(s) {
|
||||||
|
const w = who(s); if (!w || !hubCreds()) return { ok: false, reason: !w ? 'signed out' : 'hub off' };
|
||||||
|
try { const r = await hubCall('/v1/sso/signout', w, 8000); return r.status === 200 ? Object.assign({ ok: true }, r.json || {}) : { ok: false, reason: 'hub ' + r.status }; }
|
||||||
|
catch (e) { return { ok: false, reason: 'hub unreachable' }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
|
||||||
|
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
|
||||||
|
const used = new Map(); let fileLoaded = false, tableReady = null;
|
||||||
|
const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null;
|
||||||
|
function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); }
|
||||||
|
function loadFile() {
|
||||||
|
if (fileLoaded) return; fileLoaded = true;
|
||||||
|
try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {}
|
||||||
|
}
|
||||||
|
function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } }
|
||||||
|
async function spend(n, exp) {
|
||||||
|
const now = Date.now(); loadFile(); prune(now);
|
||||||
|
if (used.has(n)) return false;
|
||||||
|
used.set(n, Number(exp) + SKEW); saveFile();
|
||||||
|
const db = C && C.db;
|
||||||
|
if (db && db.enabled && db.enabled()) {
|
||||||
|
try {
|
||||||
|
if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; });
|
||||||
|
await tableReady;
|
||||||
|
await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]);
|
||||||
|
if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {});
|
||||||
|
} catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// crawlers, link previews and headless browsers never bounce
|
||||||
|
const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i;
|
||||||
|
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); };
|
||||||
|
// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser)
|
||||||
|
const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; };
|
||||||
|
|
||||||
|
function cookies(req) {
|
||||||
|
const out = {};
|
||||||
|
for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : '');
|
||||||
|
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
|
||||||
|
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
|
||||||
|
|
||||||
|
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); if (hubOn()) { hubSeen = 0; hubChecked = 0; hubUp().catch(() => {}); } hubSites = {}; hubSitesAt = 0; if (C.wallet) loadHubSites(); }
|
||||||
|
|
||||||
|
// a site this provider answers for: its own list first, then the hub's (never itself, never the peer, which has its own path)
|
||||||
|
function siteBase(x) {
|
||||||
|
if (!C || !C.wallet || !SITE_RE.test(String(x || '')) || x === C.self || x === C.peer) return null;
|
||||||
|
if (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x)) return C.wallets[x];
|
||||||
|
if (Object.prototype.hasOwnProperty.call(hubSites, x)) { const b = hubSites[x]; return () => b; }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// an unknown site asking: ask the hub once more (at most every 30 s, 2 s at most) before refusing
|
||||||
|
async function siteBaseFresh(x) { let b = siteBase(x); if (!b && C && C.wallet && SITE_RE.test(String(x || '')) && Date.now() - hubSitesAt > 30000) { await loadHubSites(); b = siteBase(x); } return b; }
|
||||||
|
const siteName = x => NAMES[x] || ({ viraladsource: 'ViralAdSource', webworthit: 'WebWorthIt', stackpol: 'Stack POL' })[x] || x;
|
||||||
|
const retOf = req => { const m = /^([a-z0-9_-]{1,64})\|(\/.*)$/.exec(cookies(req)['nsso.ret'] || ''); return m ? { site: m[1], to: safePath(m[2], '/') } : null; };
|
||||||
|
// signed in here, on the way back to a site: its wallet step first when the site needs a wallet this account does not have yet
|
||||||
|
async function backHop(s, site, to, set) {
|
||||||
|
let w = null; try { w = await C.wallet(s); } catch (e) {}
|
||||||
|
if ((!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) && C.walletPath) { set.push(ck('nsso.wait', '1', BACK_AGE, true)); log('back: wallet step first', s.email, 'for ' + siteName(site)); return C.walletPath; }
|
||||||
|
return '/go/' + site + '?to=' + encodeURIComponent(to);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
|
||||||
|
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
||||||
|
|
||||||
|
// -> true when the request was one of ours and has been answered
|
||||||
|
async function handle(req, res, u) {
|
||||||
|
if (!C || req.method !== 'GET') return false;
|
||||||
|
const p = u.pathname;
|
||||||
|
if (C.wallet && u.searchParams.has('return') && !/^\/(sso|api|go)(\/|$)/.test(p)) { // a site's "sign in / join on <provider>" link: remember the way back (2026-11-17)
|
||||||
|
const site = String(u.searchParams.get('return') || '').toLowerCase(); const to = safePath(u.searchParams.get('to'), '/');
|
||||||
|
const clean = new URL(u.pathname + u.search, 'http://x.invalid'); clean.searchParams.delete('return'); clean.searchParams.delete('to');
|
||||||
|
const here = safePath(clean.pathname + clean.search, '/');
|
||||||
|
const base = isBot(req) ? null : await siteBaseFresh(site);
|
||||||
|
if (!base) return go(res, here); // unknown site (or a bot): the page itself, nothing remembered
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (s && s.email) { // signed in here already: straight back (wallet step first when the site needs one)
|
||||||
|
const set = []; const hop = await backHop(s, site, to, set);
|
||||||
|
set.push(hop === C.walletPath ? ck('nsso.ret', site + '|' + to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
|
||||||
|
return go(res, hop, set);
|
||||||
|
}
|
||||||
|
log('return link remembered', null, 'for ' + siteName(site));
|
||||||
|
return go(res, here, [ck('nsso.ret', site + '|' + to, RET_AGE, true), ck('nsso.wait', '', 0, true)]);
|
||||||
|
}
|
||||||
|
const peerName = NAMES[C.peer] || C.peer;
|
||||||
|
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
|
||||||
|
const walletBase = siteBase; freshSites(); // the hand-written list, then the hub's sign-in sites (2026-11-17)
|
||||||
|
if (goTo && (goTo === C.peer || walletBase(goTo))) {
|
||||||
|
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
|
||||||
|
const to = safePath(u.searchParams.get('to'), '/');
|
||||||
|
const plain = base + to;
|
||||||
|
if (!enabled() || isBot(req)) return go(res, plain);
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (!s || !s.email) return go(res, plain);
|
||||||
|
if (goTo !== C.peer) { let w = null; try { w = await C.wallet(s); } catch (e) {} if (!w || !w.address) return go(res, plain); } // no wallet to vouch for: a plain link
|
||||||
|
return go(res, base + '/sso/start?mode=go' + (goTo === C.peer ? '' : '&via=' + C.self) + '&to=' + encodeURIComponent(to));
|
||||||
|
}
|
||||||
|
if (p === '/sso/start') {
|
||||||
|
const to = safePath(u.searchParams.get('to'), C.defaultPath);
|
||||||
|
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
|
||||||
|
const via = String(u.searchParams.get('via') || '');
|
||||||
|
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
|
||||||
|
const viaHub = hubOn() && !u.searchParams.get('nohub') && (await hubUp());
|
||||||
|
if (!(enabled() || viaHub) || isBot(req) || notPage(req)) return go(res, to);
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (s && (s.email || s.address)) return go(res, to); // already signed in here
|
||||||
|
const c = cookies(req);
|
||||||
|
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off']) && !u.searchParams.get('nohub')) return go(res, to);
|
||||||
|
const st = crypto.randomBytes(16).toString('hex');
|
||||||
|
if (viaHub) { // the hub answers for the whole network; the pairwise provider is the fallback when it has nobody (nsso.via)
|
||||||
|
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true), ck('nsso.via', via || '-', STATE_AGE, true)];
|
||||||
|
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||||
|
return go(res, HUB_BASE() + '/sso/check?site=' + encodeURIComponent(HUB_NAME()) + '&st=' + st + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
||||||
|
}
|
||||||
|
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
||||||
|
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||||
|
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
||||||
|
}
|
||||||
|
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
|
||||||
|
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
|
||||||
|
const clear = [ck('nsso.back', '', 0, true), ck('nsso.wait', '', 0, true)];
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) { // no deliberate tap waiting: a ?return=<site> link may be (2026-11-17)
|
||||||
|
const ret = retOf(req);
|
||||||
|
if (!ret || !siteBase(ret.site)) return go(res, C.defaultPath, clear.concat(ck('nsso.ret', '', 0, true)));
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (!s || !s.email) return go(res, C.signinPath(C.defaultPath)); // not signed in yet: keep it for after the sign-in
|
||||||
|
const set = clear.slice(); const hop = await backHop(s, ret.site, ret.to, set);
|
||||||
|
set.push(hop === C.walletPath ? ck('nsso.ret', ret.site + '|' + ret.to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
|
||||||
|
log('back to ' + siteName(ret.site), s.email); return go(res, hop, set);
|
||||||
|
}
|
||||||
|
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')) + '&m=go', clear); // m=go: still a deliberate tap (the wallet step when one is missing)
|
||||||
|
}
|
||||||
|
if (p === '/sso/check') {
|
||||||
|
const st = String(u.searchParams.get('st') || '');
|
||||||
|
const to = safePath(u.searchParams.get('to'), '/');
|
||||||
|
const r = String(u.searchParams.get('r') || '');
|
||||||
|
const wb = r && r !== C.peer ? await siteBaseFresh(r) : null; // a wallet site asking: the token carries the wallet (the hub's sign-in sites too, 2026-11-17)
|
||||||
|
if (r && r !== C.peer && !wb) { log('check: unknown site asking, nothing sent', null, r.slice(0, 20)); return go(res, C.defaultPath); } // never answer an unknown site as if the peer asked (2026-11-15: 5xYourTeam was sent to LinkSpin)
|
||||||
|
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = siteName(aud);
|
||||||
|
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
||||||
|
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (!s || !s.email) {
|
||||||
|
if (u.searchParams.get('m') === 'go' && !isBot(req)) { // a deliberate tap: sign in here first, then /sso/resume finishes the trip
|
||||||
|
log('check: not signed in here, asking to sign in', null, 'for ' + forName);
|
||||||
|
const back = new URLSearchParams({ st, to }); if (r) back.set('r', r);
|
||||||
|
return go(res, C.signinPath(C.defaultPath), [ck('nsso.back', back.toString(), BACK_AGE, true)]);
|
||||||
|
}
|
||||||
|
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
|
||||||
|
}
|
||||||
|
let w = null;
|
||||||
|
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) {
|
||||||
|
if (u.searchParams.get('m') === 'go' && C.walletPath && !isBot(req)) { // a deliberate tap: link a wallet here first, then /sso/resume finishes the trip (2026-11-17)
|
||||||
|
log('check: no wallet on the account, wallet step first', s.email, 'for ' + forName);
|
||||||
|
const back = new URLSearchParams({ st, to, m: 'go' }); if (r) back.set('r', r);
|
||||||
|
return go(res, C.walletPath, [ck('nsso.back', back.toString(), BACK_AGE, true), ck('nsso.wait', '1', BACK_AGE, true)]);
|
||||||
|
}
|
||||||
|
log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
|
||||||
|
log('token issued', s.email, 'for ' + forName);
|
||||||
|
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
|
||||||
|
}
|
||||||
|
if (p === '/sso/in') {
|
||||||
|
const c = cookies(req);
|
||||||
|
const set = [ck('nsso.st', '', 0, true)];
|
||||||
|
if (u.searchParams.get('none')) {
|
||||||
|
const nto = safePath(u.searchParams.get('to'), C.defaultPath);
|
||||||
|
if (u.searchParams.get('hub') && enabled()) { // nobody on the hub: ask the old pairwise provider once (until every site is switched)
|
||||||
|
const via = String(c['nsso.via'] || ''); set.push(ck('nsso.via', '', 0, true));
|
||||||
|
log('none on the hub, trying ' + (NAMES[via] || peerName));
|
||||||
|
return go(res, '/sso/start?nohub=1&mode=' + (u.searchParams.get('m') === 'go' ? 'go' : 'check') + (via && via !== '-' ? '&via=' + encodeURIComponent(via) : '') + '&to=' + encodeURIComponent(nto), set);
|
||||||
|
}
|
||||||
|
log('none: not signed in on ' + (u.searchParams.get('hub') ? 'the hub' : peerName)); return go(res, C.signinPath(nto), set);
|
||||||
|
}
|
||||||
|
const fromHub = !!u.searchParams.get('h');
|
||||||
|
const v = fromHub ? verifyHub(u.searchParams.get('h'), { st: c['nsso.st'] }) : verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
|
||||||
|
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
|
||||||
|
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
|
||||||
|
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
|
||||||
|
if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in
|
||||||
|
log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email);
|
||||||
|
set.push(ck('nsso.hint', v.email, HINT_AGE, true));
|
||||||
|
return go(res, C.signinPath(v.to), set);
|
||||||
|
}
|
||||||
|
let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); }
|
||||||
|
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
|
||||||
|
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||||
|
if (fromHub) { const w2 = v.wallet && C.from ? { wallet: v.wallet } : { email: v.email }; set.push(ck('nsso.hp', pushTag(w2), PUSH_AGE, true)); } // the hub already has this sign-in
|
||||||
|
log('signed in from ' + (fromHub ? 'the network hub' : (NAMES[v.iss] || peerName)), v.email);
|
||||||
|
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
|
||||||
|
}
|
||||||
|
if (p === '/api/sso/status') {
|
||||||
|
const c = cookies(req); const set = [];
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
const signedIn = !!(s && (s.email || s.address));
|
||||||
|
const out = { peer: hubOn() ? 'the network' : peerName, check: (enabled() || (hubOn() && (await hubUp()))) && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
||||||
|
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
|
||||||
|
return sendJson(res, out, set);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// every GET a site serves passes here first (2026-11-15): a signed-in member's real page load pings the hub's activity once a day and,
|
||||||
|
// with the hub on, tells the hub about this sign-in once (nsso.hp). -> true when it answered (the redirect through the hub).
|
||||||
|
async function page(req, res, u) {
|
||||||
|
if (!C || !hubCreds()) return false;
|
||||||
|
const p = u.pathname;
|
||||||
|
if (!pageLoad(req, p)) return false;
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
const w = who(s); if (!w) return false;
|
||||||
|
activity(w);
|
||||||
|
if (hubOn() && cookies(req)['nsso.hp'] !== pushTag(w) && (await hubUp())) {
|
||||||
|
log('hub: telling the hub about this sign-in', w.email || null);
|
||||||
|
return go(res, HUB_BASE() + '/sso/set?site=' + encodeURIComponent(HUB_NAME()) + '&t=' + mintHub(Object.assign({ to: p + u.search }, w)), [ck('nsso.hp', pushTag(w), PUSH_AGE, true)]);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// true when this browser came here from a deliberate network tap (nsso.back) or a ?return=<site> link (nsso.ret) and still has to
|
||||||
|
// finish it after signing in. False while it waits on the wallet step (nsso.wait): the dashboard must not bounce it back and forth.
|
||||||
|
const pendingBack = req => { const c = cookies(req); return !!(c['nsso.back'] || retOf(req)) && !c['nsso.wait']; };
|
||||||
|
// the wallet was just linked: the next hop when a way back is waiting (2026-11-17), else null
|
||||||
|
const afterWallet = req => { const c = cookies(req); return c['nsso.back'] || retOf(req) ? '/sso/resume' : null; };
|
||||||
|
// the name of the site a member is on the way back to, for a line on the provider's dashboard; null when none
|
||||||
|
function backName(req) {
|
||||||
|
const c = cookies(req); const ret = retOf(req);
|
||||||
|
if (ret) return siteName(ret.site);
|
||||||
|
if (!c['nsso.back']) return null;
|
||||||
|
const r = new URLSearchParams(c['nsso.back']).get('r'); return siteName(r || (C && C.peer) || '') || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, handle, page, seen, enabled, pendingBack, afterWallet, backName, siteBase, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES, hubOn, hubCreds, signOutEverywhere, mintHub, verifyHub, _hubSeen: t => { hubSeen = t == null ? Date.now() : t; hubChecked = Date.now(); }, _pinged: pinged, _hubSites: o => { if (o) { hubSites = o; hubSitesAt = Date.now(); } return hubSites; } };
|
||||||
Generated
+133
@@ -8,9 +8,20 @@
|
|||||||
"name": "stackpol",
|
"name": "stackpol",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"mysql2": "3.24.6",
|
||||||
"qrcode": "1.5.4"
|
"qrcode": "1.5.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/node": {
|
||||||
|
"version": "26.6.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
|
||||||
|
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"undici-types": "~8.9.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ansi-regex": {
|
"node_modules/ansi-regex": {
|
||||||
"version": "5.0.1",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||||
@@ -35,6 +46,15 @@
|
|||||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/aws-ssl-profiles": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/camelcase": {
|
"node_modules/camelcase": {
|
||||||
"version": "5.3.1",
|
"version": "5.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
||||||
@@ -107,6 +127,15 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/generate-function": {
|
||||||
|
"version": "2.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
|
||||||
|
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"is-property": "^1.0.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/get-caller-file": {
|
"node_modules/get-caller-file": {
|
||||||
"version": "2.0.5",
|
"version": "2.0.5",
|
||||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||||
@@ -116,6 +145,22 @@
|
|||||||
"node": "6.* || 8.* || >= 10.*"
|
"node": "6.* || 8.* || >= 10.*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/iconv-lite": {
|
||||||
|
"version": "0.7.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
|
||||||
|
"integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/express"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/is-fullwidth-code-point": {
|
"node_modules/is-fullwidth-code-point": {
|
||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||||
@@ -125,6 +170,12 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/is-property": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/locate-path": {
|
"node_modules/locate-path": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
|
||||||
@@ -137,6 +188,60 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/long": {
|
||||||
|
"version": "5.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
|
||||||
|
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
|
||||||
|
"license": "Apache-2.0"
|
||||||
|
},
|
||||||
|
"node_modules/lru.min": {
|
||||||
|
"version": "1.1.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.5.tgz",
|
||||||
|
"integrity": "sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"bun": ">=1.0.0",
|
||||||
|
"deno": ">=1.30.0",
|
||||||
|
"node": ">=8.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/wellwelwel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/mysql2": {
|
||||||
|
"version": "3.24.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz",
|
||||||
|
"integrity": "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"aws-ssl-profiles": "^1.1.2",
|
||||||
|
"generate-function": "^2.3.1",
|
||||||
|
"iconv-lite": "^0.7.3",
|
||||||
|
"long": "^5.3.2",
|
||||||
|
"lru.min": "^1.1.4",
|
||||||
|
"named-placeholders": "^1.1.6",
|
||||||
|
"sql-escaper": "^1.5.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/named-placeholders": {
|
||||||
|
"version": "1.1.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz",
|
||||||
|
"integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"lru.min": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/p-limit": {
|
"node_modules/p-limit": {
|
||||||
"version": "2.3.0",
|
"version": "2.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
||||||
@@ -223,12 +328,33 @@
|
|||||||
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
|
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/safer-buffer": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/set-blocking": {
|
"node_modules/set-blocking": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||||
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/sql-escaper": {
|
||||||
|
"version": "1.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.7.0.tgz",
|
||||||
|
"integrity": "sha512-ZgP6E9SPnhrhWXxd8+nLKPot3Euzyo3Rpxe6EFAYz2Ffaq9Xg2SH+6d4yJi7vsQDHaQlhzQ1phAopgE6+a1UCQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"bun": ">=1.0.0",
|
||||||
|
"deno": ">=2.0.0",
|
||||||
|
"node": ">=12.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/string-width": {
|
"node_modules/string-width": {
|
||||||
"version": "4.2.3",
|
"version": "4.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||||
@@ -255,6 +381,13 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/undici-types": {
|
||||||
|
"version": "8.9.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
|
||||||
|
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peer": true
|
||||||
|
},
|
||||||
"node_modules/which-module": {
|
"node_modules/which-module": {
|
||||||
"version": "2.0.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{ "name": "stackpol", "version": "1.0.0", "private": true, "main": "server.js", "scripts": { "start": "node server.js" }, "dependencies": { "qrcode": "1.5.4" } }
|
{"name":"stackpol","version":"1.0.0","private":true,"main":"server.js","scripts":{"start":"node server.js"},"dependencies":{"mysql2":"3.24.6","qrcode":"1.5.4"}}
|
||||||
+30
-4
@@ -1,5 +1,6 @@
|
|||||||
// The programs a Stack POL page can show (2026-11-09). Keys match the indexer (tools/indexer.py). Blurbs for the games are
|
// The programs a Stack POL page can show (2026-11-09). Keys match the indexer (tools/indexer.py). Blurbs for the games are
|
||||||
// InstantAdPay's own game descriptions (onchain-ad-membership/site server.js GAMES), so this site never invents how a game pays.
|
// InstantAdPay's own game descriptions (onchain-ad-membership/site server.js GAMES), so this site never invents how a game pays.
|
||||||
|
// guides (2026-11-17): the program's own evergreen Guides section, linked from its page and the blog index.
|
||||||
// join(u): the member's own referral link; the network pages use the site owner's (martbost).
|
// join(u): the member's own referral link; the network pages use the site owner's (martbost).
|
||||||
'use strict';
|
'use strict';
|
||||||
const { tracked } = require('./netsites');
|
const { tracked } = require('./netsites');
|
||||||
@@ -11,20 +12,45 @@ const PROGRAMS = [
|
|||||||
{ k: 'ls', slug: 'linkspin', n: 'LinkSpin', c: '#3b82f6', kind: 'Link tools', site: 'https://linkspin.app', join: u => 'https://linkspin.app/join/' + encodeURIComponent(u),
|
{ k: 'ls', slug: 'linkspin', n: 'LinkSpin', c: '#3b82f6', kind: 'Link tools', site: 'https://linkspin.app', join: u => 'https://linkspin.app/join/' + encodeURIComponent(u),
|
||||||
d: 'Free link tools: spin links that rotate your traffic, bridge pages built from any offer link, banner spins and ad zones. Package sales pay the sponsor line in POL in the same transaction.',
|
d: 'Free link tools: spin links that rotate your traffic, bridge pages built from any offer link, banner spins and ad zones. Package sales pay the sponsor line in POL in the same transaction.',
|
||||||
how: 'Payouts here are the referral payments the LinkSpin smart contract sends up the sponsor line when a package sells, in the same transaction as the purchase.' },
|
how: 'Payouts here are the referral payments the LinkSpin smart contract sends up the sponsor line when a package sells, in the same transaction as the purchase.' },
|
||||||
{ k: 'dlb', slug: 'downline-banners', n: 'Downline Banners', c: '#c6f432', kind: 'Banner board', verb: 'Join', app: true, site: 'https://downlinebanners.com', join: u => 'https://downlinebanners.com/?ref=' + encodeURIComponent(u),
|
{ k: 'dlb', guides: 'https://downlinebanners.com/guides', slug: 'downline-banners', n: 'Downline Banners', c: '#c6f432', kind: 'Banner board', verb: 'Join', app: true, site: 'https://downlinebanners.com', join: u => 'https://downlinebanners.com/?ref=' + encodeURIComponent(u),
|
||||||
d: 'The network banner board on Polygon. A $5 spot buys 300 guaranteed views on the board and a place in one line; when later spots sell, the contract pays the 10 spots above them and the buyer\'s sponsor in the same transaction. Nothing is promised.',
|
d: 'The network banner board on Polygon. A $5 spot buys 300 guaranteed views on the board and a place in one line; when later spots sell, the contract pays the 10 spots above them and the buyer\'s sponsor in the same transaction. Nothing is promised.',
|
||||||
how: 'Payouts here are the payments the Downline Banners smart contract sends to the buyer\'s sponsor and to the 10 spots above each new spot, in the same transaction as the sale. Company and momentum-fund shares are not counted.' },
|
how: 'Payouts here are the payments the Downline Banners smart contract sends to the buyer\'s sponsor and to the 10 spots above each new spot, in the same transaction as the sale. Company and momentum-fund shares are not counted.' },
|
||||||
// Viral Banner Blitz (live 2026-11-14): join through the LinkSpin network link (nwvbb, src=stackpol) so LinkSpin Reports show Stack POL as
|
// Viral Banner Blitz (live 2026-11-14): join through the LinkSpin network link (nwvbb, src=stackpol) so LinkSpin Reports show Stack POL as
|
||||||
// the source; it lands on viralbannerblitz.com/?ref=<username>. Facts from the VBB app (how.html, config.js) and the VBBShop contract.
|
// the source; it lands on viralbannerblitz.com/?ref=<username>. Facts from the VBB app (how.html, config.js) and the VBBShop contract.
|
||||||
{ k: 'vbb', slug: 'viral-banner-blitz', n: 'Viral Banner Blitz', c: '#ff2d87', kind: 'Banner loop', verb: 'Join', app: true, site: 'https://viralbannerblitz.com', join: u => tracked('vbb', 'stackpol', { s1: u }),
|
{ k: 'vbb', guides: 'https://viralbannerblitz.com/guides', slug: 'viral-banner-blitz', n: 'Viral Banner Blitz', c: '#ff2d87', kind: 'Banner loop', verb: 'Join', app: true, site: 'https://viralbannerblitz.com', join: u => tracked('vbb', 'stackpol', { s1: u }),
|
||||||
d: 'A shared loop of 125x125 banners that real visitors move. Network members post one banner free every day they sign in; every 10 verified visitors shift the loop one place, and a banner that rides out has cycled and earns 150 network ad views (advertising, not cash). Weekly leaderboards share a prize pot in POL. Credit packs ($3 for 10, $10 for 40) and a $2 banner look are one-time purchases with SafePal or any other crypto wallet, never a subscription. Nothing is promised.',
|
d: 'A shared loop of 125x125 banners that real visitors move. Network members post one banner free every day they sign in; every 10 verified visitors shift the loop one place, and a banner that rides out has cycled and earns 150 network ad views (advertising, not cash). Weekly leaderboards share a prize pot in POL. Credit packs ($3 for 10, $10 for 40) and a $2 banner look are one-time purchases with SafePal or any other crypto wallet, never a subscription. Nothing is promised.',
|
||||||
how: 'Payouts here are the 30% sponsor share the Viral Banner Blitz smart contract pays to the buyer\'s sponsor in the same transaction as each purchase, plus the weekly leaderboard prizes sent in POL from the prize wallet to the winners\' wallets. The prize-wallet and company shares are not counted.' },
|
how: 'Payouts here are the 30% sponsor share the Viral Banner Blitz smart contract pays to the buyer\'s sponsor in the same transaction as each purchase, plus the weekly leaderboard prizes sent in POL from the prize wallet to the winners\' wallets. The prize-wallet and company shares are not counted.' },
|
||||||
// ViralAdBlitz (live 2026-11-15): join through the LinkSpin network link (nwvab, src=stackpol), landing on viraladblitz.com/?ref=<username>.
|
// ViralAdBlitz (live 2026-11-15): join through the LinkSpin network link (nwvab, src=stackpol), landing on viraladblitz.com/?ref=<username>.
|
||||||
// Facts from the VAB app (README, how page) and the VABShop contract 0xb584...2905 only.
|
// Facts from the VAB app (README, how page) and the VABShop contract 0xb584...2905 only.
|
||||||
{ k: 'vab', slug: 'viraladblitz', n: 'ViralAdBlitz', c: '#0a2fa8', kind: 'Viral text ads', verb: 'Join', app: true, site: 'https://viraladblitz.com', join: u => tracked('viraladblitz', 'stackpol', { s1: u }),
|
{ k: 'vab', guides: 'https://viraladblitz.com/guides', slug: 'viraladblitz', n: 'ViralAdBlitz', c: '#0a2fa8', kind: 'Viral text ads', verb: 'Join', app: true, site: 'https://viraladblitz.com', join: u => tracked('viraladblitz', 'stackpol', { s1: u }),
|
||||||
d: 'The network\'s home for text ads. Network members post one text ad free; your member page shows your ad and the ads of the five people above you, so every person you bring in shows your ad on their page, five levels deep. A $5 Boost is a one-time purchase of 500 guaranteed network views, paid with SafePal or any other crypto wallet, never a subscription. The contract pays 10% of each Boost to each of five levels up the buyer\'s line in the same transaction. Nothing is promised.',
|
d: 'The network\'s home for text ads. Network members post one text ad free; your member page shows your ad and the ads of the five people above you, so every person you bring in shows your ad on their page, five levels deep. A $5 Boost is a one-time purchase of 500 guaranteed network views, paid with SafePal or any other crypto wallet, never a subscription. The contract pays 10% of each Boost to each of five levels up the buyer\'s line in the same transaction. Nothing is promised.',
|
||||||
how: 'Payouts here are the level shares the ViralAdBlitz smart contract pays to five people up the buyer\'s line (10% each, to people who have bought a Boost themselves) in the same transaction as each Boost. The company share is not counted.' },
|
how: 'Payouts here are the level shares the ViralAdBlitz smart contract pays to five people up the buyer\'s line (10% each, to people who have bought a Boost themselves) in the same transaction as each Boost. The company share is not counted.' },
|
||||||
{ k: 'ph', slug: 'polhunter', n: 'PolHunter', c: '#a3e635', kind: 'Scavenger hunt', site: 'https://polhunter.com', join: g('polhunter'),
|
// ViralAdSource (live 2026-11-17): join through the LinkSpin network link (nwvas, src=stackpol), landing on viraladsource.com/?ref=<username>.
|
||||||
|
// Facts from the VAS app (approved launch numbers) and the VASShop contract 0x7EFe...4f24 only.
|
||||||
|
{ k: 'vas', guides: 'https://viraladsource.com/guides', slug: 'viraladsource', n: 'ViralAdSource', c: '#c4371b', kind: 'Reshared text ads', verb: 'Join', app: true, site: 'https://viraladsource.com', join: u => tracked('viraladsource', 'stackpol', { s1: u }),
|
||||||
|
d: 'Free text ads that travel by reshares. Network members post a text ad free; anyone can reshare it with their own link, and every reshare shows as a branch on the ad\'s family tree. A $5 Boost is a one-time purchase that puts an ad on top of the reshare board for 7 days, paid with SafePal or any other crypto wallet, never a subscription. The contract splits each Boost in the same transaction: 20% to the resharer whose link it came through, 10% to each of five levels up the buyer\'s line and 10% to a capped reward pot. No Boost is needed to receive a share. Nothing is promised.',
|
||||||
|
how: 'Payouts here are what the ViralAdSource smart contract pays members in the same transaction as each Boost (the 20% resharer cut and the 10% level shares, five levels up the buyer\'s line), plus the small new-member rewards paid from its reward pot. The company share is not counted.' },
|
||||||
|
// YourProgramBuilder (live 2026-11-17): join through the LinkSpin network link (nwypb, src=stackpol), landing on yourprogrambuilder.com/?ref=<username>.
|
||||||
|
// Facts from the YPB app (decision pack answers 2026-11-17) and the YPBShop contract 0x44A0...3E2a only.
|
||||||
|
{ k: 'ypb', guides: 'https://yourprogrambuilder.com/guides', slug: 'yourprogrambuilder', n: 'YourProgramBuilder', c: '#22844a', kind: 'Program directory', verb: 'Join', app: true, site: 'https://yourprogrambuilder.com', join: u => tracked('yourprogrambuilder', 'stackpol', { s1: u }),
|
||||||
|
d: 'An open program directory the network grows. Plant a program you already use, free: your link with your ID, checked every day. Network members save their own IDs in it, and a visitor who comes through a member sees the link of the member they came through first. At 10 saved IDs a program goes to review for the Crypto Team Build Network builder. A $10 Spotlight is a one-time purchase of 1,000 views, paid with SafePal or any other crypto wallet, never a subscription. Nothing is promised.',
|
||||||
|
how: 'Payouts here are the shares the YPBShop smart contract pays up the line of the buyer in the same transaction as each Spotlight: 20% to the direct sponsor and 5% to each of the next four levels. No Spotlight is needed to receive a share. The company share is not counted.' },
|
||||||
|
// Video App Income (live 2026-11-20): direct join link carrying the network username (videoappincome.com/join?ref=<username>; the site
|
||||||
|
// resolves the username through the hub). Facts from the VAI app (site.js, server.js) and the VideoAppIncome contract 0x0cfF...C201 only.
|
||||||
|
{ k: 'vai', slug: 'video-app-income', n: 'Video App Income', c: '#8b5cf6', kind: 'Video maker', verb: 'Join', app: true, site: 'https://videoappincome.com', join: u => 'https://videoappincome.com/join?ref=' + encodeURIComponent(u),
|
||||||
|
d: 'Make short vertical promo videos from your phone for any website, offer or niche. Paste a link and the app reads the page, writes the script and adds the voice, captions, footage of the site and music in about a minute and a half, no camera needed. Every video gets a tracked share page with a button to your link, so you can see who opened it, how much they watched and who tapped. Sign in with SafePal or any other crypto wallet, or with your network account. The first video is free; after that a video is 10 credits, and a $10 pack is 100 credits, a one-time purchase in POL, never a subscription. Nothing is promised.',
|
||||||
|
how: 'Payouts here are the shares the Video App Income smart contract pays members in the same transaction as each credit purchase: 30% to the buyer\'s sponsor and 8% to each of the five positions above the buyer in a 3-wide matrix, to people who have bought credits themselves. The company shares are not counted.' },
|
||||||
|
// 5xYourTeam The Draft (live 2026-11-15): join through the LinkSpin network link (nw5x, src=stackpol), landing on 5xyourteam.com/?ref=<username>.
|
||||||
|
// Facts from the 5x app (README, config) and the DraftPosition contract 0x83Bb...bc74 only.
|
||||||
|
{ k: 'fx', guides: 'https://5xyourteam.com/guides', slug: '5xyourteam', n: '5xYourTeam', c: '#ffc93c', kind: 'Team draft', verb: 'Join', app: true, site: 'https://5xyourteam.com', join: u => tracked('fivex', 'stackpol', { s1: u }),
|
||||||
|
d: 'A weekly sports-style draft of people waiting in the network holding tank. A $10 position is a one-time purchase with SafePal or any other crypto wallet, never a subscription: it gives 5 picks right away and a spot in every Monday draft, where coaches pick people to sponsor and help. Draft order is earned by how many of last week\'s picks got started. Nothing is promised.',
|
||||||
|
how: 'Payouts here are the shares the DraftPosition smart contract pays up the buyer\'s line in the same transaction as each position: 25% to the sponsor and 5% to each of four more levels (to people who hold a position themselves). The weekly Best Coach pot and the company share are not counted.' },
|
||||||
|
// DownlineHydra (live 2026-11-15): join through the LinkSpin network link (nwdh, src=stackpol), landing on downlinehydra.com/?ref=<username>.
|
||||||
|
// Facts from the DH app (terms, /pro, config) and the HydraPro contract 0xEd07...4e90 only.
|
||||||
|
{ k: 'dh', guides: 'https://downlinehydra.com/guides', slug: 'downlinehydra', n: 'DownlineHydra', c: '#b4471f', kind: 'Downline builder', verb: 'Join', app: true, site: 'https://downlinehydra.com', join: u => tracked('downlinehydra', 'stackpol', { s1: u }),
|
||||||
|
d: 'The network\'s front door: join once and you are a member of every network site, with one sponsor line through all of them. Save your referral ID for each program in the builder and the people who join through you see your link first; free members show one program of their own to their team, five levels deep. Pro is $30, a one-time purchase with SafePal or any other crypto wallet, never a subscription, and shows four. Nothing is promised.',
|
||||||
|
how: 'Payouts here are the shares the HydraPro smart contract pays up the buyer\'s line in the same transaction as each Pro upgrade: 20% to the direct sponsor (free or Pro) and 10% to each of the next four Pro members above them. The company share is not counted.' },
|
||||||
|
{ k: 'ph', guides: 'https://polhunter.com/guides', slug: 'polhunter', n: 'PolHunter', c: '#a3e635', kind: 'Scavenger hunt', site: 'https://polhunter.com', join: g('polhunter'),
|
||||||
d: 'Hunt hidden codes on sites across the network. Every find drips POL straight to your wallet.' },
|
d: 'Hunt hidden codes on sites across the network. Every find drips POL straight to your wallet.' },
|
||||||
{ k: 'ec', slug: 'earners-corner', n: 'Earners Corner', c: '#a78bfa', kind: 'Community forum', site: 'https://earnerscorner.com', join: u => 'https://instantadpay.com/forum/join/' + encodeURIComponent(u),
|
{ k: 'ec', slug: 'earners-corner', n: 'Earners Corner', c: '#a78bfa', kind: 'Community forum', site: 'https://earnerscorner.com', join: u => 'https://instantadpay.com/forum/join/' + encodeURIComponent(u),
|
||||||
d: 'The network\'s forum for people who earn online. Activated InstantAdPay members get a one-time 1 POL welcome for introducing themselves.',
|
d: 'The network\'s forum for people who earn online. Activated InstantAdPay members get a one-time 1 POL welcome for introducing themselves.',
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/* Site assistant widget, Stack POL look (layout.js): deep violet night, gold for the stack, Sora headings, Manrope body.
|
||||||
|
Fallbacks match the layout's tokens. */
|
||||||
|
#scChat{--sc-bg:var(--panel,#130c24);--sc-bg2:var(--panel-2,#1b1232);--sc-ink:var(--ink,#f3efff);--sc-sub:var(--muted,#a8a0c6);--sc-line:var(--line,rgba(183,148,255,.18));
|
||||||
|
--sc-violet:var(--violet,#8247e5);--sc-violet-hi:var(--violet-hi,#b794ff);--sc-gold:var(--gold,#ffc24b);--sc-gold-d:var(--gold-d,#b9781a);
|
||||||
|
--sc-disp:var(--display,"Sora","Segoe UI",system-ui,sans-serif);--sc-font:var(--body,"Manrope",system-ui,sans-serif);
|
||||||
|
position:fixed;right:18px;bottom:18px;z-index:80;font-family:var(--sc-font)}
|
||||||
|
#scBtn{width:58px;height:58px;border-radius:18px;border:0;cursor:pointer;background:var(--sc-gold);color:#160b02;display:flex;align-items:center;justify-content:center;box-shadow:0 5px 0 var(--sc-gold-d),0 14px 30px rgba(255,194,75,.2)}
|
||||||
|
#scBtn:focus-visible{outline:2px solid var(--sc-violet-hi);outline-offset:4px}
|
||||||
|
#scChat.open #scBtn{background:var(--sc-violet);color:#fff;box-shadow:0 5px 0 #4b2394}
|
||||||
|
/* the panel sets display:flex, which would beat the hidden attribute: closing must win */
|
||||||
|
#scPanel[hidden]{display:none}
|
||||||
|
#scPanel{position:absolute;right:0;bottom:76px;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);border:1px solid var(--sc-line);border-radius:18px;box-shadow:0 24px 60px rgba(0,0,0,.55);overflow:hidden}
|
||||||
|
.sc-head{display:flex;align-items:flex-start;gap:10px;padding:14px 16px;background:linear-gradient(135deg,rgba(130,71,229,.35),rgba(19,12,36,0) 75%),var(--sc-bg2);border-bottom:1px solid var(--sc-line)}
|
||||||
|
.sc-head>div{flex:1;min-width:0}
|
||||||
|
.sc-title{display:block;font:800 19px var(--sc-disp);letter-spacing:-.01em}
|
||||||
|
.sc-sub{display:block;font-size:12.5px;color:var(--sc-sub)}
|
||||||
|
#scClose{background:transparent;border:0;color:var(--sc-sub);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.5;border-radius:14px;overflow-wrap:anywhere}
|
||||||
|
.sc-m.bot{align-self:flex-start;background:var(--sc-bg2);border:1px solid var(--sc-line);border-bottom-left-radius:4px}
|
||||||
|
.sc-m.me{align-self:flex-end;background:var(--sc-violet);color:#fff;border-bottom-right-radius:4px}
|
||||||
|
.sc-m a{color:var(--sc-gold);text-decoration:underline}
|
||||||
|
.sc-m.me a{color:#fff}
|
||||||
|
.sc-m.wait{opacity:.6}
|
||||||
|
.sc-cta{display:inline-block;background:var(--sc-gold);color:#160b02!important;text-decoration:none!important;font:800 14px var(--sc-disp);padding:8px 14px;border-radius:12px;box-shadow:0 4px 0 var(--sc-gold-d)}
|
||||||
|
.sc-handoff{background:transparent!important;border:0!important;padding:0!important}
|
||||||
|
.sc-topics{display:flex;flex-wrap:wrap;gap:6px;padding:0 14px 8px}
|
||||||
|
.sc-topics button{background:transparent;color:var(--sc-violet-hi);border:1px solid var(--sc-line);border-radius:999px;font:600 12.5px var(--sc-font);padding:5px 11px;cursor:pointer}
|
||||||
|
.sc-topics button:hover{border-color:var(--sc-violet-hi)}
|
||||||
|
.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);border-radius:12px;padding:10px 12px;font:15px var(--sc-font);color:var(--sc-ink);background:var(--ground,#0a0715)}
|
||||||
|
.sc-input input::placeholder{color:var(--sc-sub)}
|
||||||
|
.sc-input input:focus{outline:2px solid var(--sc-violet-hi);outline-offset:-1px}
|
||||||
|
.sc-input button{background:var(--sc-gold);color:#160b02;border:0;border-radius:12px;font:800 14px var(--sc-disp);padding:0 16px;cursor:pointer}
|
||||||
|
.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:68px;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=20261115e'; 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>'
|
||||||
|
+ '<div id="scPanel" role="dialog" aria-label="Questions" hidden>'
|
||||||
|
+ '<div 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></div>'
|
||||||
|
+ '<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>'
|
||||||
|
+ '</div>';
|
||||||
|
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(); });
|
||||||
|
})();
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// "Network Weekend" ribbon (Marty 2026-11-17): a thin bar at the top of every network site page while a network event is live.
|
||||||
|
// Data: /api/network-deals (netdeals.js, from the hub). Switches on and off by this page's own clock at the event's exact
|
||||||
|
// startsAt / endsAt (US Central midnights), so a cached feed never shows it early or late, and it takes itself down at endsAt on
|
||||||
|
// a page left open. Shows this site's own deal for today (byDay, Central date) and links to the full deals page.
|
||||||
|
// The same file lives in every network site. Never RM Circle, never the games. No inline styles (CSP): styles go through CSSOM.
|
||||||
|
// Test clock: window.__NW_NOW (ms) before this script runs; nothing else.
|
||||||
|
(function () {
|
||||||
|
if (window.__nwRibbon) return; window.__nwRibbon = 1;
|
||||||
|
var tag = document.currentScript;
|
||||||
|
var meAttr = (tag && tag.getAttribute('data-site')) || '';
|
||||||
|
function now() { return typeof window.__NW_NOW === 'number' ? window.__NW_NOW : Date.now(); }
|
||||||
|
// late November is CST (UTC-6) for every date this ribbon covers
|
||||||
|
function ctDay(ms) { return new Date(ms - 6 * 3600 * 1000).toISOString().slice(0, 10); }
|
||||||
|
function closedKey(id, day) { return 'nw.closed.' + id + '.' + day; }
|
||||||
|
function isClosed(id, day) { try { return window.localStorage.getItem(closedKey(id, day)) === '1'; } catch (e) { return false; } }
|
||||||
|
function setClosed(id, day) { try { window.localStorage.setItem(closedKey(id, day), '1'); } catch (e) {} }
|
||||||
|
var bar = null;
|
||||||
|
function remove() { if (bar && bar.parentNode) bar.parentNode.removeChild(bar); bar = null; }
|
||||||
|
function paint(body) {
|
||||||
|
var me = meAttr || (body && body.self) || '';
|
||||||
|
var t = now();
|
||||||
|
var ev = ((body && body.events) || []).filter(function (e) { return t >= Date.parse(e.startsAt) && t < Date.parse(e.endsAt); })[0];
|
||||||
|
if (!ev) { remove(); return false; }
|
||||||
|
var day = ctDay(t);
|
||||||
|
if (isClosed(ev.id, day)) { remove(); return true; }
|
||||||
|
var mine = (ev.deals || []).filter(function (d) { return d.site === me && t < Date.parse(d.endsAt || ev.endsAt); })[0];
|
||||||
|
var line = mine ? ((mine.byDay && mine.byDay[day]) || mine.text) : '';
|
||||||
|
var label = (ev.days && ev.days[day]) || '';
|
||||||
|
var onDealsPage = !!ev.url && (function () { try { var u = new URL(ev.url); return location.pathname === u.pathname && (location.hostname === u.hostname || me === 'iap'); } catch (e) { return false; } })();
|
||||||
|
remove();
|
||||||
|
bar = document.createElement('div');
|
||||||
|
bar.className = 'nw-ribbon'; bar.setAttribute('role', 'region'); bar.setAttribute('aria-label', ev.name);
|
||||||
|
bar.style.cssText = 'position:relative;z-index:50;display:flex;flex-wrap:wrap;gap:4px 12px;align-items:center;justify-content:center;padding:8px 40px 8px 16px;'
|
||||||
|
+ 'background:#14161b;color:#f4f1e8;font:600 13.5px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;text-align:center;border-bottom:2px solid #f2c94c';
|
||||||
|
// built node by node with CSSOM styles: no style attributes, so a strict CSP (style-src 'self') has nothing to block
|
||||||
|
function el(tagName, css, text) { var n = document.createElement(tagName); if (css) n.style.cssText = css; if (text) n.textContent = text; return n; }
|
||||||
|
var head = el('span'); head.appendChild(el('b', 'color:#f2c94c', ev.name)); if (label) head.appendChild(document.createTextNode(' · ' + label));
|
||||||
|
bar.appendChild(head);
|
||||||
|
var body2 = el('span', 'font-weight:500', line || ev.tagline);
|
||||||
|
if (line && mine && mine.note) { body2.appendChild(document.createTextNode(' ')); body2.appendChild(el('span', 'opacity:.75', mine.note)); }
|
||||||
|
bar.appendChild(body2);
|
||||||
|
if (ev.url && !onDealsPage) { var a = el('a', 'color:#f2c94c;text-decoration:underline', 'See every deal'); a.href = ev.url; a.target = '_blank'; a.rel = 'noopener'; bar.appendChild(a); }
|
||||||
|
var x = el('button', 'position:absolute;right:8px;top:50%;transform:translateY(-50%);background:none;border:0;color:#f4f1e8;font-size:18px;line-height:1;cursor:pointer;padding:4px 8px', '×');
|
||||||
|
x.type = 'button'; x.setAttribute('aria-label', 'Hide for today'); bar.appendChild(x);
|
||||||
|
bar.querySelector('button').addEventListener('click', function () { setClosed(ev.id, day); remove(); });
|
||||||
|
document.body.insertBefore(bar, document.body.firstChild);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
var feed = null, timer = null;
|
||||||
|
function schedule() {
|
||||||
|
clearTimeout(timer); if (!feed) return;
|
||||||
|
// wake at the next switch moment (start, end, a deal ending, the next Central midnight), at least once a minute
|
||||||
|
var t = now(), next = t + 60 * 1000;
|
||||||
|
(feed.events || []).forEach(function (e) {
|
||||||
|
[e.startsAt, e.endsAt].concat((e.deals || []).map(function (d) { return d.endsAt; })).forEach(function (s) { var x = Date.parse(s); if (x > t && x < next) next = x; });
|
||||||
|
});
|
||||||
|
timer = setTimeout(function () { if (typeof window.__NW_NOW === 'number') window.__NW_NOW += next - t; paint(feed); schedule(); }, Math.max(250, next - t));
|
||||||
|
}
|
||||||
|
function run() {
|
||||||
|
fetch('/api/network-deals', { credentials: 'omit' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (b) {
|
||||||
|
if (!b || !Array.isArray(b.events) || !b.events.length) return;
|
||||||
|
feed = b; paint(b); schedule();
|
||||||
|
}).catch(function () {});
|
||||||
|
}
|
||||||
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
||||||
|
window.__nwPaint = function (b) { feed = b; return paint(b); }; // tests
|
||||||
|
})();
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 58 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 60 KiB |
@@ -0,0 +1,675 @@
|
|||||||
|
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||||
|
<meta name="description" content="A one-page guide to the Crypto Team Build Network: one account across every site, everything on Polygon, where your ad shows up, and how payments split on the spot.">
|
||||||
|
<link rel="canonical" href="https://stackpol.com/network">
|
||||||
|
<meta property="og:title" content="How the Crypto Team Build Network Works"><meta property="og:description" content="One account, every site, all on Polygon. See how visitors travel, where ads show up and how every payment splits on the spot.">
|
||||||
|
<meta property="og:url" content="https://stackpol.com/network"><meta property="og:image" content="https://stackpol.com/og-stackpol-1200x630.jpg"><meta name="twitter:card" content="summary_large_image">
|
||||||
|
<link rel="icon" href="/favicon.svg">
|
||||||
|
<style>:root{padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}body{margin:0;font:14px system-ui,sans-serif}img{max-width:100%}[hidden]{display:none!important}</style>
|
||||||
|
</head><body>
|
||||||
|
<title>How the Crypto Team Build Network Works</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@600;700;800&family=Atkinson+Hyperlegible:wght@400;700&display=swap">
|
||||||
|
<style>
|
||||||
|
/* Layout: a transit map over violet POL glass. Colored "lines" (traffic, sites, money, trust) run down one long page; each section is a numbered stop; glass panels and coins carry the Polygon thread. */
|
||||||
|
:root{
|
||||||
|
--bg:#F3F2FB; --surface:#FFFFFF; --ink:#1B1E38; --muted:#4E5478; --rule:#DCDCEE;
|
||||||
|
--violet:#7B3FE4; --violet-2:#A77BFF; --violet-soft:#ECE3FF;
|
||||||
|
--glass:rgba(255,255,255,.62); --glass-edge:rgba(123,63,228,.28); --glass-shine:rgba(255,255,255,.9);
|
||||||
|
--orb-a:rgba(140,82,255,.30); --orb-b:rgba(80,160,255,.22);
|
||||||
|
--traffic:#EA6324; --sites:#2A7FD4; --money:#C98F00; --trust:#C9356A; --go:#1F9D6A;
|
||||||
|
--sites-soft:#DCEAFA; --trust-soft:#F8DDE7; --go-soft:#D9F2E7; --money-soft:#FBF0CF;
|
||||||
|
--on-color:#FFFFFF; --bar-ink:#1B1E38;
|
||||||
|
--display:"Plus Jakarta Sans","Segoe UI","Segoe UI",system-ui,sans-serif;
|
||||||
|
--body:"Atkinson Hyperlegible","Segoe UI",system-ui,sans-serif;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
|
||||||
|
--bg:#110F24; --surface:#1C1A36; --ink:#F0EEFB; --muted:#B0ACD0; --rule:#322E5A;
|
||||||
|
--violet:#A47BFF; --violet-2:#C9AEFF; --violet-soft:#2A2152;
|
||||||
|
--glass:rgba(40,32,82,.55); --glass-edge:rgba(180,150,255,.30); --glass-shine:rgba(255,255,255,.18);
|
||||||
|
--orb-a:rgba(140,82,255,.35); --orb-b:rgba(60,120,255,.22);
|
||||||
|
--traffic:#FF8A52; --sites:#5AA6F0; --money:#F2C14A; --trust:#EE6A98; --go:#45C792;
|
||||||
|
--sites-soft:#17304D; --trust-soft:#3D1C2B; --go-soft:#123828; --money-soft:#3A3014;
|
||||||
|
--on-color:#11102A; --bar-ink:#11102A;
|
||||||
|
color-scheme:dark}}
|
||||||
|
:root[data-theme="dark"]{
|
||||||
|
--bg:#110F24; --surface:#1C1A36; --ink:#F0EEFB; --muted:#B0ACD0; --rule:#322E5A;
|
||||||
|
--violet:#A47BFF; --violet-2:#C9AEFF; --violet-soft:#2A2152;
|
||||||
|
--glass:rgba(40,32,82,.55); --glass-edge:rgba(180,150,255,.30); --glass-shine:rgba(255,255,255,.18);
|
||||||
|
--orb-a:rgba(140,82,255,.35); --orb-b:rgba(60,120,255,.22);
|
||||||
|
--traffic:#FF8A52; --sites:#5AA6F0; --money:#F2C14A; --trust:#EE6A98; --go:#45C792;
|
||||||
|
--sites-soft:#17304D; --trust-soft:#3D1C2B; --go-soft:#123828; --money-soft:#3A3014;
|
||||||
|
--on-color:#11102A; --bar-ink:#11102A;
|
||||||
|
color-scheme:dark}
|
||||||
|
body{background:var(--bg);color:var(--ink);font-family:var(--body);font-size:1.125rem;line-height:1.6;
|
||||||
|
background-image:radial-gradient(40rem 28rem at 85% -5%,var(--orb-a),transparent 70%),radial-gradient(34rem 26rem at -10% 30%,var(--orb-b),transparent 70%),radial-gradient(36rem 30rem at 110% 62%,var(--orb-a),transparent 70%);background-repeat:no-repeat}
|
||||||
|
.wrap{max-width:1080px;margin:0 auto;padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px));padding-block:32px 48px;display:flex;flex-direction:column;gap:60px}
|
||||||
|
h1,h2,h3{font-family:var(--display);line-height:1.15;text-wrap:balance;margin:0}
|
||||||
|
h1{font-size:clamp(2.1rem,5.5vw,3.5rem);font-weight:800;letter-spacing:-.02em}
|
||||||
|
h2{font-size:clamp(1.6rem,3.6vw,2.3rem);font-weight:800;letter-spacing:-.01em}
|
||||||
|
h3{font-size:1.3rem;font-weight:600}
|
||||||
|
p{margin:0}
|
||||||
|
.glass{background:var(--glass);border:1.5px solid var(--glass-edge);-webkit-backdrop-filter:blur(14px) saturate(140%);backdrop-filter:blur(14px) saturate(140%);box-shadow:inset 0 1px 0 var(--glass-shine),0 10px 30px -18px var(--violet)}
|
||||||
|
.lede{font-size:1.3rem;color:var(--muted);max-width:44ch}
|
||||||
|
.sec{display:flex;flex-direction:column;gap:20px}
|
||||||
|
.sec-head{display:flex;align-items:center;gap:14px}
|
||||||
|
.stop{flex:none;width:52px;height:52px;border-radius:50%;display:grid;place-items:center;font-family:var(--display);font-weight:700;font-size:1.5rem;color:var(--on-color);background:var(--c);border:5px solid var(--bg);box-shadow:0 0 0 4px var(--c)}
|
||||||
|
.intro{max-width:62ch;color:var(--muted)}
|
||||||
|
.hero{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(0,1fr);gap:24px;align-items:center}
|
||||||
|
@media (max-width:760px){.hero{grid-template-columns:1fr}.coins{max-width:280px}}
|
||||||
|
.hero-text{display:flex;flex-direction:column;gap:18px;min-width:0}
|
||||||
|
.coins{width:100%;height:auto;display:block}
|
||||||
|
.tag{font-family:var(--display);font-weight:600;letter-spacing:.06em;text-transform:uppercase;font-size:.9rem;color:var(--violet)}
|
||||||
|
.lines{display:flex;flex-wrap:wrap;gap:10px}
|
||||||
|
.line-chip{display:inline-flex;align-items:center;gap:8px;font-family:var(--display);font-weight:600;font-size:1rem;padding:6px 14px;border-radius:999px;background:var(--surface);border:2px solid var(--c)}
|
||||||
|
.line-chip i{width:12px;height:12px;border-radius:50%;background:var(--c)}
|
||||||
|
figure{margin:0}
|
||||||
|
.diagram{border-radius:22px;padding:16px;overflow-x:auto}
|
||||||
|
.diagram svg{display:block;width:100%;height:auto}
|
||||||
|
figcaption{margin-top:10px;color:var(--muted);font-size:1rem;max-width:70ch}
|
||||||
|
.wide{display:block}.tall{display:none}
|
||||||
|
@media (max-width:700px){.wide{display:none}.tall{display:block}.tall svg{max-width:400px;margin:0 auto}}
|
||||||
|
.ico{width:36px;height:36px;flex:none}
|
||||||
|
.cols3{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
|
||||||
|
@media (max-width:820px){.cols3{grid-template-columns:1fr}}
|
||||||
|
.acard{border-radius:18px;padding:18px;display:flex;gap:14px;align-items:flex-start;min-width:0}
|
||||||
|
.acard p{font-size:1.05rem}
|
||||||
|
.acard b{font-family:var(--display);font-weight:600;font-size:1.2rem;display:block;margin-bottom:2px}
|
||||||
|
.soft-sites{background:var(--sites-soft)}
|
||||||
|
.chain{border-radius:26px;padding:24px;display:grid;grid-template-columns:auto 1fr;gap:24px;align-items:center}
|
||||||
|
@media (max-width:700px){.chain{grid-template-columns:1fr}}
|
||||||
|
.chain .coin1{width:120px;height:120px}
|
||||||
|
.chain ul{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:1fr 1fr;gap:14px 24px}
|
||||||
|
@media (max-width:560px){.chain ul{grid-template-columns:1fr}}
|
||||||
|
.chain li{display:flex;gap:12px;align-items:flex-start;min-width:0}
|
||||||
|
.chain li i{flex:none;width:30px;height:30px;border-radius:50%;background:linear-gradient(145deg,var(--violet-2),var(--violet));display:grid;place-items:center;color:#fff;font-style:normal;font-family:var(--display);font-weight:700;font-size:.95rem;box-shadow:inset 0 1px 0 rgba(255,255,255,.55)}
|
||||||
|
.chain b{font-family:var(--display);font-weight:600;font-size:1.15rem;display:block}
|
||||||
|
.chain span{color:var(--muted);font-size:1.02rem;line-height:1.45}
|
||||||
|
.groups{display:grid;grid-template-columns:repeat(2,1fr);gap:18px}
|
||||||
|
@media (max-width:760px){.groups{grid-template-columns:1fr}}
|
||||||
|
.group{background:var(--surface);border-radius:20px;padding:18px 18px 8px;border-top:8px solid var(--c);min-width:0}
|
||||||
|
.group h3{margin-bottom:6px}
|
||||||
|
.site{display:flex;gap:12px;align-items:flex-start;padding:10px 0;border-top:1px solid var(--rule)}
|
||||||
|
.site:first-of-type{border-top:0}
|
||||||
|
.site .dot{flex:none;width:14px;height:14px;margin-top:7px;border-radius:50%;background:var(--c)}
|
||||||
|
.site b{font-family:var(--display);font-weight:600;font-size:1.15rem}
|
||||||
|
.site span{display:block;color:var(--muted);font-size:1.02rem;line-height:1.45}
|
||||||
|
.site .soon{display:inline-block;font-family:var(--display);font-size:.8rem;font-weight:600;letter-spacing:.05em;text-transform:uppercase;padding:2px 8px;border-radius:999px;background:var(--violet-soft);color:var(--ink);margin-left:6px;vertical-align:2px}
|
||||||
|
.steps{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(5,1fr);gap:14px;counter-reset:s}
|
||||||
|
@media (max-width:900px){.steps{grid-template-columns:1fr}}
|
||||||
|
.steps li{background:var(--surface);border-radius:18px;padding:16px;display:flex;flex-direction:column;gap:8px;min-width:0;counter-increment:s}
|
||||||
|
.steps li::before{content:counter(s);font-family:var(--display);font-weight:700;width:34px;height:34px;border-radius:50%;display:grid;place-items:center;background:var(--traffic);color:var(--on-color)}
|
||||||
|
.steps b{font-family:var(--display);font-weight:600;font-size:1.15rem;line-height:1.25}
|
||||||
|
.steps span{font-size:1rem;color:var(--muted);line-height:1.45}
|
||||||
|
.walls{display:grid;grid-template-columns:repeat(4,1fr);gap:14px}
|
||||||
|
@media (max-width:900px){.walls{grid-template-columns:1fr 1fr}}
|
||||||
|
@media (max-width:520px){.walls{grid-template-columns:1fr}}
|
||||||
|
.wall{background:var(--surface);border-radius:16px;padding:14px 16px;display:flex;flex-direction:column;gap:4px;min-width:0;border-left:6px solid var(--violet)}
|
||||||
|
.wall b{font-family:var(--display);font-weight:600;font-size:1.12rem}
|
||||||
|
.wall span{font-size:1rem;color:var(--muted);line-height:1.4}
|
||||||
|
.stats{display:grid;grid-template-columns:1fr 1fr;gap:16px}
|
||||||
|
@media (max-width:620px){.stats{grid-template-columns:1fr}}
|
||||||
|
.stat{border-radius:20px;padding:18px 20px;display:flex;flex-direction:column;gap:4px;min-width:0}
|
||||||
|
.stat .num{font-family:var(--display);font-weight:700;font-size:2.4rem;line-height:1.05;color:var(--violet);font-variant-numeric:tabular-nums}
|
||||||
|
.stat span{color:var(--muted);font-size:1rem}
|
||||||
|
.example{background:var(--surface);border-radius:20px;padding:20px;display:flex;flex-direction:column;gap:16px}
|
||||||
|
.example-top{display:flex;flex-wrap:wrap;gap:8px 20px;align-items:baseline}
|
||||||
|
.big{font-family:var(--display);font-weight:700;font-size:2.6rem;line-height:1}
|
||||||
|
.bar{display:flex;height:64px;border-radius:14px;overflow:hidden;font-family:var(--display);font-weight:700;font-size:1.15rem}
|
||||||
|
.bar div{display:grid;place-items:center;color:var(--bar-ink);min-width:0}
|
||||||
|
.legend{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(4,1fr);gap:12px}
|
||||||
|
@media (max-width:760px){.legend{grid-template-columns:1fr 1fr}}
|
||||||
|
.legend li{display:flex;gap:10px;align-items:flex-start;font-size:1rem;line-height:1.4;min-width:0}
|
||||||
|
.legend i{flex:none;width:18px;height:18px;border-radius:5px;margin-top:3px}
|
||||||
|
.legend b{display:block;font-family:var(--display);font-weight:600;font-size:1.15rem;font-variant-numeric:tabular-nums}
|
||||||
|
.note{font-size:1rem;color:var(--muted);max-width:70ch}
|
||||||
|
.earn{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}
|
||||||
|
@media (max-width:900px){.earn{grid-template-columns:1fr 1fr}}
|
||||||
|
@media (max-width:560px){.earn{grid-template-columns:1fr}}
|
||||||
|
.ecard{border-radius:18px;padding:16px 18px;display:flex;flex-direction:column;gap:6px;min-width:0}
|
||||||
|
.ecard .site-name{font-family:var(--display);font-weight:600;font-size:.9rem;letter-spacing:.05em;text-transform:uppercase;color:var(--violet)}
|
||||||
|
.ecard b{font-family:var(--display);font-weight:600;font-size:1.18rem;line-height:1.25}
|
||||||
|
.ecard p{font-size:1rem;color:var(--muted);line-height:1.45}
|
||||||
|
.ecard.credits{border-style:dashed}
|
||||||
|
.nowd{border-radius:24px;padding:22px 24px;display:grid;grid-template-columns:auto 1fr;gap:20px;align-items:start}
|
||||||
|
@media (max-width:620px){.nowd{grid-template-columns:1fr}}
|
||||||
|
.nowd svg{width:72px;height:72px}
|
||||||
|
.nowd h3{font-size:clamp(1.4rem,3vw,1.8rem);font-weight:800;margin-bottom:6px}
|
||||||
|
.nowd .lead{font-size:1.15rem;margin-bottom:14px}
|
||||||
|
.nowd ul{list-style:none;margin:0 0 12px;padding:0;display:grid;grid-template-columns:1fr 1fr;gap:12px 20px}
|
||||||
|
@media (max-width:760px){.nowd ul{grid-template-columns:1fr}}
|
||||||
|
.nowd li b{display:block;font-family:var(--display);font-weight:700;font-size:1.1rem}
|
||||||
|
.nowd li span{color:var(--muted);font-size:1rem;line-height:1.45}
|
||||||
|
.nowd small{display:block;color:var(--muted);font-size:.9rem;line-height:1.45}
|
||||||
|
.promise{border-radius:18px;padding:16px 20px;background:var(--trust-soft);font-family:var(--display);font-weight:600;font-size:1.25rem;line-height:1.35}
|
||||||
|
.promise span{display:block;font-family:var(--body);font-weight:400;font-size:1rem;color:var(--muted);margin-top:4px}
|
||||||
|
.trust{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}
|
||||||
|
@media (max-width:900px){.trust{grid-template-columns:1fr 1fr}}
|
||||||
|
@media (max-width:520px){.trust{grid-template-columns:1fr}}
|
||||||
|
.tcard{background:var(--trust-soft);border-radius:18px;padding:18px;display:flex;flex-direction:column;gap:8px;min-width:0}
|
||||||
|
.tcard b{font-family:var(--display);font-weight:600;font-size:1.2rem}
|
||||||
|
.tcard p{font-size:1.02rem;line-height:1.45}
|
||||||
|
.start{background:var(--go-soft);border:3px solid var(--go);border-radius:24px;padding:24px;display:flex;flex-direction:column;gap:18px}
|
||||||
|
.start ol{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(3,1fr);gap:16px;counter-reset:g}
|
||||||
|
@media (max-width:760px){.start ol{grid-template-columns:1fr}}
|
||||||
|
.start li{counter-increment:g;display:flex;gap:12px;align-items:flex-start;min-width:0}
|
||||||
|
.start li::before{content:counter(g);flex:none;font-family:var(--display);font-weight:700;font-size:1.3rem;width:42px;height:42px;border-radius:50%;display:grid;place-items:center;background:var(--go);color:var(--on-color)}
|
||||||
|
.start b{font-family:var(--display);font-weight:600;font-size:1.25rem;display:block}
|
||||||
|
.fine{border-top:2px solid var(--rule);padding-top:20px;display:flex;flex-direction:column;gap:6px;color:var(--muted);font-size:1rem}
|
||||||
|
.fine strong{color:var(--ink)}
|
||||||
|
svg text{font-family:var(--display)}
|
||||||
|
h1,h2,h3,b,svg text,.tag,.line-chip,.site-name,.num,.big,.bar,.stop{font-feature-settings:"calt" 0;font-variant-ligatures:no-contextual}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<svg width="0" height="0" style="position:absolute" aria-hidden="true">
|
||||||
|
<defs>
|
||||||
|
<symbol id="i-key" viewBox="0 0 24 24"><circle cx="8" cy="12" r="4.5" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M12.5 12H21M18 12v3.5M21 12v2.5" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></symbol>
|
||||||
|
<symbol id="i-person" viewBox="0 0 24 24"><circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M4 21c1.2-4.2 4.3-6 8-6s6.8 1.8 8 6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></symbol>
|
||||||
|
<symbol id="i-team" viewBox="0 0 24 24"><circle cx="8" cy="9" r="3.2" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="16.5" cy="9" r="3.2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M2.5 20c.8-3.4 3-5 5.5-5s4.7 1.6 5.5 5M11 20c.8-3.4 3-5 5.5-5s4.7 1.6 5.5 5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
|
||||||
|
<linearGradient id="g-coin" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#C9A8FF"/><stop offset=".55" stop-color="#8247E5"/><stop offset="1" stop-color="#4B1FA8"/></linearGradient>
|
||||||
|
<linearGradient id="g-shine" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#FFFFFF" stop-opacity=".75"/><stop offset="1" stop-color="#FFFFFF" stop-opacity="0"/></linearGradient>
|
||||||
|
<symbol id="coin" viewBox="0 0 100 100">
|
||||||
|
<circle cx="50" cy="50" r="46" fill="url(#g-coin)" opacity=".92"/>
|
||||||
|
<circle cx="50" cy="50" r="46" fill="none" stroke="#FFFFFF" stroke-opacity=".55" stroke-width="2"/>
|
||||||
|
<circle cx="50" cy="50" r="34" fill="none" stroke="#FFFFFF" stroke-opacity=".45" stroke-width="2"/>
|
||||||
|
<path d="M20 34C30 14 70 14 80 34C64 26 36 26 20 34z" fill="url(#g-shine)"/>
|
||||||
|
<text x="50" y="58" text-anchor="middle" font-family="Plus Jakarta Sans,Segoe UI,sans-serif" font-weight="800" font-size="22" fill="#FFFFFF">POL</text>
|
||||||
|
</symbol>
|
||||||
|
</defs>
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
<main class="wrap">
|
||||||
|
|
||||||
|
<header class="hero">
|
||||||
|
<div class="hero-text">
|
||||||
|
<p class="tag">A one-page guide for new members</p>
|
||||||
|
<h1>How the Crypto Team Build Network Works</h1>
|
||||||
|
<p class="lede">It is a group of websites that work as one team. People share links, visitors see ads, and when someone buys ads, the payment is split on the spot.</p>
|
||||||
|
<div class="lines" aria-label="The parts of this page">
|
||||||
|
<span class="line-chip" style="--c:var(--sites)"><i></i>One account</span>
|
||||||
|
<span class="line-chip" style="--c:var(--violet)"><i></i>Polygon</span>
|
||||||
|
<span class="line-chip" style="--c:var(--traffic)"><i></i>Traffic</span>
|
||||||
|
<span class="line-chip" style="--c:var(--money)"><i></i>Money</span>
|
||||||
|
<span class="line-chip" style="--c:var(--trust)"><i></i>Trust</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<svg class="coins" viewBox="0 0 300 260" role="img" aria-label="Three violet glass POL coins">
|
||||||
|
<use href="#coin" x="120" y="10" width="160" height="160"/>
|
||||||
|
<use href="#coin" x="20" y="96" width="120" height="120"/>
|
||||||
|
<use href="#coin" x="160" y="160" width="90" height="90"/>
|
||||||
|
</svg>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="sec" aria-labelledby="big">
|
||||||
|
<h2 id="big">The whole network in one picture</h2>
|
||||||
|
<figure>
|
||||||
|
<div class="diagram glass wide">
|
||||||
|
<svg viewBox="0 60 1040 300" role="img" aria-label="A shared link is clicked, LinkSpin counts the click and sends the visitor to a network site, the visitor sees ads and may buy ads in POL, and a public contract splits that payment between the sponsor line and the company.">
|
||||||
|
<defs>
|
||||||
|
<marker id="aw" viewBox="0 0 10 10" refX="8" refY="5" markerUnits="userSpaceOnUse" markerWidth="13" markerHeight="13" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="var(--violet)"/></marker>
|
||||||
|
<marker id="aws" viewBox="0 0 10 10" refX="8" refY="5" markerUnits="userSpaceOnUse" markerWidth="13" markerHeight="13" orient="auto"><path d="M0 0L10 5L0 10z" fill="var(--sites)"/></marker>
|
||||||
|
</defs>
|
||||||
|
<g fill="none" stroke-width="10" stroke-linecap="round">
|
||||||
|
<path d="M70 145H270" stroke="var(--traffic)"/>
|
||||||
|
<path d="M270 145H470" stroke="var(--sites)"/>
|
||||||
|
<path d="M470 145H840" stroke="var(--violet)"/>
|
||||||
|
</g>
|
||||||
|
<g font-size="15" fill="var(--muted)" text-anchor="middle" font-weight="600">
|
||||||
|
<text x="170" y="104">click</text>
|
||||||
|
<text x="370" y="82">sends to</text><text x="370" y="104">the right page</text>
|
||||||
|
<text x="570" y="82">buys ads</text><text x="570" y="104">in POL</text>
|
||||||
|
<text x="755" y="82">split in</text><text x="755" y="104">one payment</text>
|
||||||
|
</g>
|
||||||
|
<g stroke-width="6">
|
||||||
|
<circle cx="70" cy="145" r="30" fill="var(--surface)" stroke="var(--traffic)"/>
|
||||||
|
<circle cx="270" cy="145" r="30" fill="var(--surface)" stroke="var(--traffic)"/>
|
||||||
|
<circle cx="470" cy="145" r="30" fill="var(--surface)" stroke="var(--sites)"/>
|
||||||
|
<circle cx="670" cy="145" r="30" fill="var(--surface)" stroke="var(--violet)"/>
|
||||||
|
</g>
|
||||||
|
<use href="#coin" x="802" y="107" width="76" height="76"/>
|
||||||
|
<g font-size="24" font-weight="700" text-anchor="middle" fill="var(--ink)">
|
||||||
|
<text x="70" y="153">1</text><text x="270" y="153">2</text><text x="470" y="153">3</text><text x="670" y="153">4</text>
|
||||||
|
</g>
|
||||||
|
<g font-size="19" font-weight="700" text-anchor="middle" fill="var(--ink)">
|
||||||
|
<text x="70" y="212">You share</text>
|
||||||
|
<text x="270" y="212">LinkSpin</text>
|
||||||
|
<text x="470" y="212">Network site</text>
|
||||||
|
<text x="670" y="212">A buyer</text>
|
||||||
|
<text x="840" y="212">Smart contract</text>
|
||||||
|
</g>
|
||||||
|
<g font-size="15" text-anchor="middle" fill="var(--muted)">
|
||||||
|
<text x="70" y="236">your tracked link</text>
|
||||||
|
<text x="270" y="236">counts every click</text>
|
||||||
|
<text x="470" y="236">sees ads, joins free</text>
|
||||||
|
<text x="670" y="236">package, Boost,</text><text x="670" y="255">spot or upgrade</text>
|
||||||
|
<text x="840" y="236">public, on Polygon</text>
|
||||||
|
</g>
|
||||||
|
<g fill="none" stroke="var(--violet)" stroke-width="4" color="var(--violet)">
|
||||||
|
<path d="M840 252V340"/>
|
||||||
|
<path d="M840 296H868" marker-end="url(#aw)"/>
|
||||||
|
<path d="M840 340H868" marker-end="url(#aw)"/>
|
||||||
|
</g>
|
||||||
|
<g font-size="15" font-weight="700" fill="var(--ink)">
|
||||||
|
<text x="876" y="301">Sponsor line</text>
|
||||||
|
<text x="876" y="345">Company</text>
|
||||||
|
</g>
|
||||||
|
<g fill="none" stroke="var(--sites)" stroke-width="3" stroke-dasharray="7 7" color="var(--sites)">
|
||||||
|
<path d="M660 272C640 318 500 318 480 274" marker-end="url(#aws)"/>
|
||||||
|
</g>
|
||||||
|
<text x="570" y="338" font-size="15" text-anchor="middle" fill="var(--muted)" font-weight="600">their ads show to visitors</text>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="diagram glass tall">
|
||||||
|
<svg viewBox="0 0 360 720" role="img" aria-label="A shared link is clicked, LinkSpin counts the click and sends the visitor to a network site, the visitor sees ads and may buy ads in POL, and a public contract splits that payment between the sponsor line and the company.">
|
||||||
|
<defs>
|
||||||
|
<marker id="aw2" viewBox="0 0 10 10" refX="8" refY="5" markerUnits="userSpaceOnUse" markerWidth="13" markerHeight="13" orient="auto"><path d="M0 0L10 5L0 10z" fill="var(--violet)"/></marker>
|
||||||
|
</defs>
|
||||||
|
<g fill="none" stroke-width="10" stroke-linecap="round">
|
||||||
|
<path d="M60 50V190" stroke="var(--traffic)"/>
|
||||||
|
<path d="M60 190V330" stroke="var(--sites)"/>
|
||||||
|
<path d="M60 330V610" stroke="var(--violet)"/>
|
||||||
|
</g>
|
||||||
|
<g font-size="13" fill="var(--muted)" font-weight="600">
|
||||||
|
<text x="80" y="125">click</text>
|
||||||
|
<text x="80" y="265">sends to the right page</text>
|
||||||
|
<text x="80" y="405">buys ads in POL</text>
|
||||||
|
<text x="80" y="545">split in one payment</text>
|
||||||
|
</g>
|
||||||
|
<g stroke-width="6">
|
||||||
|
<circle cx="60" cy="50" r="28" fill="var(--surface)" stroke="var(--traffic)"/>
|
||||||
|
<circle cx="60" cy="190" r="28" fill="var(--surface)" stroke="var(--traffic)"/>
|
||||||
|
<circle cx="60" cy="330" r="28" fill="var(--surface)" stroke="var(--sites)"/>
|
||||||
|
<circle cx="60" cy="470" r="28" fill="var(--surface)" stroke="var(--violet)"/>
|
||||||
|
</g>
|
||||||
|
<use href="#coin" x="30" y="580" width="60" height="60"/>
|
||||||
|
<g font-size="22" font-weight="700" text-anchor="middle" fill="var(--ink)">
|
||||||
|
<text x="60" y="58">1</text><text x="60" y="198">2</text><text x="60" y="338">3</text><text x="60" y="478">4</text>
|
||||||
|
</g>
|
||||||
|
<g font-size="18" font-weight="700" fill="var(--ink)">
|
||||||
|
<text x="104" y="46">You share</text>
|
||||||
|
<text x="104" y="186">LinkSpin</text>
|
||||||
|
<text x="104" y="326">Network site</text>
|
||||||
|
<text x="104" y="466">A buyer</text>
|
||||||
|
<text x="104" y="606">Smart contract</text>
|
||||||
|
</g>
|
||||||
|
<g font-size="14" fill="var(--muted)">
|
||||||
|
<text x="104" y="68">your tracked link</text>
|
||||||
|
<text x="104" y="208">counts every click</text>
|
||||||
|
<text x="104" y="348">visitor sees ads, joins free</text>
|
||||||
|
<text x="104" y="488">package, Boost, spot, upgrade</text>
|
||||||
|
<text x="104" y="628">public, on Polygon</text>
|
||||||
|
</g>
|
||||||
|
<g stroke="var(--violet)" stroke-width="4" fill="none" color="var(--violet)">
|
||||||
|
<path d="M60 642V672H104" marker-end="url(#aw2)"/>
|
||||||
|
<path d="M60 672V700H104" marker-end="url(#aw2)"/>
|
||||||
|
</g>
|
||||||
|
<g font-size="15" font-weight="700" fill="var(--ink)">
|
||||||
|
<text x="112" y="677">Sponsor line wallets</text>
|
||||||
|
<text x="112" y="705">Company</text>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<figcaption>Follow the colors. Orange is traffic, blue is the sites, purple is money on Polygon. A visit can turn into a sign-up, and a sign-up can turn into an ad purchase that pays the people who helped.</figcaption>
|
||||||
|
</figure>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="sec" aria-labelledby="s1" style="--c:var(--sites)">
|
||||||
|
<div class="sec-head"><span class="stop">1</span><h2 id="s1">One account, many sites</h2></div>
|
||||||
|
<p class="intro">You do not need a new account for every site. Think of it like one library card that works at every branch.</p>
|
||||||
|
<div class="cols3">
|
||||||
|
<div class="acard soft-sites"><svg class="ico" style="color:var(--sites)"><use href="#i-key"/></svg><p><b>Sign in once</b>Use your InstantAdPay or LinkSpin account. The other network sites let you in with it.</p></div>
|
||||||
|
<div class="acard soft-sites"><svg class="ico" style="color:var(--sites)"><use href="#i-person"/></svg><p><b>It is free</b>Joining costs nothing. You only pay if you choose to buy ads.</p></div>
|
||||||
|
<div class="acard soft-sites"><svg class="ico" style="color:var(--sites)"><use href="#i-team"/></svg><p><b>Your sponsor follows you</b>The person who invited you stays your sponsor on every site. Your team does too.</p></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="sec" aria-labelledby="s2" style="--c:var(--violet)">
|
||||||
|
<div class="sec-head"><span class="stop">2</span><h2 id="s2">Everything runs on Polygon</h2></div>
|
||||||
|
<p class="intro">Polygon is a blockchain: a public record book that thousands of computers keep together. Its coin is called POL. Every network site uses the same one.</p>
|
||||||
|
<div class="chain glass">
|
||||||
|
<svg class="coin1" viewBox="0 0 100 100" role="img" aria-label="A POL coin"><use href="#coin" width="100" height="100"/></svg>
|
||||||
|
<ul>
|
||||||
|
<li><i>1</i><div><b>One wallet works everywhere</b><span>Link the same wallet once. Every site pays to it.</span></div></li>
|
||||||
|
<li><i>2</i><div><b>Every site pays in POL</b><span>Same coin, same chain, on every site.</span></div></li>
|
||||||
|
<li><i>3</i><div><b>Fast with tiny fees</b><span>A payment settles in seconds, and the network fee is very small.</span></div></li>
|
||||||
|
<li><i>4</i><div><b>You can check every payment</b><span>Look any payment up on Polygonscan, the public search page for Polygon.</span></div></li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="sec" aria-labelledby="s3" style="--c:var(--sites)">
|
||||||
|
<div class="sec-head"><span class="stop">3</span><h2 id="s3">The sites on the map</h2></div>
|
||||||
|
<p class="intro">Each site does one job. Together they bring in visitors, show ads and help people build a team.</p>
|
||||||
|
<div class="groups">
|
||||||
|
<div class="group" style="--c:var(--sites)">
|
||||||
|
<h3>Start here</h3>
|
||||||
|
<div class="site"><i class="dot"></i><div><b>InstantAdPay</b><span>Buy ad packages. When people on your team buy, you can earn a share.</span></div></div>
|
||||||
|
<div class="site"><i class="dot"></i><div><b>LinkSpin</b><span>A free link that rotates your pages, counts real clicks and blocks bots. Free pages and ad zones too.</span></div></div>
|
||||||
|
<div class="site"><i class="dot"></i><div><b>DownlineHydra</b><span>Join once and you are in the whole network, with one sponsor line through every site.</span></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="group" style="--c:var(--traffic)">
|
||||||
|
<h3>Ads that spread</h3>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--traffic)"></i><div><b>Downline Banners</b><span>Buy a banner spot in one long line. Your banner shows on the pages in your line.</span></div></div>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--traffic)"></i><div><b>Viral Banner Blitz</b><span>Small banners in a shared loop. Every real visitor moves the loop forward.</span></div></div>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--traffic)"></i><div><b>ViralAdBlitz</b><span>A free text ad that shows on your team's pages, five levels down.</span></div></div>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--traffic)"></i><div><b>ViralAdSource</b><span>Post a free text ad. Others reshare it, and you watch how far it travels.</span></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="group" style="--c:var(--go)">
|
||||||
|
<h3>Team builders</h3>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--go)"></i><div><b>5xYourTeam</b><span>A weekly draft. Coaches pick new members who joined without a sponsor and help them start.</span></div></div>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--go)"></i><div><b>YourProgramBuilder</b><i class="soon">New</i><span>The Seed Bed: plant a program, members save their IDs, and the best ones join the Crypto Team Build Network builder.</span></div></div>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--go)"></i><div><b>CryptoTeamBuild</b><i class="soon">Coming Dec 15</i><span>The network's team builder, rebuilt on the same rails.</span></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="group" style="--c:var(--violet)">
|
||||||
|
<h3>See, talk and play</h3>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--violet)"></i><div><b>Stack POL</b><span>Shows payouts across the network, each one you can check yourself.</span></div></div>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--violet)"></i><div><b>Earners Corner</b><span>A friendly forum to ask questions and talk with other members.</span></div></div>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--violet)"></i><div><b>PolHunter</b><span>Missions: visit a site, find the code, get a small drip of POL to your wallet.</span></div></div>
|
||||||
|
<div class="site"><i class="dot" style="background:var(--violet)"></i><div><b>The games</b><span>Free games you sign in to with your InstantAdPay account.</span></div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="sec" aria-labelledby="s4" style="--c:var(--traffic)">
|
||||||
|
<div class="sec-head"><span class="stop">4</span><h2 id="s4">How visitors travel</h2></div>
|
||||||
|
<p class="intro">Traffic means people visiting a website. Here is the path a visitor takes.</p>
|
||||||
|
<ol class="steps">
|
||||||
|
<li><b>Members share links</b><span>In mailers, safelists, traffic exchanges, social sites, Telegram and Massifly.</span></li>
|
||||||
|
<li><b>LinkSpin counts the click</b><span>Every click is counted, bots are dropped, and the visitor goes to the right page.</span></li>
|
||||||
|
<li><b>Visitors land on a network site</b><span>They look around and can join free. Whoever shared the link becomes their sponsor.</span></li>
|
||||||
|
<li><b>They hop to other sites</b><span>PolHunter missions and the links between sites send people from one site to the next.</span></li>
|
||||||
|
<li><b>Ads get seen</b><span>Network pages carry ad spots, so each visit puts ads in front of real people.</span></li>
|
||||||
|
</ol>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="sec" aria-labelledby="s5" style="--c:var(--traffic)">
|
||||||
|
<div class="sec-head"><span class="stop">5</span><h2 id="s5">Where your ad shows up</h2></div>
|
||||||
|
<p class="intro">Your ad is like a poster. These are all the walls it can hang on. When you buy ads on InstantAdPay, they can run on the network's own sites and also go out to partner places.</p>
|
||||||
|
<figure>
|
||||||
|
<div class="diagram glass wide">
|
||||||
|
<svg viewBox="0 0 1000 380" role="img" aria-label="An ad bought on InstantAdPay is sent out to the network sites, Network Ad Space, DripOffers, AdRevLinks, LinkSpin ad zones, the EnjoyBestGames arcade, and pages that PolHunter missions send hunters to.">
|
||||||
|
<defs>
|
||||||
|
<marker id="aw3" viewBox="0 0 10 10" refX="8" refY="5" markerUnits="userSpaceOnUse" markerWidth="13" markerHeight="13" orient="auto"><path d="M0 0L10 5L0 10z" fill="var(--violet)"/></marker>
|
||||||
|
</defs>
|
||||||
|
<rect x="40" y="130" width="230" height="120" rx="18" fill="var(--violet-soft)" stroke="var(--violet)" stroke-width="3"/>
|
||||||
|
<rect x="64" y="150" width="56" height="78" rx="6" fill="var(--surface)" stroke="var(--violet)" stroke-width="2.5"/>
|
||||||
|
<path d="M74 166h36M74 178h36M74 190h24" stroke="var(--violet)" stroke-width="3" stroke-linecap="round"/>
|
||||||
|
<text x="136" y="182" font-size="21" font-weight="700" fill="var(--ink)">Your ad</text>
|
||||||
|
<text x="136" y="206" font-size="14" fill="var(--muted)">bought on</text>
|
||||||
|
<text x="136" y="224" font-size="14" fill="var(--muted)">InstantAdPay</text>
|
||||||
|
<g fill="none" stroke="var(--violet)" stroke-width="3" color="var(--violet)">
|
||||||
|
<path d="M270 190C330 190 330 40 452 40" marker-end="url(#aw3)"/>
|
||||||
|
<path d="M270 190C340 190 340 115 452 115" marker-end="url(#aw3)"/>
|
||||||
|
<path d="M270 190H452" marker-end="url(#aw3)"/>
|
||||||
|
<path d="M270 190C340 190 340 265 452 265" marker-end="url(#aw3)"/>
|
||||||
|
<path d="M270 190C330 190 330 340 452 340" marker-end="url(#aw3)"/>
|
||||||
|
</g>
|
||||||
|
<g font-size="18" font-weight="700" fill="var(--ink)">
|
||||||
|
<text x="462" y="38">Network sites</text>
|
||||||
|
<text x="462" y="113">Network Ad Space</text>
|
||||||
|
<text x="462" y="188">DripOffers</text>
|
||||||
|
<text x="462" y="263">AdRevLinks</text>
|
||||||
|
<text x="462" y="338">LinkSpin ad zones</text>
|
||||||
|
</g>
|
||||||
|
<g font-size="14" fill="var(--muted)">
|
||||||
|
<text x="462" y="58">shown to members across the network</text>
|
||||||
|
<text x="462" y="133">banner spots on many network and partner sites</text>
|
||||||
|
<text x="462" y="208">offer walls inside other people's paid-to-click sites</text>
|
||||||
|
<text x="462" y="283">people shorten links, visitors see ads on the way</text>
|
||||||
|
<text x="462" y="358">ad spaces members put on their own pages</text>
|
||||||
|
</g>
|
||||||
|
<g font-size="13" font-weight="700" fill="var(--violet)" text-anchor="end">
|
||||||
|
<text x="985" y="113">counts views</text>
|
||||||
|
<text x="985" y="188">counts clicks</text>
|
||||||
|
<text x="985" y="263">counts views</text>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="diagram glass tall">
|
||||||
|
<svg viewBox="0 0 360 560" role="img" aria-label="An ad bought on InstantAdPay is sent out to the network sites, Network Ad Space, DripOffers, AdRevLinks and LinkSpin ad zones.">
|
||||||
|
<defs>
|
||||||
|
<marker id="aw4" viewBox="0 0 10 10" refX="8" refY="5" markerUnits="userSpaceOnUse" markerWidth="13" markerHeight="13" orient="auto"><path d="M0 0L10 5L0 10z" fill="var(--violet)"/></marker>
|
||||||
|
</defs>
|
||||||
|
<rect x="10" y="10" width="340" height="80" rx="16" fill="var(--violet-soft)" stroke="var(--violet)" stroke-width="3"/>
|
||||||
|
<rect x="26" y="22" width="40" height="56" rx="5" fill="var(--surface)" stroke="var(--violet)" stroke-width="2.5"/>
|
||||||
|
<path d="M33 34h26M33 44h26M33 54h17" stroke="var(--violet)" stroke-width="3" stroke-linecap="round"/>
|
||||||
|
<text x="80" y="46" font-size="20" font-weight="700" fill="var(--ink)">Your ad</text>
|
||||||
|
<text x="80" y="68" font-size="14" fill="var(--muted)">bought on InstantAdPay</text>
|
||||||
|
<path d="M40 90V510" stroke="var(--violet)" stroke-width="4" fill="none"/>
|
||||||
|
<g stroke="var(--violet)" stroke-width="3" fill="none" color="var(--violet)">
|
||||||
|
<path d="M40 140H70" marker-end="url(#aw4)"/>
|
||||||
|
<path d="M40 230H70" marker-end="url(#aw4)"/>
|
||||||
|
<path d="M40 320H70" marker-end="url(#aw4)"/>
|
||||||
|
<path d="M40 410H70" marker-end="url(#aw4)"/>
|
||||||
|
<path d="M40 500H70" marker-end="url(#aw4)"/>
|
||||||
|
</g>
|
||||||
|
<g font-size="17" font-weight="700" fill="var(--ink)">
|
||||||
|
<text x="80" y="140">Network sites</text>
|
||||||
|
<text x="80" y="230">Network Ad Space</text>
|
||||||
|
<text x="80" y="320">DripOffers</text>
|
||||||
|
<text x="80" y="410">AdRevLinks</text>
|
||||||
|
<text x="80" y="500">LinkSpin ad zones</text>
|
||||||
|
</g>
|
||||||
|
<g font-size="13" fill="var(--muted)">
|
||||||
|
<text x="80" y="160">shown to members</text>
|
||||||
|
<text x="80" y="250">banner spots on many sites</text>
|
||||||
|
<text x="80" y="340">offer walls on paid-to-click sites</text>
|
||||||
|
<text x="80" y="430">ads seen while links open</text>
|
||||||
|
<text x="80" y="520">ad spaces on member pages</text>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<figcaption>Each wall counts what really happened, a real view or a real click, before your credits are used.</figcaption>
|
||||||
|
</figure>
|
||||||
|
<h3>More walls where people see the network</h3>
|
||||||
|
<div class="walls">
|
||||||
|
<div class="wall"><b>PolHunter missions</b><span>Hunters visit sites to find a code, so they look at the pages, ads included.</span></div>
|
||||||
|
<div class="wall"><b>EnjoyBestGames</b><span>A free game arcade with a network ad spot and links to our games.</span></div>
|
||||||
|
<div class="wall"><b>MyLnks and Mail Splat</b><span>A link shortener and a temporary email site, both PolHunter mission stops.</span></div>
|
||||||
|
<div class="wall"><b>Where members share</b><span>Traffic exchanges, mailers, safelists, social sites and Telegram.</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="stats">
|
||||||
|
<div class="stat glass"><span class="num">About 2 million</span><span>ad views shown by Network Ad Space in one month (August 2026)</span></div>
|
||||||
|
<div class="stat glass"><span class="num">About 32,000</span><span>people on the network's member lists, counted November 12, 2026</span></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="sec" aria-labelledby="s6" style="--c:var(--money)">
|
||||||
|
<div class="sec-head"><span class="stop">6</span><h2 id="s6">How the money moves</h2></div>
|
||||||
|
<p class="intro">Money comes in when someone buys advertising: an ad package, a Boost, a banner spot or an upgrade. They pay in POL. A public smart contract (a program on the blockchain that anyone can read) splits the payment right away. The shares go straight to wallets in that same payment.</p>
|
||||||
|
<div class="example">
|
||||||
|
<div class="example-top"><span class="big">$20</span><h3>Example: one InstantAdPay package</h3></div>
|
||||||
|
<p class="note">The buyer gets 2,000 ad credits. Here is where their $20 of POL goes, in the same payment.</p>
|
||||||
|
<div class="bar" role="img" aria-label="$10 to the direct sponsor, $4 to level 2, $2 to level 3, $4 to the company">
|
||||||
|
<div style="flex:50;background:var(--money)">$10</div>
|
||||||
|
<div style="flex:20;background:var(--traffic)">$4</div>
|
||||||
|
<div style="flex:10;background:var(--sites)">$2</div>
|
||||||
|
<div style="flex:20;background:var(--violet-2)">$4</div>
|
||||||
|
</div>
|
||||||
|
<ul class="legend">
|
||||||
|
<li><i style="background:var(--money)"></i><div><b>$10 · 50%</b>The direct sponsor, the person who invited the buyer.</div></li>
|
||||||
|
<li><i style="background:var(--traffic)"></i><div><b>$4 · 20%</b>Level 2, the sponsor's sponsor.</div></li>
|
||||||
|
<li><i style="background:var(--sites)"></i><div><b>$2 · 10%</b>Level 3, one more step up.</div></li>
|
||||||
|
<li><i style="background:var(--violet-2)"></i><div><b>$4 · 20%</b>The company, in two wallets of $2.</div></li>
|
||||||
|
</ul>
|
||||||
|
<p class="note">Levels 2 and 3 are unlocked by inviting people who buy. If someone has not unlocked a level yet, that share moves up the line to the next person who has. These rules are written into the contract, and no one can change them.</p>
|
||||||
|
</div>
|
||||||
|
<p class="note">Other sites have their own split, shown on each site's "Is it legit?" guide. The idea is the same everywhere: money in, money out, in one payment.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="sec" aria-labelledby="s7" style="--c:var(--violet)">
|
||||||
|
<div class="sec-head"><span class="stop">7</span><h2 id="s7">Ways you can earn</h2></div>
|
||||||
|
<p class="intro">There is more than one way to earn in the network. Most of them pay when someone you brought in buys something. Each one has its own rules on its site.</p>
|
||||||
|
<figure>
|
||||||
|
<div class="diagram glass wide">
|
||||||
|
<svg viewBox="0 0 1040 540" role="img" aria-label="Eleven network sites each send their own kind of payment, such as sponsor shares, level shares, resharer cuts, hunt rewards and prizes, into one member wallet on Polygon.">
|
||||||
|
<defs>
|
||||||
|
<marker id="awm" viewBox="0 0 10 10" refX="8" refY="5" markerUnits="userSpaceOnUse" markerWidth="14" markerHeight="14" orient="auto"><path d="M0 0L10 5L0 10z" fill="var(--violet)"/></marker>
|
||||||
|
</defs>
|
||||||
|
<g fill="none" stroke="var(--violet)" stroke-width="2.5" stroke-opacity=".75">
|
||||||
|
<path d="M470 40C640 40 640 270 770 270"/>
|
||||||
|
<path d="M470 86C640 86 640 270 770 270"/>
|
||||||
|
<path d="M470 132C640 132 640 270 770 270"/>
|
||||||
|
<path d="M470 178C640 178 640 270 770 270"/>
|
||||||
|
<path d="M470 224C640 224 640 270 770 270"/>
|
||||||
|
<path d="M470 270C640 270 640 270 770 270"/>
|
||||||
|
<path d="M470 316C640 316 640 270 770 270"/>
|
||||||
|
<path d="M470 362C640 362 640 270 770 270"/>
|
||||||
|
<path d="M470 408C640 408 640 270 770 270"/>
|
||||||
|
<path d="M470 454C640 454 640 270 770 270"/>
|
||||||
|
<path d="M470 500C640 500 640 270 770 270"/>
|
||||||
|
</g>
|
||||||
|
<path d="M770 270H806" stroke="var(--violet)" stroke-width="5" fill="none" marker-end="url(#awm)"/>
|
||||||
|
<rect x="200" y="26" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="72" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="118" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="164" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="210" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="256" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="302" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="348" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="394" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="440" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<rect x="200" y="486" width="270" height="28" rx="14" fill="var(--violet-soft)"/>
|
||||||
|
<g font-size="16" font-weight="700" fill="var(--ink)">
|
||||||
|
<text x="20" y="46">InstantAdPay</text>
|
||||||
|
<text x="20" y="92">LinkSpin</text>
|
||||||
|
<text x="20" y="138">Downline Banners</text>
|
||||||
|
<text x="20" y="184">Viral Banner Blitz</text>
|
||||||
|
<text x="20" y="230">ViralAdBlitz</text>
|
||||||
|
<text x="20" y="276">ViralAdSource</text>
|
||||||
|
<text x="20" y="322">DownlineHydra</text>
|
||||||
|
<text x="20" y="368">5xYourTeam</text>
|
||||||
|
<text x="20" y="414">YourProgramBuilder</text>
|
||||||
|
<text x="20" y="460">PolHunter</text>
|
||||||
|
<text x="20" y="506">The games</text>
|
||||||
|
</g>
|
||||||
|
<g font-size="13" font-weight="600" fill="var(--ink)" text-anchor="middle">
|
||||||
|
<text x="335" y="45">sponsor + level shares</text>
|
||||||
|
<text x="335" y="91">sponsor + level shares</text>
|
||||||
|
<text x="335" y="137">sponsor share + spot shares</text>
|
||||||
|
<text x="335" y="183">sponsor share + weekly prizes</text>
|
||||||
|
<text x="335" y="229">level shares</text>
|
||||||
|
<text x="335" y="275">resharer cut + level shares</text>
|
||||||
|
<text x="335" y="321">sponsor + level shares</text>
|
||||||
|
<text x="335" y="367">level shares + Best Coach prize</text>
|
||||||
|
<text x="335" y="413">sponsor + level shares</text>
|
||||||
|
<text x="335" y="459">hunt rewards + prizes</text>
|
||||||
|
<text x="335" y="505">game rewards</text>
|
||||||
|
</g>
|
||||||
|
<rect x="816" y="170" width="200" height="200" rx="28" fill="var(--violet-soft)" stroke="var(--violet)" stroke-width="3"/>
|
||||||
|
<rect x="816" y="170" width="200" height="56" rx="28" fill="var(--violet)" fill-opacity=".14"/>
|
||||||
|
<use href="#coin" x="866" y="200" width="100" height="100"/>
|
||||||
|
<text x="916" y="330" font-size="19" font-weight="800" text-anchor="middle" fill="var(--ink)">Your wallet</text>
|
||||||
|
<text x="916" y="352" font-size="13" text-anchor="middle" fill="var(--muted)">one wallet on Polygon</text>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="diagram glass tall">
|
||||||
|
<svg viewBox="0 0 360 750" role="img" aria-label="Eleven network sites each send their own kind of payment into one member wallet on Polygon.">
|
||||||
|
<defs>
|
||||||
|
<marker id="awm2" viewBox="0 0 10 10" refX="8" refY="5" markerUnits="userSpaceOnUse" markerWidth="14" markerHeight="14" orient="auto"><path d="M0 0L10 5L0 10z" fill="var(--violet)"/></marker>
|
||||||
|
</defs>
|
||||||
|
<g fill="none" stroke="var(--violet)" stroke-width="2.5" stroke-opacity=".75">
|
||||||
|
<path d="M224 33H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 81H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 129H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 177H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 225H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 273H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 321H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 369H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 417H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 465H330" stroke-dasharray="4 5"/>
|
||||||
|
<path d="M224 513H330" stroke-dasharray="4 5"/>
|
||||||
|
</g>
|
||||||
|
<path d="M330 30V586H262" stroke="var(--violet)" stroke-width="4" fill="none" stroke-linejoin="round" marker-end="url(#awm2)"/>
|
||||||
|
<g font-size="15" font-weight="700" fill="var(--ink)">
|
||||||
|
<text x="16" y="35">InstantAdPay</text>
|
||||||
|
<text x="16" y="83">LinkSpin</text>
|
||||||
|
<text x="16" y="131">Downline Banners</text>
|
||||||
|
<text x="16" y="179">Viral Banner Blitz</text>
|
||||||
|
<text x="16" y="227">ViralAdBlitz</text>
|
||||||
|
<text x="16" y="275">ViralAdSource</text>
|
||||||
|
<text x="16" y="323">DownlineHydra</text>
|
||||||
|
<text x="16" y="371">5xYourTeam</text>
|
||||||
|
<text x="16" y="419">YourProgramBuilder</text>
|
||||||
|
<text x="16" y="467">PolHunter</text>
|
||||||
|
<text x="16" y="515">The games</text>
|
||||||
|
</g>
|
||||||
|
<g font-size="12.5" fill="var(--muted)">
|
||||||
|
<text x="16" y="53">sponsor + level shares</text>
|
||||||
|
<text x="16" y="101">sponsor + level shares</text>
|
||||||
|
<text x="16" y="149">sponsor share + spot shares</text>
|
||||||
|
<text x="16" y="197">sponsor share + weekly prizes</text>
|
||||||
|
<text x="16" y="245">level shares</text>
|
||||||
|
<text x="16" y="293">resharer cut + level shares</text>
|
||||||
|
<text x="16" y="341">sponsor + level shares</text>
|
||||||
|
<text x="16" y="389">level shares + Best Coach prize</text>
|
||||||
|
<text x="16" y="437">sponsor + level shares</text>
|
||||||
|
<text x="16" y="485">hunt rewards + prizes</text>
|
||||||
|
<text x="16" y="533">game rewards</text>
|
||||||
|
</g>
|
||||||
|
<rect x="60" y="560" width="190" height="170" rx="26" fill="var(--violet-soft)" stroke="var(--violet)" stroke-width="3"/>
|
||||||
|
<use href="#coin" x="115" y="574" width="80" height="80"/>
|
||||||
|
<text x="155" y="686" font-size="18" font-weight="800" text-anchor="middle" fill="var(--ink)">Your wallet</text>
|
||||||
|
<text x="155" y="707" font-size="12.5" text-anchor="middle" fill="var(--muted)">one wallet on Polygon</text>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<figcaption>Every arrow is a separate on-chain payment you can check on Polygonscan. This is an example of the kinds of payments, not a promise of any. Ad credits stay on your account and are not shown here.</figcaption>
|
||||||
|
</figure>
|
||||||
|
<div class="nowd glass">
|
||||||
|
<svg viewBox="0 0 100 100" role="img" aria-label="A POL coin"><use href="#coin" width="100" height="100"/></svg>
|
||||||
|
<div>
|
||||||
|
<h3>No withdrawal requests. Ever.</h3>
|
||||||
|
<p class="lead">You never ask anyone to pay you. When you earn, the POL goes to your wallet by itself.</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>Shares from sales</b><span>InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, ViralAdSource, DownlineHydra, 5xYourTeam and YourProgramBuilder: the smart contract pays your share in the same payment as the purchase, the moment it happens.</span></li>
|
||||||
|
<li><b>Hunt and game rewards</b><span>PolHunter and the games send rewards to your wallet automatically, usually within minutes. No request needed.</span></li>
|
||||||
|
</ul>
|
||||||
|
<small>Small print: if a transfer can't be delivered to your wallet, on most of these sites it waits safely in the contract for you to collect. On InstantAdPay and LinkSpin that share moves up the line instead, and on Downline Banners it goes to the momentum fund.</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="promise">Nothing is promised. Crypto involves risk.<span>You only earn a share when a real purchase happens. Results depend on what you and your team do.</span></div>
|
||||||
|
<div class="earn">
|
||||||
|
<div class="ecard glass"><span class="site-name">InstantAdPay</span><b>Sponsor shares on ad packages</b><p>50% to the sponsor, plus level 2 and level 3 shares once you unlock them.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">LinkSpin</span><b>Sponsor shares on LinkSpin packages</b><p>The same split as InstantAdPay, on its own contract.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">Downline Banners</span><b>Spot sales</b><p>30% to the buyer's sponsor, and the spots bought just before a new one share in it.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">Viral Banner Blitz</span><b>Banner packs and weekly prizes</b><p>30% to the member who introduced the buyer. 10% goes to weekly leaderboard prizes.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">ViralAdBlitz</span><b>Boost shares, five levels</b><p>10% each to five people up the line who have bought a Boost themselves.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">ViralAdSource</span><b>Reshare and level shares</b><p>20% to the resharer whose link sold a Boost, plus 10% to each of five sponsor levels.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">DownlineHydra</span><b>Pro upgrade shares</b><p>20% to the direct sponsor, free or Pro. Levels 2 to 5 get 10% each, for Pro members.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">5xYourTeam</span><b>Position shares and Best Coach</b><p>25% to the sponsor, 5% each to levels 2 to 5, and 10% to a weekly Best Coach prize.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">YourProgramBuilder</span><b>Spotlight shares</b><p>A share when someone in your line buys a $10 Spotlight: 20% to the sponsor, 5% each to levels 2 to 5.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">PolHunter</span><b>Hunts and weekly prizes</b><p>A small random drip of POL for finds on sites new to you. Game Pass holders can win weekly prizes.</p></div>
|
||||||
|
<div class="ecard glass"><span class="site-name">The games</span><b>Game rewards</b><p>Some network games pay small POL rewards for playing.</p></div>
|
||||||
|
<div class="ecard glass credits"><span class="site-name">ViralAdSource and PolHunter</span><b>Ad credits</b><p>Reshares and PolHunter tour stops can earn ad credits. Ad credits buy advertising, not income.</p></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="sec" aria-labelledby="s8" style="--c:var(--trust)">
|
||||||
|
<div class="sec-head"><span class="stop">8</span><h2 id="s8">Why you can check it</h2></div>
|
||||||
|
<div class="trust">
|
||||||
|
<div class="tcard"><b>Verified contracts</b><p>The code that splits payments is public. Anyone can read it on Polygonscan.</p></div>
|
||||||
|
<div class="tcard"><b>Public ledger</b><p>Every payment is recorded on the blockchain. Stack POL puts them in one place.</p></div>
|
||||||
|
<div class="tcard"><b>No monthly charges</b><p>Every purchase is one time. Nothing bills you again.</p></div>
|
||||||
|
<div class="tcard"><b>Free to join</b><p>You can look around, use the free tools and learn before you spend anything.</p></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="start" aria-labelledby="go">
|
||||||
|
<h2 id="go">Start here</h2>
|
||||||
|
<ol>
|
||||||
|
<li><div><b>Join free</b>Make one account on InstantAdPay or LinkSpin.</div></li>
|
||||||
|
<li><div><b>Link a wallet</b>SafePal or any other crypto wallet.</div></li>
|
||||||
|
<li><div><b>Share your link</b>Use your tracked LinkSpin link wherever you promote.</div></li>
|
||||||
|
</ol>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<footer class="fine">
|
||||||
|
<p><strong>Ad credits buy advertising, not income.</strong></p>
|
||||||
|
<p><strong>Nothing is promised. Crypto involves risk.</strong> Payments in POL are final. Results depend on what you and your team do.</p>
|
||||||
|
<p>© 2026 TrustClickz</p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
|
||||||
|
</body></html>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"site": "stackpol",
|
||||||
|
"home": [
|
||||||
|
{ "q": "What is Stack POL?", "kb": "about", "must": ["every POL payout", "holds nothing"] },
|
||||||
|
{ "q": "Where do the numbers come from?", "kb": "numbers", "must": ["5 minutes", "Polygonscan"] },
|
||||||
|
{ "q": "How often does it update?", "kb": "numbers", "must": ["5 minutes"] },
|
||||||
|
{ "q": "Will I earn this much?", "kb": "income", "must": ["No promise of income"] },
|
||||||
|
{ "q": "How do I get my own Stack POL page?", "kb": "my-page", "must": ["Promo tools", "link a wallet"] },
|
||||||
|
{ "q": "Which programs are on Stack POL?", "kb": "programs", "must": ["InstantAdPay", "ViralAdBlitz", "DownlineHydra"] },
|
||||||
|
{ "q": "How do I join?", "kb": "start", "must": ["instantadpay.com/join"] },
|
||||||
|
{ "q": "Does Stack POL hold my money?", "kb": "custody", "must": ["straight from the program"] },
|
||||||
|
{ "q": "What is POL?", "kb": "pol", "must": ["Polygon", "SafePal or any other crypto wallet"] },
|
||||||
|
{ "q": "Is there a blog?", "kb": "blog", "must": ["feed.xml"] }
|
||||||
|
],
|
||||||
|
"cross": [
|
||||||
|
{ "q": "How does Downline Banners pay?", "site": "bannerline" },
|
||||||
|
{ "q": "What is a ViralAdBlitz Boost?", "site": "viraladblitz" },
|
||||||
|
{ "q": "How much is a 5xYourTeam position?", "site": "fivex" },
|
||||||
|
{ "q": "What does DownlineHydra Pro give me?", "site": "downlinehydra" },
|
||||||
|
{ "q": "How does Viral Banner Blitz work?", "site": "vbb" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
// 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';
|
||||||
|
|
||||||
|
try { const cfg = require(path.join(ROOT, 'config.js')); if (cfg.reset) cfg.reset(); } catch (e) {} // Stack POL has no config.js
|
||||||
|
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 >= 10, 'at least 10 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'); }
|
||||||
|
if (dataDir) fs.writeFileSync(path.join(dataDir, 'openrouter.key'), 'test-key'); else process.env.OPENROUTER_API_KEY = 'test-key'; // no volume (Stack POL): the env 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 => !['support', 'refund', 'about'].includes(c.id) && (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 r = await bot.answer(GENERAL + ' on Other Site'); ok(!r.canned, 'a question naming another site skips this site\'s instant answers (' + r.kb + ')'); }
|
||||||
|
{ const r = await bot.answer('I need a real person, my order on Other Site failed'); ok(r.handoff === true, 'a hand-off still wins when another site is named'); }
|
||||||
|
{ const r = await bot.answer(bot.CANNED.find(c => c.id === 'about').q[0]); ok(r.canned && r.kb === 'c-about', 'this site\'s own name keeps the instant answer'); }
|
||||||
|
{ 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);
|
||||||
+265
@@ -0,0 +1,265 @@
|
|||||||
|
// My Stack POL checks (2026-11-19): node qa/my.test.mjs
|
||||||
|
// No network, no production data: boots server.js twice on a temp DATA_DIR (no DOCSTORE_URL) with a stand-in hub and a stand-in
|
||||||
|
// InstantAdPay switch interface. Checks: the silent check and the "not signed in anywhere" answer, the hub sign-in callback (a good
|
||||||
|
// token signs in, a replayed or wrong-state or wrong-key token does not), /my for a member with a live page + Pro + payouts, one switched
|
||||||
|
// off with payouts, one with nothing yet, the switch (IAP gets the signed call, /my and the public page follow at once, a cross-site
|
||||||
|
// post is refused), the copy of IAP's switch when the interface is off (a link to Promo tools, the state from the snapshot), the
|
||||||
|
// wallet match when the network username differs, sign-out (the old cookie stops working) and the public pages without a sign-in.
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import http from 'node:http';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const ok = (c, m) => { if (c) pass++; else { fail++; console.log('FAIL', m); } };
|
||||||
|
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36';
|
||||||
|
const HUB_SECRET = crypto.randomBytes(24).toString('hex'), SWITCH_KEY = crypto.randomBytes(24).toString('hex');
|
||||||
|
const W = { a1: '0x' + 'a1'.repeat(20), a2: '0x' + 'a2'.repeat(20), b1: '0x' + 'b1'.repeat(20) };
|
||||||
|
const TX = n => '0x' + String(n).repeat(64).slice(0, 64);
|
||||||
|
|
||||||
|
// ---- the snapshot the indexer would push (tools/indexer.py shape, `my` included)
|
||||||
|
const now = Date.now();
|
||||||
|
const aliceRows = [{ k: 'iap', pol: 12.5, tx: TX(1), ts: now - 3600e3 }, { k: 'ph', pol: 0.3333, tx: TX(2), ts: now - 7200e3 }, { k: 'iap', pol: 1, tx: TX(3), ts: now - 86400e3 }];
|
||||||
|
const bobRows = [{ k: 'ls', pol: 4.25, tx: TX(4), ts: now - 5000e3 }];
|
||||||
|
const snap = {
|
||||||
|
v: 1, at: now - 60e3, network: { pol: 18.0833, payments: 4, wallets: 2 }, last7: { pol: 18.0833, payments: 4 },
|
||||||
|
programs: { iap: { pol: 13.5, payments: 2, wallets: 1 }, ph: { pol: 0.3333, payments: 1, wallets: 1 }, ls: { pol: 4.25, payments: 1, wallets: 1 } },
|
||||||
|
recent: aliceRows.map(r => Object.assign({ u: 'alice', pub: true }, r)).concat(bobRows.map(r => Object.assign({ u: 'bob', pub: false }, r))),
|
||||||
|
progRecent: {},
|
||||||
|
stacks: { alice: { total: 13.8333, payments: 3, since: now - 86400e3, byProg: { iap: { pol: 13.5, payments: 2 }, ph: { pol: 0.3333, payments: 1 } }, recent: aliceRows, pro: { spins: [], links: [{ code: 'abc123', name: 'My offer' }] } } },
|
||||||
|
my: {
|
||||||
|
members: {
|
||||||
|
alice: { total: 13.8333, payments: 3, since: now - 86400e3, byProg: { iap: { pol: 13.5, payments: 2 }, ph: { pol: 0.3333, payments: 1 } }, rows: aliceRows, wallets: [W.a1, W.a2], page: true },
|
||||||
|
bob: { total: 4.25, payments: 1, since: now - 5000e3, byProg: { ls: { pol: 4.25, payments: 1 } }, rows: bobRows, wallets: [W.b1], page: false }
|
||||||
|
},
|
||||||
|
switch: { bob: false }, pro: ['alice']
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- stand-in hub: /sso/check answers for whoever `hubUser` is
|
||||||
|
let hubUser = null; const hubCalls = [];
|
||||||
|
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||||
|
function hubToken(o, secret) {
|
||||||
|
const t = { iss: 'hub', aud: o.aud || 'stackpol', to: o.to || '/my', iat: o.iat || Date.now(), exp: (o.iat || Date.now()) + 60000, n: crypto.randomBytes(16).toString('hex'), email: o.email, st: o.st };
|
||||||
|
if (o.wallet) t.wallet = o.wallet; if (o.name) t.name = o.name;
|
||||||
|
const body = b64u(JSON.stringify(t)); return 'h1.' + body + '.' + b64u(crypto.createHmac('sha256', secret || HUB_SECRET).update('hubsso.v1.' + body).digest());
|
||||||
|
}
|
||||||
|
let SP = ''; // the Stack POL base the hub sends people back to (set per server)
|
||||||
|
const hub = http.createServer((req, res) => { let raw = ''; req.on('data', c => { raw += c; }); req.on('end', () => {
|
||||||
|
const u = new URL(req.url, 'http://x'); hubCalls.push(u.pathname);
|
||||||
|
const send = (code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); };
|
||||||
|
if (u.pathname === '/health') return send(200, { ok: true });
|
||||||
|
if (u.pathname === '/sso/check') {
|
||||||
|
const st = u.searchParams.get('st'), to = u.searchParams.get('to') || '/', m = u.searchParams.get('m') === 'go' ? 'go' : 'check';
|
||||||
|
const loc = hubUser ? SP + '/sso/in?h=' + hubToken(Object.assign({ st, to }, hubUser)) : SP + '/sso/in?none=1&hub=1&m=' + m + '&to=' + encodeURIComponent(to);
|
||||||
|
res.writeHead(302, { Location: loc }); return res.end();
|
||||||
|
}
|
||||||
|
if (u.pathname === '/sso/set') { res.writeHead(302, { Location: SP + '/' }); return res.end(); }
|
||||||
|
if (u.pathname === '/v1/sso/signout') return send(200, { ok: true, ended: 1 });
|
||||||
|
return send(404, { error: 'not here' });
|
||||||
|
}); });
|
||||||
|
await new Promise(r => hub.listen(0, '127.0.0.1', r));
|
||||||
|
const HUB = 'http://127.0.0.1:' + hub.address().port;
|
||||||
|
|
||||||
|
// ---- stand-in InstantAdPay: the switch interface iapswitch.js documents
|
||||||
|
const iap = { 'alice@example.com': { un: 'alice', on: true, pro: true }, 'bob@example.com': { un: 'bob', on: false, pro: false }, 'carol@example.com': { un: 'carol', on: true, pro: false } };
|
||||||
|
const iapCalls = []; let iapDown = false;
|
||||||
|
const iapSrv = http.createServer((req, res) => { let raw = ''; req.on('data', c => { raw += c; }); req.on('end', () => {
|
||||||
|
const send = (code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); };
|
||||||
|
if (req.url !== '/api/partner/stackpol/switch' || req.method !== 'POST') return send(404, { error: 'no' });
|
||||||
|
if (iapDown) return send(503, { error: 'down' });
|
||||||
|
const ts = String(req.headers['x-stack-ts'] || ''), sig = String(req.headers['x-stack-sig'] || '');
|
||||||
|
const want = crypto.createHmac('sha256', SWITCH_KEY).update(ts + '\n' + raw).digest('hex');
|
||||||
|
if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want)) || Math.abs(Date.now() - Number(ts)) > 300000) return send(401, { error: 'bad signature' });
|
||||||
|
const b = JSON.parse(raw); const a = iap[b.email]; iapCalls.push(b);
|
||||||
|
if (!a) return send(404, { error: 'no account' });
|
||||||
|
if (typeof b.on === 'boolean') a.on = b.on;
|
||||||
|
return send(200, { on: a.on, username: a.un, pro: a.pro });
|
||||||
|
}); });
|
||||||
|
await new Promise(r => iapSrv.listen(0, '127.0.0.1', r));
|
||||||
|
const IAP = 'http://127.0.0.1:' + iapSrv.address().port;
|
||||||
|
|
||||||
|
// ---- boot a Stack POL server on its own temp data dir
|
||||||
|
const kids = [];
|
||||||
|
async function boot(extra) {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'stackpol-my-'));
|
||||||
|
fs.writeFileSync(path.join(dir, 'stack-index.json'), JSON.stringify(Object.assign({}, snap, { at: undefined })));
|
||||||
|
fs.writeFileSync(path.join(dir, 'stack-index-at.json'), JSON.stringify({ at: snap.at }));
|
||||||
|
const port = 20000 + Math.floor(Math.random() * 20000);
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, SITE_URL: 'http://127.0.0.1:' + port, HUB_SSO: 'on', HUB_URL: HUB, HUB_SECRET, HUB_SITE: 'stackpol', NETKB: '0', HUB_ACTIVITY: '0', IAP_URL: IAP, STACK_INGEST_KEY: 'test-ingest-key' }, extra || {});
|
||||||
|
delete env.DOCSTORE_URL; delete env.NETWORK_SSO_SECRET; delete env.OPENROUTER_API_KEY;
|
||||||
|
for (const k of Object.keys(extra || {})) if (extra[k] == null) delete env[k];
|
||||||
|
const kid = spawn(process.execPath, [path.join(ROOT, 'server.js')], { env, stdio: ['ignore', 'pipe', 'pipe'] }); kids.push(kid);
|
||||||
|
let log = ''; kid.stdout.on('data', d => { log += d; }); kid.stderr.on('data', d => { log += d; });
|
||||||
|
const base = 'http://127.0.0.1:' + port;
|
||||||
|
for (let i = 0; i < 100; i++) { try { const r = await fetch(base + '/health'); if (r.ok) break; } catch (e) {} await new Promise(r => setTimeout(r, 100)); }
|
||||||
|
return { base, dir, log: () => log };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- a browser: one cookie jar for the Stack POL server, follows redirects across the stand-ins
|
||||||
|
function browser(base) {
|
||||||
|
const jar = new Map();
|
||||||
|
const cookieHeader = () => [...jar].map(([k, v]) => k + '=' + v).join('; ');
|
||||||
|
const take = r => { for (const c of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv, ...attrs] = c.split(';'); const i = kv.indexOf('='); const k = kv.slice(0, i).trim(), v = kv.slice(i + 1).trim(); const age = attrs.map(a => a.trim()).find(a => /^max-age=/i.test(a)); if (age && Number(age.split('=')[1]) <= 0) jar.delete(k); else jar.set(k, v); } };
|
||||||
|
async function go(url, opts) {
|
||||||
|
opts = opts || {}; let hops = []; let r;
|
||||||
|
for (let i = 0; i < 12; i++) {
|
||||||
|
const mine = url.startsWith(base);
|
||||||
|
const headers = Object.assign({ 'User-Agent': UA }, opts.headers || {}); if (mine && jar.size) headers.Cookie = cookieHeader();
|
||||||
|
r = await fetch(url, { method: i === 0 ? opts.method || 'GET' : 'GET', headers, body: i === 0 ? opts.body : undefined, redirect: 'manual' });
|
||||||
|
if (mine) take(r);
|
||||||
|
hops.push(r.status + ' ' + url.replace(base, '').replace(HUB, 'HUB').slice(0, 90));
|
||||||
|
const loc = r.headers.get('location'); if (!loc || r.status < 300 || r.status >= 400 || opts.noFollow) break;
|
||||||
|
url = new URL(loc, url).toString();
|
||||||
|
}
|
||||||
|
const text = await r.text();
|
||||||
|
return { status: r.status, text, url, hops, location: r.headers.get('location') };
|
||||||
|
}
|
||||||
|
const post = (p, form, headers) => go(base + p, { method: 'POST', body: new URLSearchParams(form).toString(), headers: Object.assign({ 'Content-Type': 'application/x-www-form-urlencoded', Origin: base }, headers || {}) });
|
||||||
|
return { go, post, jar };
|
||||||
|
}
|
||||||
|
const signIn = async (b, who) => { hubUser = who; const r = await b.go(SP + '/sso/start?mode=go&to=%2Fmy'); hubUser = null; return r; };
|
||||||
|
|
||||||
|
try {
|
||||||
|
// ===== server 1: hub sign-in + the switch interface on
|
||||||
|
const s1 = await boot({ STACKPOL_SWITCH_KEY: SWITCH_KEY }); SP = s1.base;
|
||||||
|
|
||||||
|
// signed out: one silent check, then the sign-in page saying this browser is not signed in anywhere
|
||||||
|
const anon = browser(s1.base);
|
||||||
|
let r = await anon.go(s1.base + '/my');
|
||||||
|
ok(r.hops[0].startsWith('303 /my'), 'signed-out /my starts one silent check: ' + r.hops[0]);
|
||||||
|
ok(r.hops.some(h => h.includes('HUB/sso/check')), 'the silent check goes through the hub');
|
||||||
|
ok(r.status === 200 && /signin=none/.test(r.url), 'nobody on the hub: back to /my?signin=none (' + r.url + ')');
|
||||||
|
ok(/Sign in with your network account/.test(r.text) && /not signed in anywhere in the network/.test(r.text), 'sign-in page with the not-signed-in note');
|
||||||
|
ok(/href="\/sso\/start\?mode=go&to=%2Fmy"/.test(r.text), 'the sign-in button starts a deliberate hub sign-in');
|
||||||
|
r = await anon.go(s1.base + '/my');
|
||||||
|
ok(r.hops.length === 1 && r.status === 200, 'no second silent check (loop guard)');
|
||||||
|
ok(!anon.jar.has('sp.sid'), 'no session without a sign-in');
|
||||||
|
|
||||||
|
// sign-in callback: alice
|
||||||
|
const alice = browser(s1.base);
|
||||||
|
r = await signIn(alice, { email: 'alice@example.com', wallet: W.a1, name: 'alice' });
|
||||||
|
ok(r.status === 200 && r.url === s1.base + '/my', 'alice lands on /my after the hub sign-in (' + r.hops.join(' > ') + ')');
|
||||||
|
ok(alice.jar.has('sp.sid') && alice.jar.get('sp.in') === '1', 'session cookie + header hint set');
|
||||||
|
ok(/@alice/.test(r.text), '/my names @alice');
|
||||||
|
ok(/<span class="pill on">On<\/span>/.test(r.text) && /Live now/.test(r.text), 'page switch shows On and live');
|
||||||
|
ok(r.text.includes('value="' + s1.base + '/alice"'), 'page link ready to copy');
|
||||||
|
ok(/<span class="pill on">Pro<\/span>/.test(r.text) && /1 spin link/.test(r.text), 'Pro status shown with what is on the page');
|
||||||
|
ok(r.text.includes('value="https://instantadpay.com/join/alice"') && r.text.includes('value="https://linkspin.app/join/alice"'), 'join links carry alice');
|
||||||
|
ok(r.text.includes('instantadpay.com/g/polhunter?ref=alice') || r.text.includes('ref=alice'), 'game join links carry alice');
|
||||||
|
ok(r.text.includes('13.83') && r.text.includes('>3</b><span>payments'), 'payout total 13.83 POL in 3 payments, as the ledger has it');
|
||||||
|
ok(r.text.includes('polygonscan.com/tx/' + TX(1)) && r.text.includes('polygonscan.com/tx/' + TX(3)), 'payout rows link to Polygonscan');
|
||||||
|
ok(!r.text.includes(TX(4)), "bob's payout is not on alice's page");
|
||||||
|
ok(r.text.includes('polygonscan.com/address/' + W.a2), 'both of alice\'s wallets listed');
|
||||||
|
ok(/\/qr\/alice\.svg/.test(r.text) && /og-stackpol-1200x630\.jpg/.test(r.text), 'share kit: QR (Pro) and the share image');
|
||||||
|
ok(/Switch my page off/.test(r.text) && /same switch as InstantAdPay Promo tools/.test(r.text), 'the switch is there');
|
||||||
|
ok(!/[–—]/.test(r.text), 'no em or en dashes on /my');
|
||||||
|
|
||||||
|
// the callback refuses a replayed token, a wrong state and a token signed with another key
|
||||||
|
{
|
||||||
|
const st = crypto.randomBytes(16).toString('hex');
|
||||||
|
const evil = browser(s1.base);
|
||||||
|
await evil.go(s1.base + '/sso/start?mode=go&to=%2Fmy', { noFollow: true }); // gets a real state cookie
|
||||||
|
const real = evil.jar.get('nsso.st');
|
||||||
|
const good = hubToken({ email: 'alice@example.com', st: real });
|
||||||
|
r = await evil.go(s1.base + '/sso/in?h=' + good, { noFollow: true });
|
||||||
|
ok(r.status === 302 && r.location === '/my' && evil.jar.has('sp.sid'), 'a good token signs in');
|
||||||
|
const ev2 = browser(s1.base); await ev2.go(s1.base + '/sso/start?mode=go&to=%2Fmy', { noFollow: true }); ev2.jar.set('nsso.st', real);
|
||||||
|
r = await ev2.go(s1.base + '/sso/in?h=' + good, { noFollow: true });
|
||||||
|
ok(!ev2.jar.has('sp.sid'), 'the same token a second time is refused');
|
||||||
|
const ev3 = browser(s1.base); await ev3.go(s1.base + '/sso/start?mode=go&to=%2Fmy', { noFollow: true });
|
||||||
|
r = await ev3.go(s1.base + '/sso/in?h=' + hubToken({ email: 'alice@example.com', st }), { noFollow: true });
|
||||||
|
ok(!ev3.jar.has('sp.sid'), 'a token for another state is refused');
|
||||||
|
const ev4 = browser(s1.base); await ev4.go(s1.base + '/sso/start?mode=go&to=%2Fmy', { noFollow: true });
|
||||||
|
r = await ev4.go(s1.base + '/sso/in?h=' + hubToken({ email: 'alice@example.com', st: ev4.jar.get('nsso.st') }, crypto.randomBytes(24).toString('hex')), { noFollow: true });
|
||||||
|
ok(!ev4.jar.has('sp.sid'), 'a token signed with another key is refused');
|
||||||
|
const ev5 = browser(s1.base); ev5.jar.set('sp.sid', 'v1.' + b64u(JSON.stringify({ e: 'alice@example.com', iat: Date.now(), exp: Date.now() + 1e6 })) + '.' + b64u(crypto.randomBytes(32)));
|
||||||
|
r = await ev5.go(s1.base + '/my?signin=none');
|
||||||
|
ok(!/@alice/.test(r.text), 'a forged session cookie is not a session');
|
||||||
|
}
|
||||||
|
|
||||||
|
// the switch: off from Stack POL, IAP gets it, /my and the public page follow at once
|
||||||
|
ok((await fetch(s1.base + '/alice')).status === 200, 'alice public page is up before the switch');
|
||||||
|
const before = iapCalls.length;
|
||||||
|
r = await alice.post('/api/my/switch', { on: '0' });
|
||||||
|
ok(/sw=ok/.test(r.url) && iapCalls.length > before && iapCalls.some(c => c.email === 'alice@example.com' && c.on === false), 'switch off sent to IAP signed (' + r.url + ')');
|
||||||
|
ok(iap['alice@example.com'].on === false, 'IAP now has alice off');
|
||||||
|
ok(/<span class="pill off">Off<\/span>/.test(r.text) && /Switched off/.test(r.text) && /Switch my page on/.test(r.text), '/my shows Off');
|
||||||
|
ok((await fetch(s1.base + '/alice')).status === 404, 'public page hidden right away');
|
||||||
|
ok((await fetch(s1.base + '/qr/alice.svg')).status === 404, 'QR hidden with it');
|
||||||
|
r = await alice.post('/api/my/switch', { on: '1' });
|
||||||
|
ok(iap['alice@example.com'].on === true && /pill on">On/.test(r.text), 'switch back on');
|
||||||
|
ok((await fetch(s1.base + '/alice')).status === 200, 'public page back');
|
||||||
|
// a switch made in IAP itself shows on /my (one place for the switch)
|
||||||
|
iap['alice@example.com'].on = false; r = await alice.go(s1.base + '/my'); ok(/pill off">Off/.test(r.text), 'a switch made in IAP shows on /my'); iap['alice@example.com'].on = true;
|
||||||
|
// cross-site post refused; IAP down = nothing changed, said so
|
||||||
|
r = await alice.post('/api/my/switch', { on: '0' }, { Origin: 'https://evil.example' });
|
||||||
|
ok(r.status === 403 && iap['alice@example.com'].on === true, 'cross-site switch refused');
|
||||||
|
iapDown = true; r = await alice.post('/api/my/switch', { on: '0' }); iapDown = false;
|
||||||
|
ok(/sw=err/.test(r.url) && /did not go through/.test(r.text), 'IAP down: switch error shown, nothing changed');
|
||||||
|
ok((await fetch(s1.base + '/alice')).status === 200, 'IAP down: public page untouched');
|
||||||
|
const nobody = browser(s1.base); r = await nobody.post('/api/my/switch', { on: '0' });
|
||||||
|
ok(iap['alice@example.com'].on === true, 'no session: no switch');
|
||||||
|
|
||||||
|
// bob: switched off, has payouts, no Pro
|
||||||
|
const bob = browser(s1.base);
|
||||||
|
r = await signIn(bob, { email: 'bob@example.com', wallet: W.b1, name: 'bob' });
|
||||||
|
ok(/@bob/.test(r.text) && /pill off">Off/.test(r.text) && /Switch my page on/.test(r.text), 'bob: page Off, switch offered');
|
||||||
|
ok(/pill off">Not yet/.test(r.text) && /\$10 or more/.test(r.text), 'bob: not Pro, how Pro unlocks');
|
||||||
|
ok(r.text.includes('4.25') && r.text.includes('polygonscan.com/tx/' + TX(4)) && !r.text.includes(TX(1)), 'bob: his own payouts only');
|
||||||
|
ok((await fetch(s1.base + '/bob')).status === 404, 'bob: no public page');
|
||||||
|
|
||||||
|
// carol: nothing yet
|
||||||
|
const carol = browser(s1.base);
|
||||||
|
r = await signIn(carol, { email: 'carol@example.com', name: 'carol' });
|
||||||
|
ok(/@carol/.test(r.text) && /goes live with your first payout/.test(r.text) && /No payouts on the ledger for @carol yet/.test(r.text), 'carol: no page yet, no payouts yet');
|
||||||
|
ok(r.text.includes('value="https://instantadpay.com/join/carol"'), 'carol: join links ready');
|
||||||
|
ok(!/\/qr\/carol\.svg/.test(r.text), 'carol: no QR (not Pro)');
|
||||||
|
|
||||||
|
// sign out: cookies cleared, the old cookie stops working, no silent re-sign-in
|
||||||
|
const oldSid = alice.jar.get('sp.sid');
|
||||||
|
r = await alice.post('/api/my/signout', {});
|
||||||
|
ok(/\/my\?out=1$/.test(r.url) && /You are signed out of Stack POL/.test(r.text), 'sign-out lands on the signed-out page');
|
||||||
|
ok(!alice.jar.has('sp.sid') && !alice.jar.has('sp.in') && alice.jar.get('nsso.off') === '1', 'session and header hint cleared, silent check paused');
|
||||||
|
const thief = browser(s1.base); thief.jar.set('sp.sid', oldSid);
|
||||||
|
r = await thief.go(s1.base + '/my?signin=none');
|
||||||
|
ok(!/@alice/.test(r.text) && /Sign in with your network account/.test(r.text), 'the cookie from before the sign-out no longer works');
|
||||||
|
r = await alice.go(s1.base + '/my');
|
||||||
|
ok(r.hops.length === 1 && !/@alice/.test(r.text), 'after sign-out /my does not sign back in by itself');
|
||||||
|
r = await bob.post('/api/my/signout', { everywhere: '1' });
|
||||||
|
ok(hubCalls.includes('/v1/sso/signout'), 'sign out of the whole network asks the hub');
|
||||||
|
|
||||||
|
// public pages: no sign-in needed, header entry in the site look
|
||||||
|
for (const p of ['/', '/ledger', '/programs', '/blog', '/earn/instantadpay']) {
|
||||||
|
const x = await fetch(s1.base + p); const t = await x.text();
|
||||||
|
ok(x.status === 200 && /id="spmy" href="\/my"[^>]*>Sign in<\/a>/.test(t), p + ' is public and has the Sign in entry');
|
||||||
|
}
|
||||||
|
const robots = await (await fetch(s1.base + '/robots.txt')).text();
|
||||||
|
ok(/Disallow: \/my/.test(robots), 'robots keeps /my out');
|
||||||
|
|
||||||
|
// ===== server 2: no switch interface (IAP not changed yet): /my links to Promo tools; wallet match when the network name differs
|
||||||
|
const s2 = await boot({ STACKPOL_SWITCH_KEY: null }); SP = s2.base;
|
||||||
|
const b2 = browser(s2.base);
|
||||||
|
r = await signIn(b2, { email: 'bob@example.com', wallet: W.b1, name: 'bobby' });
|
||||||
|
ok(/@bob\b/.test(r.text) && !/@bobby/.test(r.text), 'wallet match: the network name bobby resolves to the Stack POL member bob');
|
||||||
|
ok(/pill off">Off/.test(r.text), 'state from the snapshot: bob switched off in IAP');
|
||||||
|
ok(/Change it in InstantAdPay/.test(r.text) && r.text.includes(IAP + '/my#promo?s=stackpol') && !/Switch my page on/.test(r.text), 'no interface: a link to IAP Promo tools, no switch button');
|
||||||
|
const calls = iapCalls.length; r = await b2.post('/api/my/switch', { on: '1' });
|
||||||
|
ok(/sw=err/.test(r.url) && iapCalls.length === calls, 'no interface: a post changes nothing and calls nobody');
|
||||||
|
const a2 = browser(s2.base);
|
||||||
|
r = await signIn(a2, { email: 'alice@example.com', wallet: W.a2, name: 'alice' });
|
||||||
|
ok(/pill on">On/.test(r.text) && /pill on">Pro/.test(r.text), 'no interface: alice On + Pro from the snapshot');
|
||||||
|
const n2 = browser(s2.base);
|
||||||
|
r = await signIn(n2, { email: 'new@example.com', name: 'new.person' });
|
||||||
|
ok(/Pick a username first/.test(r.text), 'no Stack POL username: asked to pick one in IAP');
|
||||||
|
|
||||||
|
// ingest still works and keeps `my`
|
||||||
|
const ing = await fetch(s2.base + '/api/ingest', { method: 'POST', headers: { Authorization: 'Bearer test-ingest-key', 'Content-Type': 'application/json' }, body: JSON.stringify(Object.assign({}, snap, { at: Date.now() })) });
|
||||||
|
ok(ing.status === 200, 'ingest accepts the snapshot with `my`');
|
||||||
|
r = await a2.go(s2.base + '/my'); ok(/13\.83/.test(r.text), '/my reads the pushed snapshot');
|
||||||
|
} catch (e) { fail++; console.log('FAIL threw', e.stack); }
|
||||||
|
finally { for (const k of kids) k.kill(); hub.close(); iapSrv.close(); }
|
||||||
|
console.log(pass + ' passed, ' + fail + ' failed');
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// Semantic matching, site side (netkb.js route/suggest/match, 2026-11-16) + parity of the shared files: node qa/netkb-semantic.test.mjs
|
||||||
|
// A stand-in hub answers /v1/kb/match with scripted hits, so no model and no network. Checks: a sure match answers with this site's
|
||||||
|
// entry, a pattern hit is kept when the match agrees or has no idea and overruled when the match points elsewhere, other sites'
|
||||||
|
// entries rank behind this site's unless named or clearly closer, a named site that asks about "here" stays home, a slow or down hub
|
||||||
|
// answers null inside the timeout and is skipped for a while (fail soft), and the support suggestions never offer the contact-support entry.
|
||||||
|
// Parity: netkb.js is the same file in all eight network sites, chatcore.js + kb.js in the six that share them (checked against the
|
||||||
|
// sibling checkouts beside this one; a missing sibling is skipped, a different one fails).
|
||||||
|
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline Banners, Stack POL).
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import http from 'node:http';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
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')), '..');
|
||||||
|
let pass = 0, fail = 0, skip = 0;
|
||||||
|
const ok = (c, m) => { if (c) pass++; else { fail++; console.log('FAIL', m); } };
|
||||||
|
|
||||||
|
// ---- parity with the sibling checkouts
|
||||||
|
const sha = f => crypto.createHash('sha1').update(fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n')).digest('hex');
|
||||||
|
const SIBLINGS = ['onchain-ad-membership/site', 'linkspin/site', 'vbb/app', 'banner-line/app', 'viraladblitz/app', 'downlinehydra/app', '5xyourteam/app', 'stackpol'];
|
||||||
|
const KIT = new Set(['vbb/app', 'banner-line/app', 'viraladblitz/app', 'downlinehydra/app', '5xyourteam/app', 'stackpol']);
|
||||||
|
let base = ROOT; for (let i = 0; i < 4 && !SIBLINGS.some(s => path.resolve(base, s) === ROOT); i++) base = path.dirname(base);
|
||||||
|
const mine = SIBLINGS.find(s => path.resolve(base, s) === ROOT);
|
||||||
|
for (const s of SIBLINGS) {
|
||||||
|
if (s === mine) continue;
|
||||||
|
const dir = path.resolve(base, s);
|
||||||
|
const files = ['netkb.js'].concat(mine && KIT.has(mine) && KIT.has(s) ? ['chatcore.js', 'kb.js'] : []);
|
||||||
|
for (const f of files) {
|
||||||
|
if (!fs.existsSync(path.join(dir, f))) { skip++; continue; }
|
||||||
|
ok(sha(path.join(dir, f)) === sha(path.join(ROOT, f)), 'parity: ' + f + ' differs from ' + s + '/' + f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ok(/The SAME file ships in every network site/.test(fs.readFileSync(path.join(ROOT, 'netkb.js'), 'utf8')), 'netkb.js carries the shared-file header');
|
||||||
|
|
||||||
|
// ---- a stand-in hub
|
||||||
|
let script = () => ({ hits: [], margin: 0 }), delay = 0, status = 200, last = null;
|
||||||
|
const hub = http.createServer((req, res) => { let b = ''; req.on('data', c => { b += c; }); req.on('end', () => {
|
||||||
|
last = { path: req.url, body: JSON.parse(b || '{}'), site: req.headers['x-hub-site'] };
|
||||||
|
setTimeout(() => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(status === 200 ? Object.assign({ ok: true }, script(last.body)) : { error: 'embeddings_down' })); }, delay);
|
||||||
|
}); });
|
||||||
|
await new Promise(r => hub.listen(0, '127.0.0.1', r));
|
||||||
|
process.env.HUB_URL = 'http://127.0.0.1:' + hub.address().port; process.env.HUB_SECRET = 'q'.repeat(40); process.env.HUB_SITE = 'home'; process.env.NETKB_MATCH_MS = '400';
|
||||||
|
delete process.env.NETKB; delete process.env.NETKB_MATCH;
|
||||||
|
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'nksem-'));
|
||||||
|
const netkb = require(path.join(ROOT, 'netkb.js'));
|
||||||
|
netkb._set({ version: 'v', sites: { home: { name: 'Home', url: 'https://home.example' }, other: { name: 'Other', url: 'https://other.example' } },
|
||||||
|
entries: [{ site: 'other', id: 'c-split', title: 'Other split', questions: [], answer: 'Other split answer.', tags: [] }] });
|
||||||
|
const own = [{ id: 'c-split', title: 'Split', answer: 'Home split.' }, { id: 'c-packages', title: 'Packages', answer: 'Home prices.' }, { id: 'c-support', title: 'Support', answer: 'Ask support.', handoff: true }, { id: 'kb-t1', title: 'From a ticket', answer: 'Ticket answer.', source: 'ticket' }];
|
||||||
|
const H = (site, id, score) => ({ site, id, title: id, answer: '', score, boosted: score + (site === 'home' ? 0.08 : 0), home: site === 'home' });
|
||||||
|
const set = (hits, margin) => { script = () => ({ hits, margin: margin == null ? 0.1 : margin, confidence: hits.length ? hits[0].score : 0 }); };
|
||||||
|
|
||||||
|
// a sure match answers with this site's entry, even over a pattern hit that points elsewhere
|
||||||
|
set([H('home', 'c-split', 0.93), H('home', 'c-packages', 0.7)]);
|
||||||
|
let r = await netkb.route('how much do I earn', { fast: own[1], own });
|
||||||
|
ok(r && r.via === 'answer' && r.hit.id === 'c-split', 'sure match answers (' + JSON.stringify(r && [r.via, r.hit && r.hit.id]) + ')');
|
||||||
|
ok(last && last.path === '/v1/kb/match' && last.site === 'home' && last.body.k === 8, 'signed match call as this site');
|
||||||
|
// the pattern hit kept when the match agrees
|
||||||
|
set([H('home', 'c-split', 0.78), H('home', 'c-packages', 0.72)], 0.01);
|
||||||
|
r = await netkb.route('what does it cost', { fast: own[1], own });
|
||||||
|
ok(r && r.via === 'agree' && r.hit.id === 'c-packages', 'pattern kept when the match agrees (' + (r && r.via) + ')');
|
||||||
|
// the pattern hit kept when the match has no idea
|
||||||
|
set([H('home', 'c-split', 0.55)]);
|
||||||
|
r = await netkb.route('zzq', { fast: own[1], own });
|
||||||
|
ok(r && r.via === 'regex' && r.hit.id === 'c-packages', 'pattern kept when the match has no idea');
|
||||||
|
// overruled when the match points elsewhere with some confidence
|
||||||
|
set([H('home', 'c-split', 0.8), H('home', 'kb-t1', 0.75)], 0.05);
|
||||||
|
r = await netkb.route('what is my cut when my friends buy', { fast: own[1], own });
|
||||||
|
ok(r && r.via === 'veto' && r.hit === null && r.hits[0].entry.id === 'c-split', 'pattern overruled, the match feeds the prompt (' + (r && r.via) + ')');
|
||||||
|
// home first: another site's entry stays behind unless clearly closer
|
||||||
|
set([H('other', 'c-split', 0.82), H('home', 'c-split', 0.79)], 0.02);
|
||||||
|
r = await netkb.route('my cut', { own });
|
||||||
|
ok(r && r.via === 'context' && r.hits[0].entry.id === 'c-split' && !r.hits[0].entry.site, 'home entry first when no site is named');
|
||||||
|
set([H('other', 'c-split', 0.95), H('home', 'c-packages', 0.70)], 0.2);
|
||||||
|
r = await netkb.route('other thing', { own });
|
||||||
|
ok(r && !r.hits[0].entry.site && r.hits.some(h => h.entry.site === 'other'), 'another site rides behind this site entry when clearly closer');
|
||||||
|
set([H('other', 'c-split', 0.95), H('home', 'c-packages', 0.55)], 0.2);
|
||||||
|
r = await netkb.route('other thing', { own });
|
||||||
|
ok(r && r.hits[0].entry.site === 'other', 'another site leads when this site has nothing close');
|
||||||
|
// a named site asked about "here" stays home (no prefer sent)
|
||||||
|
set([H('home', 'c-split', 0.9)]);
|
||||||
|
await netkb.route('I am on Other, will my team carry over here?', { own, prefer: ['other'] });
|
||||||
|
ok(!last.body.prefer, 'named site + "here": no prefer');
|
||||||
|
await netkb.route('How much is the split on Other?', { own, prefer: ['other'] });
|
||||||
|
ok(Array.isArray(last.body.prefer) && last.body.prefer[0] === 'other', 'named site: prefer sent');
|
||||||
|
// remote never answers outright
|
||||||
|
set([H('other', 'c-split', 0.99)], 0.3);
|
||||||
|
r = await netkb.route('How much is the split on Other?', { own, prefer: ['other'] });
|
||||||
|
ok(r && r.hit === null && r.hits[0].entry.site === 'other', 'another site\'s entry rides as context, never the instant answer');
|
||||||
|
|
||||||
|
// suggestions: KB entries only, no contact-support entry, ticket-derived entries labelled
|
||||||
|
set([H('home', 'kb-t1', 0.82), H('home', 'c-support', 0.8), H('home', 'c-split', 0.79), H('home', 'c-packages', 0.5)]);
|
||||||
|
let s = await netkb.suggest('my payout never arrived after a purchase', { own });
|
||||||
|
ok(s.via === 'semantic' && s.items.map(i => i.id).join() === 'kb-t1,c-split', 'suggest: closest answers, no support entry, no weak ones (' + s.items.map(i => i.id) + ')');
|
||||||
|
ok(s.items[0].fromTicket === true && s.items[1].fromTicket === false, 'suggest: past-ticket entries labelled');
|
||||||
|
s = await netkb.suggest('hi', { own }); ok(s.items.length === 0 && s.via === 'short', 'suggest: too short asks nothing');
|
||||||
|
|
||||||
|
// fail soft: slow hub -> null inside the timeout, then skipped for a while; down hub -> null; suggest falls back to BM25
|
||||||
|
netkb._matchReset(); delay = 2000;
|
||||||
|
let t0 = Date.now(); r = await netkb.route('anything', { own }); const took = Date.now() - t0;
|
||||||
|
ok(r === null && took < 1500, 'slow hub: null within the timeout (' + took + ' ms)');
|
||||||
|
delay = 0; t0 = Date.now(); r = await netkb.route('anything', { own });
|
||||||
|
ok(r === null && Date.now() - t0 < 50, 'after a failure the hub is skipped for a while (no wait)');
|
||||||
|
s = await netkb.suggest('my payout never arrived after a purchase', { own, fallback: async () => [{ entry: own[0] }, { entry: own[2] }] });
|
||||||
|
ok(s.via === 'bm25' && s.items.map(i => i.id).join() === 'c-split', 'suggest falls back to BM25 when the hub is skipped');
|
||||||
|
netkb._matchReset(); status = 503;
|
||||||
|
r = await netkb.route('anything', { own }); ok(r === null, 'hub 503: null');
|
||||||
|
netkb._matchReset(); status = 200;
|
||||||
|
process.env.NETKB_MATCH = '0'; r = await netkb.route('anything', { own }); ok(r === null, 'NETKB_MATCH=0: off'); delete process.env.NETKB_MATCH;
|
||||||
|
const v = netkb.view(); ok(v.matchErrors >= 2 && v.semAnswer >= 1 && typeof v.sem.answer === 'number', 'view carries the semantic counters');
|
||||||
|
|
||||||
|
hub.close();
|
||||||
|
console.log((fail ? 'FAILED ' : 'ok ') + pass + ' passed, ' + fail + ' failed' + (skip ? ', ' + skip + ' sibling files not here (skipped)' : ''));
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
@@ -2,14 +2,20 @@
|
|||||||
// full SEO footprint. Every POL payout across the network, stacked: a network home with live totals, one page per program,
|
// full SEO footprint. Every POL payout across the network, stacked: a network home with live totals, one page per program,
|
||||||
// the public ledger (every row links to Polygonscan), opt-in member stacks at /<username>, and the blog.
|
// the public ledger (every row links to Polygonscan), opt-in member stacks at /<username>, and the blog.
|
||||||
// Data: tools/indexer.py on core reads every program's payout records and IAP/LinkSpin's chain index every 5 minutes and POSTs
|
// Data: tools/indexer.py on core reads every program's payout records and IAP/LinkSpin's chain index every 5 minutes and POSTs
|
||||||
// one JSON snapshot to /api/ingest (Bearer STACK_INGEST_KEY). Pages read that snapshot, never the chain. The last snapshot is
|
// one JSON snapshot to /api/ingest (Bearer STACK_INGEST_KEY). Pages read that snapshot, never the chain.
|
||||||
// kept in /tmp so a restart serves numbers at once; the next push replaces it within 5 minutes.
|
// Storage (Marty 2026-11-16: "Stack POL wipes its payout totals on every deploy; they should live in the database"): the last
|
||||||
|
// snapshot and the chatbot's knowledge base are MySQL documents through docstore.js (DOCSTORE_URL, Coolify stackpol-mysql), loaded
|
||||||
|
// at boot before the server listens, so a restart or deploy serves the last totals at once. The snapshot is two documents:
|
||||||
|
// stack-index.json (everything but `at`) and stack-index-at.json ({at}), so a push with no new payouts rewrites only the tiny one
|
||||||
|
// (docstore skips unchanged bodies; binlog stays small). Without DOCSTORE_URL (local only) they are files in DATA_DIR.
|
||||||
'use strict';
|
'use strict';
|
||||||
const http = require('http');
|
const http = require('http');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
|
||||||
|
const docstore = require('./docstore'); docstore.install(DATA_DIR); // before any module reads data
|
||||||
const zlib = require('zlib');
|
const zlib = require('zlib');
|
||||||
const { SITE, esc, head, tail, ZONES, spot, personalize, memberLinks, proCta } = require('./layout');
|
const { SITE, esc, head, tail, ZONES, spot, personalize, memberLinks, memberVideos, proCta } = require('./layout');
|
||||||
let QR = null; try { QR = require('qrcode'); } catch (e) { console.error('[stackpol] qrcode module missing: no QR on Pro pages'); }
|
let QR = null; try { QR = require('qrcode'); } catch (e) { console.error('[stackpol] qrcode module missing: no QR on Pro pages'); }
|
||||||
const { PROGRAMS, BY_KEY, BY_SLUG } = require('./programs');
|
const { PROGRAMS, BY_KEY, BY_SLUG } = require('./programs');
|
||||||
const blog = require('./blog');
|
const blog = require('./blog');
|
||||||
@@ -17,9 +23,16 @@ const blog = require('./blog');
|
|||||||
const PORT = Number(process.env.PORT) || 80;
|
const PORT = Number(process.env.PORT) || 80;
|
||||||
const KEY = String(process.env.STACK_INGEST_KEY || '').trim();
|
const KEY = String(process.env.STACK_INGEST_KEY || '').trim();
|
||||||
const OWNER = 'martbost'; // the network pages' join links (the site owner's referral)
|
const OWNER = 'martbost'; // the network pages' join links (the site owner's referral)
|
||||||
const SNAP = '/tmp/stack-index.json';
|
const SNAP = path.join(DATA_DIR, 'stack-index.json'), SNAP_AT = path.join(DATA_DIR, 'stack-index-at.json');
|
||||||
const PUB = path.join(__dirname, 'public');
|
const PUB = path.join(__dirname, 'public');
|
||||||
let IDX = null; try { IDX = JSON.parse(fs.readFileSync(SNAP, 'utf8')); } catch (e) {}
|
let IDX = null;
|
||||||
|
function loadSnap() {
|
||||||
|
try { const j = JSON.parse(fs.readFileSync(SNAP, 'utf8')); let at = 0; try { at = Number(JSON.parse(fs.readFileSync(SNAP_AT, 'utf8')).at) || 0; } catch (e) {} j.at = at || j.at || null; IDX = j; } catch (e) { IDX = null; }
|
||||||
|
}
|
||||||
|
function saveSnap(j) {
|
||||||
|
const body = Object.assign({}, j); delete body.at;
|
||||||
|
fs.writeFileSync(SNAP, JSON.stringify(body)); fs.writeFileSync(SNAP_AT, JSON.stringify({ at: j.at }));
|
||||||
|
}
|
||||||
blog.load();
|
blog.load();
|
||||||
|
|
||||||
const fmt = n => Number(n || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
const fmt = n => Number(n || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||||
@@ -27,7 +40,7 @@ const fmtInt = n => Number(n || 0).toLocaleString('en-US');
|
|||||||
const ago = ts => { const s = Math.max(0, (Date.now() - ts) / 1000); return s < 90 ? 'just now' : s < 5400 ? Math.round(s / 60) + ' min ago' : s < 129600 ? Math.round(s / 3600) + ' h ago' : Math.round(s / 86400) + ' days ago'; };
|
const ago = ts => { const s = Math.max(0, (Date.now() - ts) / 1000); return s < 90 ? 'just now' : s < 5400 ? Math.round(s / 60) + ' min ago' : s < 129600 ? Math.round(s / 3600) + ' h ago' : Math.round(s / 86400) + ' days ago'; };
|
||||||
const when = ts => new Date(ts).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'America/Chicago' }) + ' CT';
|
const when = ts => new Date(ts).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'America/Chicago' }) + ' CT';
|
||||||
const shortTx = tx => tx ? tx.slice(0, 10) + '…' + tx.slice(-4) : '';
|
const shortTx = tx => tx ? tx.slice(0, 10) + '…' + tx.slice(-4) : '';
|
||||||
const RESERVED = new Set(['blog', 'ledger', 'programs', 'earn', 'api', 'img', 'sitemap', 'robots', 'favicon', 'about', 'admin', 'login', 'join', 'feed', 'www', 'static', 'assets']);
|
const RESERVED = new Set(['blog', 'ledger', 'programs', 'earn', 'api', 'img', 'sitemap', 'robots', 'favicon', 'about', 'admin', 'login', 'join', 'feed', 'www', 'static', 'assets', 'terms', 'privacy', 'disclaimer', 'sso', 'signin', 'signout', 'logout', 'account']);
|
||||||
const net = () => (IDX && IDX.network) || { pol: 0, payments: 0, wallets: 0 };
|
const net = () => (IDX && IDX.network) || { pol: 0, payments: 0, wallets: 0 };
|
||||||
const prog = k => (IDX && IDX.programs && IDX.programs[k]) || { pol: 0, payments: 0, wallets: 0 };
|
const prog = k => (IDX && IDX.programs && IDX.programs[k]) || { pol: 0, payments: 0, wallets: 0 };
|
||||||
const live = () => IDX ? '<div class="live"><span class="dot"></span>Ledger refreshed ' + ago(IDX.at) + '</div>' : '<div class="live"><span class="dot" style="background:var(--gold)"></span>Ledger warming up</div>';
|
const live = () => IDX ? '<div class="live"><span class="dot"></span>Ledger refreshed ' + ago(IDX.at) + '</div>' : '<div class="live"><span class="dot" style="background:var(--gold)"></span>Ledger warming up</div>';
|
||||||
@@ -104,6 +117,7 @@ function programPage(p, who) { const ref = who || OWNER; // a Pro member's ref (
|
|||||||
h += '<div class="cta"><a class="btn" href="' + esc(p.join(ref)) + '" rel="nofollow noopener" target="_blank">' + (p.verb || (p.k === 'iap' || p.k === 'ls' ? 'Join' : 'Play')) + ' ' + esc(p.n) + ' free</a><a class="btn sec" href="/ledger?p=' + p.k + '">Its payouts on the ledger</a></div></div>';
|
h += '<div class="cta"><a class="btn" href="' + esc(p.join(ref)) + '" rel="nofollow noopener" target="_blank">' + (p.verb || (p.k === 'iap' || p.k === 'ls' ? 'Join' : 'Play')) + ' ' + esc(p.n) + ' free</a><a class="btn sec" href="/ledger?p=' + p.k + '">Its payouts on the ledger</a></div></div>';
|
||||||
h += '<aside><img src="/img/' + p.k + '.jpg" alt="' + esc(p.n) + '" width="800" height="420" style="border-radius:18px;border:1px solid var(--line)"></aside></section>';
|
h += '<aside><img src="/img/' + p.k + '.jpg" alt="' + esc(p.n) + '" width="800" height="420" style="border-radius:18px;border:1px solid var(--line)"></aside></section>';
|
||||||
h += '<div class="sec-head"><h2>How ' + esc(p.n) + ' pays</h2></div><p class="lead" style="max-width:72ch">' + esc(p.how || ('Rewards are sent in POL from ' + p.n + '\'s own payout wallet straight to the wallet on your account, on the Polygon network. Every payment is a public transaction you can open on Polygonscan.')) + '</p>';
|
h += '<div class="sec-head"><h2>How ' + esc(p.n) + ' pays</h2></div><p class="lead" style="max-width:72ch">' + esc(p.how || ('Rewards are sent in POL from ' + p.n + '\'s own payout wallet straight to the wallet on your account, on the Polygon network. Every payment is a public transaction you can open on Polygonscan.')) + '</p>';
|
||||||
|
if (p.guides) h += '<p class="lead" style="max-width:72ch"><a href="' + esc(p.guides) + '" target="_blank" rel="noopener">Read the ' + esc(p.n) + ' guides</a> on its own site: how it works, whether it is legit (the contract, the ledger and the split) and the FAQ.</p>'; // 2026-11-17
|
||||||
h += '<div class="sec-head"><h2>Latest ' + esc(p.n) + ' payouts</h2><p><a href="/ledger?p=' + p.k + '">All of them</a></p></div>' + tableHead(true) + ledgerRows(rows, true) + '</tbody></table></div>';
|
h += '<div class="sec-head"><h2>Latest ' + esc(p.n) + ' payouts</h2><p><a href="/ledger?p=' + p.k + '">All of them</a></p></div>' + tableHead(true) + ledgerRows(rows, true) + '</tbody></table></div>';
|
||||||
const posts = blog.listPublished().filter(b => b.tags.includes(p.slug) || b.tags.includes(p.n.toLowerCase())).slice(0, 3);
|
const posts = blog.listPublished().filter(b => b.tags.includes(p.slug) || b.tags.includes(p.n.toLowerCase())).slice(0, 3);
|
||||||
if (posts.length) h += '<div class="sec-head"><h2>Guides</h2></div><div class="posts">' + posts.map(blog.cardHtml).join('') + '</div>';
|
if (posts.length) h += '<div class="sec-head"><h2>Guides</h2></div><div class="posts">' + posts.map(blog.cardHtml).join('') + '</div>';
|
||||||
@@ -132,6 +146,7 @@ function stackPage(u, st) {
|
|||||||
if (st.pro) { // Stack POL Pro (2026-11-09): the member's own links and a purple Polygon QR that opens this page
|
if (st.pro) { // Stack POL Pro (2026-11-09): the member's own links and a purple Polygon QR that opens this page
|
||||||
h += '<div class="prorow"><div style="min-width:0">' + (memberLinks(u, st) || '<p class="kick">@' + esc(u) + '\'s page</p>') + '<p class="lead" style="margin:6px 0 0">Scan the code to open @' + esc(u) + '\'s stack on your phone, or share it anywhere people can see it.</p></div>'
|
h += '<div class="prorow"><div style="min-width:0">' + (memberLinks(u, st) || '<p class="kick">@' + esc(u) + '\'s page</p>') + '<p class="lead" style="margin:6px 0 0">Scan the code to open @' + esc(u) + '\'s stack on your phone, or share it anywhere people can see it.</p></div>'
|
||||||
+ (QR ? '<div class="qr"><img src="/qr/' + esc(u) + '.svg" alt="QR code for stackpol.com/' + esc(u) + '" width="150" height="150"><span>stackpol.com/' + esc(u) + '</span></div>' : '') + '</div>';
|
+ (QR ? '<div class="qr"><img src="/qr/' + esc(u) + '.svg" alt="QR code for stackpol.com/' + esc(u) + '" width="150" height="150"><span>stackpol.com/' + esc(u) + '</span></div>' : '') + '</div>';
|
||||||
|
h += memberVideos(u, st); // their LinkSpin Video Spin (2026-11-23)
|
||||||
}
|
}
|
||||||
h += spot(ZONES.banner, ZONES.strip);
|
h += spot(ZONES.banner, ZONES.strip);
|
||||||
h += '<div class="sec-head"><h2>@' + esc(u) + '\'s latest payouts</h2></div>' + tableHead(false) + ledgerRows(st.recent || [], false) + '</tbody></table></div>';
|
h += '<div class="sec-head"><h2>@' + esc(u) + '\'s latest payouts</h2></div>' + tableHead(false) + ledgerRows(st.recent || [], false) + '</tbody></table></div>';
|
||||||
@@ -149,15 +164,15 @@ async function qrSvg(un) {
|
|||||||
function notFound(msg) { return head({ title: 'Not found | Stack POL', desc: 'This page is not on Stack POL.', path: '/404', noindex: true }) + '<section style="padding:60px 0"><h1>Nothing stacked here</h1><p class="lead">' + esc(msg || 'That page does not exist.') + '</p><p><a class="btn" href="/">Go to Stack POL</a></p></section>' + tail(); }
|
function notFound(msg) { return head({ title: 'Not found | Stack POL', desc: 'This page is not on Stack POL.', path: '/404', noindex: true }) + '<section style="padding:60px 0"><h1>Nothing stacked here</h1><p class="lead">' + esc(msg || 'That page does not exist.') + '</p><p><a class="btn" href="/">Go to Stack POL</a></p></section>' + tail(); }
|
||||||
function sitemap() {
|
function sitemap() {
|
||||||
const d = new Date().toISOString().slice(0, 10);
|
const d = new Date().toISOString().slice(0, 10);
|
||||||
const u = [['/', 'daily', '1.0'], ['/programs', 'daily', '0.9'], ['/ledger', 'hourly', '0.8'], ['/blog', 'daily', '0.9']].map(([p, f, pr]) => '<url><loc>' + SITE + p + '</loc><lastmod>' + d + '</lastmod><changefreq>' + f + '</changefreq><priority>' + pr + '</priority></url>').join('')
|
const u = [['/', 'daily', '1.0'], ['/programs', 'daily', '0.9'], ['/network', 'monthly', '0.7'], ['/ledger', 'hourly', '0.8'], ['/blog', 'daily', '0.9'], ['/terms', 'yearly', '0.2'], ['/privacy', 'yearly', '0.2'], ['/disclaimer', 'yearly', '0.2']].map(([p, f, pr]) => '<url><loc>' + SITE + p + '</loc><lastmod>' + d + '</lastmod><changefreq>' + f + '</changefreq><priority>' + pr + '</priority></url>').join('')
|
||||||
+ PROGRAMS.map(p => '<url><loc>' + SITE + '/earn/' + p.slug + '</loc><lastmod>' + d + '</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>').join('')
|
+ PROGRAMS.map(p => '<url><loc>' + SITE + '/earn/' + p.slug + '</loc><lastmod>' + d + '</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>').join('')
|
||||||
+ blog.listPublished().map(p => '<url><loc>' + SITE + '/blog/' + p.slug + '</loc><lastmod>' + new Date(p.updated).toISOString().slice(0, 10) + '</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url>').join('')
|
+ blog.listPublished().map(p => '<url><loc>' + SITE + '/blog/' + p.slug + '</loc><lastmod>' + new Date(p.updated).toISOString().slice(0, 10) + '</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url>').join('')
|
||||||
+ Object.keys((IDX && IDX.stacks) || {}).map(x => '<url><loc>' + SITE + '/' + x + '</loc><changefreq>daily</changefreq><priority>0.5</priority></url>').join('');
|
+ Object.keys((IDX && IDX.stacks) || {}).map(x => '<url><loc>' + SITE + '/' + x + '</loc><changefreq>daily</changefreq><priority>0.5</priority></url>').join('');
|
||||||
return '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + u + '</urlset>';
|
return '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + u + '</urlset>';
|
||||||
}
|
}
|
||||||
const robots = () => 'User-agent: *\nAllow: /\nDisallow: /api/\n\nSitemap: ' + SITE + '/sitemap.xml\n';
|
const robots = () => 'User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /my\nDisallow: /sso/\n\nSitemap: ' + SITE + '/sitemap.xml\n';
|
||||||
|
|
||||||
const TYPES = { '.jpg': 'image/jpeg', '.png': 'image/png', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.webmanifest': 'application/manifest+json', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
|
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.jpg': 'image/jpeg', '.png': 'image/png', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.webmanifest': 'application/manifest+json', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
|
||||||
function send(req, res, code, type, body, cache) {
|
function send(req, res, code, type, body, cache) {
|
||||||
const h = { 'Content-Type': type, 'Cache-Control': cache || 'public, max-age=60', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' };
|
const h = { 'Content-Type': type, 'Cache-Control': cache || 'public, max-age=60', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' };
|
||||||
if (/gzip/.test(req.headers['accept-encoding'] || '') && /text|xml|json|javascript/.test(type) && body.length > 1024) { h['Content-Encoding'] = 'gzip'; h.Vary = 'Accept-Encoding'; body = zlib.gzipSync(body); }
|
if (/gzip/.test(req.headers['accept-encoding'] || '') && /text|xml|json|javascript/.test(type) && body.length > 1024) { h['Content-Encoding'] = 'gzip'; h.Vary = 'Accept-Encoding'; body = zlib.gzipSync(body); }
|
||||||
@@ -178,19 +193,69 @@ function staticFile(req, res, p) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const server = http.createServer((req, res) => {
|
// the site assistant (2026-11-15): chatcore.js + kb.js + the network knowledge base (netkb.js); no admin editing on Stack POL
|
||||||
|
const chatbot = require('./chatbot');
|
||||||
|
const legal = require('./legal');
|
||||||
|
const chatJson = (res, code, obj, extra) => { res.writeHead(code, Object.assign({ 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }, extra || {})); res.end(JSON.stringify(obj)); };
|
||||||
|
// My Stack POL (Marty approved 2026-11-19): the network sign-in through the hub (networksso.js, the shared file; HUB_SSO=on with
|
||||||
|
// HUB_URL, HUB_SECRET, HUB_SITE=stackpol) and the signed-in area at /my (my.js). Nothing public needs it.
|
||||||
|
// InstantAdPay as the fallback (Marty 2026-11-20: "you click on it ... and it never goes anywhere"): with only the hub, a browser
|
||||||
|
// the hub has no sign-in for came straight back to /my. NETWORK_SSO_SECRET (the same as IAP's) turns on the pairwise path the other
|
||||||
|
// rebuilt sites use, and `from: { iap }` makes the hop name this site (&r=stackpol) so InstantAdPay signs the member in and sends
|
||||||
|
// them back here, not to its own peer LinkSpin.
|
||||||
|
const networksso = require('./networksso');
|
||||||
|
const my = require('./my');
|
||||||
|
const IAP_BASE = String(process.env.IAP_URL || 'https://instantadpay.com').trim().replace(/\/+$/, '');
|
||||||
|
my.init({ idx: () => IDX, PROGRAMS, BY_KEY, head, tail, esc, fmt, fmtInt, when, ledgerRows, tableHead, SITE, dataDir: DATA_DIR, qr: !!QR });
|
||||||
|
networksso.init({ self: 'stackpol', peer: 'iap', peerBase: () => IAP_BASE, from: { iap: () => IAP_BASE }, isProd: /^https:/.test(SITE), dataDir: DATA_DIR, defaultPath: '/my',
|
||||||
|
member: async req => { const s = my.session(req); return s ? { email: s.email, address: s.address } : null; },
|
||||||
|
accept: async email => (email ? { ok: true } : { fallback: 'no email' }), // the hub vouches for a network member; Stack POL keeps no accounts
|
||||||
|
signIn: async (email, req, v) => my.mintSession({ email, wallet: v && v.wallet, name: v && v.name }),
|
||||||
|
landing: to => to, signinPath: () => '/my?signin=none' });
|
||||||
|
const formBody = req => new Promise(resolve => { const ch = []; let n = 0; req.on('data', c => { n += c.length; if (n <= 4096) ch.push(c); }); req.on('end', () => resolve(new URLSearchParams(n <= 4096 ? Buffer.concat(ch).toString('utf8') : ''))); req.on('error', () => resolve(new URLSearchParams())); });
|
||||||
|
const sameSite = req => { const o = req.headers.origin; if (req.headers['sec-fetch-site'] === 'cross-site') return false; if (!o) return true; try { return new URL(o).origin === new URL(SITE).origin; } catch (e) { return false; } };
|
||||||
|
const seeOther = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(303, h); res.end(); };
|
||||||
|
async function myPost(req, res, p) {
|
||||||
|
if (!sameSite(req)) { res.writeHead(403, { 'Content-Type': 'text/plain' }); return res.end('Forbidden'); }
|
||||||
|
const b = await formBody(req); const s = my.session(req);
|
||||||
|
if (p === '/api/my/signout') {
|
||||||
|
const set = my.clearCookies().concat(networksso.offCookie());
|
||||||
|
if (s) { my.signOut(s.email); if (b.get('everywhere') === '1') await networksso.signOutEverywhere(s).catch(() => null); }
|
||||||
|
return seeOther(res, '/my?out=1', set);
|
||||||
|
}
|
||||||
|
if (!s) return seeOther(res, '/my');
|
||||||
|
const r = await my.doSwitch(s, b.get('on') === '1').catch(e => ({ ok: false, reason: e.message }));
|
||||||
|
if (!r.ok) console.error('[stackpol] my switch', r.reason);
|
||||||
|
return seeOther(res, '/my?sw=' + (r.ok ? 'ok' : 'err'));
|
||||||
|
}
|
||||||
|
const chatBody = req => new Promise(resolve => { const ch = []; let n = 0; req.on('data', c => { n += c.length; if (n <= 32768) ch.push(c); }); req.on('end', () => { try { resolve(n && n <= 32768 ? JSON.parse(Buffer.concat(ch).toString('utf8')) : {}); } catch (e) { resolve({}); } }); req.on('error', () => resolve({})); });
|
||||||
|
const server = http.createServer(async (req, res) => {
|
||||||
let u; try { u = new URL(req.url, SITE); } catch (e) { res.writeHead(400); return res.end(); }
|
let u; try { u = new URL(req.url, SITE); } catch (e) { res.writeHead(400); return res.end(); }
|
||||||
const p = decodeURIComponent(u.pathname);
|
let p; try { p = decodeURIComponent(u.pathname); } catch (e) { res.writeHead(400); return res.end(); }
|
||||||
if ((req.headers.host || '').startsWith('www.')) { res.writeHead(301, { Location: SITE + req.url }); return res.end(); }
|
if ((req.headers.host || '').startsWith('www.')) { res.writeHead(301, { Location: SITE + req.url }); return res.end(); }
|
||||||
try {
|
try {
|
||||||
|
// network sign-in + My Stack POL (2026-11-19)
|
||||||
|
if (req.method === 'GET' && await networksso.page(req, res, u)) return;
|
||||||
|
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
|
||||||
|
if (req.method === 'POST' && (p === '/api/my/signout' || p === '/api/my/switch')) return await myPost(req, res, p);
|
||||||
|
if ((p === '/my' || p === '/my/') && (req.method === 'GET' || req.method === 'HEAD')) {
|
||||||
|
const c = my.cookies(req);
|
||||||
|
if (!my.session(req) && !c['nsso.tried'] && !c['nsso.off'] && !u.searchParams.has('signin') && !u.searchParams.has('out') && !networksso.isBot(req) && (networksso.hubOn() || networksso.enabled())) return seeOther(res, '/sso/start?mode=check&to=%2Fmy'); // one silent check through the hub
|
||||||
|
const r = await my.render(req, { out: u.searchParams.has('out'), signin: u.searchParams.get('signin'), sw: u.searchParams.get('sw') });
|
||||||
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'X-Robots-Tag': 'noindex', ...(r.set.length ? { 'Set-Cookie': r.set } : {}) });
|
||||||
|
return res.end(req.method === 'HEAD' ? undefined : r.body);
|
||||||
|
}
|
||||||
if (p === '/api/ingest' && req.method === 'POST') {
|
if (p === '/api/ingest' && req.method === 'POST') {
|
||||||
if (!KEY || req.headers.authorization !== 'Bearer ' + KEY) { res.writeHead(401); return res.end(); }
|
if (!KEY || req.headers.authorization !== 'Bearer ' + KEY) { res.writeHead(401); return res.end(); }
|
||||||
const chunks = []; let n = 0;
|
const chunks = []; let n = 0;
|
||||||
req.on('data', c => { n += c.length; if (n > 8e6) req.destroy(); else chunks.push(c); });
|
req.on('data', c => { n += c.length; if (n > 8e6) req.destroy(); else chunks.push(c); });
|
||||||
req.on('end', () => { try { const j = JSON.parse(Buffer.concat(chunks).toString('utf8')); if (!j || !j.network || !j.programs) throw new Error('shape'); j.at = j.at || Date.now(); IDX = j; fs.writeFile(SNAP, JSON.stringify(j), () => {}); send(req, res, 200, 'application/json', JSON.stringify({ ok: true, at: j.at }), 'no-store'); } catch (e) { send(req, res, 400, 'application/json', JSON.stringify({ error: e.message }), 'no-store'); } });
|
req.on('end', () => { try { const j = JSON.parse(Buffer.concat(chunks).toString('utf8')); if (!j || !j.network || !j.programs) throw new Error('shape'); j.at = j.at || Date.now(); IDX = j; saveSnap(j); send(req, res, 200, 'application/json', JSON.stringify({ ok: true, at: j.at }), 'no-store'); } catch (e) { send(req, res, 400, 'application/json', JSON.stringify({ error: e.message }), 'no-store'); } });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) { chatbot.handle(req, res, p, u, { json: chatJson, readBody: chatBody, isAdmin: () => false })
|
||||||
|
.then(done => { if (!done) chatJson(res, 404, { error: 'Not found' }); }).catch(e => { console.error('[stackpol] chat', e.message); if (!res.headersSent) chatJson(res, 500, { error: 'Server error' }); }); return; }
|
||||||
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); return res.end(); }
|
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); return res.end(); }
|
||||||
|
if (p === '/api/network-deals' && req.method === 'GET') return require('./netdeals').handle(req, res, 'stackpol'); // Network Weekend ribbon (2026-11-17)
|
||||||
if (p === '/api/totals') return send(req, res, 200, 'application/json', JSON.stringify({ at: IDX ? IDX.at : null, network: net(), programs: (IDX && IDX.programs) || {} }), 'public, max-age=120');
|
if (p === '/api/totals') return send(req, res, 200, 'application/json', JSON.stringify({ at: IDX ? IDX.at : null, network: net(), programs: (IDX && IDX.programs) || {} }), 'public, max-age=120');
|
||||||
if (p === '/health') return send(req, res, 200, 'text/plain', 'ok', 'no-store');
|
if (p === '/health') return send(req, res, 200, 'text/plain', 'ok', 'no-store');
|
||||||
// ?ref=<username> of a Pro member (Marty 2026-11-09): every call to action credits them (join links, game links, program
|
// ?ref=<username> of a Pro member (Marty 2026-11-09): every call to action credits them (join links, game links, program
|
||||||
@@ -199,8 +264,10 @@ const server = http.createServer((req, res) => {
|
|||||||
const pc = refSt && refSt.pro ? { who: refName, st: refSt } : null;
|
const pc = refSt && refSt.pro ? { who: refName, st: refSt } : null;
|
||||||
const page = body => pc ? personalize(body, pc.who, pc.st) : body;
|
const page = body => pc ? personalize(body, pc.who, pc.st) : body;
|
||||||
const q = /^\/qr\/([a-z0-9_]{3,30})\.svg$/.exec(p);
|
const q = /^\/qr\/([a-z0-9_]{3,30})\.svg$/.exec(p);
|
||||||
if (q) { const st = IDX && IDX.stacks && IDX.stacks[q[1]]; if (!QR || !st || !st.pro) return html(req, res, 404, notFound()); return qrSvg(q[1]).then(svg => send(req, res, 200, 'image/svg+xml', svg, 'public, max-age=86400')).catch(() => html(req, res, 500, notFound())); }
|
if (q) { const st = IDX && IDX.stacks && IDX.stacks[q[1]]; if (!QR || !st || !st.pro || my.hiddenNow(q[1])) return html(req, res, 404, notFound()); return qrSvg(q[1]).then(svg => send(req, res, 200, 'image/svg+xml', svg, 'public, max-age=86400')).catch(() => html(req, res, 500, notFound())); }
|
||||||
if (p === '/') return html(req, res, 200, page(home()), 'public, max-age=120');
|
if (p === '/') return html(req, res, 200, page(home()), 'public, max-age=120');
|
||||||
|
if (legal.PATHS.includes(p)) return html(req, res, 200, page(legal.render(p)), 'public, max-age=3600'); // Terms / Privacy / Disclaimer (2026-11-17)
|
||||||
|
if (p === '/network' || p === '/how-it-works') return staticFile(req, res, '/network.html') || html(req, res, 404, notFound()); // the one-page network explainer (Marty 2026-11-17)
|
||||||
if (p === '/programs') return html(req, res, 200, page(programsPage()), 'public, max-age=300');
|
if (p === '/programs') return html(req, res, 200, page(programsPage()), 'public, max-age=300');
|
||||||
if (p === '/ledger') return html(req, res, 200, page(ledgerPage(u.searchParams.get('p'))), 'public, max-age=120');
|
if (p === '/ledger') return html(req, res, 200, page(ledgerPage(u.searchParams.get('p'))), 'public, max-age=120');
|
||||||
let m = /^\/earn\/([a-z0-9-]+)\/?$/.exec(p); if (m) return BY_SLUG[m[1]] ? html(req, res, 200, page(programPage(BY_SLUG[m[1]], pc && pc.who)), 'public, max-age=300') : html(req, res, 404, notFound());
|
let m = /^\/earn\/([a-z0-9-]+)\/?$/.exec(p); if (m) return BY_SLUG[m[1]] ? html(req, res, 200, page(programPage(BY_SLUG[m[1]], pc && pc.who)), 'public, max-age=300') : html(req, res, 404, notFound());
|
||||||
@@ -215,10 +282,20 @@ const server = http.createServer((req, res) => {
|
|||||||
m = /^\/@?([a-z0-9_]{3,30})\/?$/i.exec(p);
|
m = /^\/@?([a-z0-9_]{3,30})\/?$/i.exec(p);
|
||||||
if (m && !RESERVED.has(m[1].toLowerCase())) {
|
if (m && !RESERVED.has(m[1].toLowerCase())) {
|
||||||
const name = m[1].toLowerCase(), st = IDX && IDX.stacks && IDX.stacks[name];
|
const name = m[1].toLowerCase(), st = IDX && IDX.stacks && IDX.stacks[name];
|
||||||
if (st) return html(req, res, 200, st.pro ? personalize(stackPage(name, st), name, st) : stackPage(name, st), 'public, max-age=120');
|
if (st && !my.hiddenNow(name)) return html(req, res, 200, st.pro ? personalize(stackPage(name, st), name, st) : stackPage(name, st), 'public, max-age=120');
|
||||||
return html(req, res, 404, notFound('@' + name + ' has not switched on a Stack POL page yet. Members turn it on in InstantAdPay Promo tools.'));
|
return html(req, res, 404, notFound('@' + name + ' has not switched on a Stack POL page yet. Members turn it on in InstantAdPay Promo tools.'));
|
||||||
}
|
}
|
||||||
return html(req, res, 404, notFound());
|
return html(req, res, 404, notFound());
|
||||||
} catch (e) { console.error('[stackpol]', p, e); html(req, res, 500, notFound('Something went wrong on our side. Try again in a minute.'), 'no-store'); }
|
} catch (e) { console.error('[stackpol]', p, e); html(req, res, 500, notFound('Something went wrong on our side. Try again in a minute.'), 'no-store'); }
|
||||||
});
|
});
|
||||||
server.listen(PORT, () => console.log('Stack POL on :' + PORT + ' | snapshot ' + (IDX ? new Date(IDX.at).toISOString() : 'none yet') + ' | posts ' + blog.listPublished().length + ' | ingest ' + (KEY ? 'on' : 'OFF (no STACK_INGEST_KEY)')));
|
(async () => {
|
||||||
|
// MySQL first: never serve (or take a push into) an empty copy. A few tries for a database that is still starting.
|
||||||
|
for (let i = 1; ; i++) {
|
||||||
|
try { await docstore.init(); break; } catch (e) { console.error('docstore init try ' + i + ':', e.message); if (i >= 6) throw e; await new Promise(r => setTimeout(r, 5000)); }
|
||||||
|
}
|
||||||
|
process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); });
|
||||||
|
if (!docstore.isOn()) { try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (e) {} }
|
||||||
|
loadSnap();
|
||||||
|
chatbot.init(); // after docstore.init: kb.json and netkb-cache.json are MySQL documents
|
||||||
|
server.listen(PORT, () => console.log('Stack POL on :' + PORT + ' | snapshot ' + (IDX && IDX.at ? new Date(IDX.at).toISOString() : 'none yet') + ' | store ' + (docstore.isOn() ? 'MySQL' : 'files in ' + DATA_DIR) + ' | posts ' + blog.listPublished().length + ' | ingest ' + (KEY ? 'on' : 'OFF (no STACK_INGEST_KEY)')));
|
||||||
|
})().catch(e => { console.error('start failed:', e.message); process.exit(1); });
|
||||||
|
|||||||
+157
-16
@@ -9,7 +9,7 @@
|
|||||||
weekly prize transfers listed in VBB's prizes.json, each checked on chain (sent by the prize wallet, to that winner, succeeded).
|
weekly prize transfers listed in VBB's prizes.json, each checked on chain (sent by the prize wallet, to that winner, succeeded).
|
||||||
The scan position and the checked prize transfers are cached in /root/stackpol-indexer/vbb-chain.json.
|
The scan position and the checked prize transfers are cached in /root/stackpol-indexer/vbb-chain.json.
|
||||||
- ViralAdBlitz (2026-11-15): VABShop Paid (level 1-5 shares) and Claimed logs read from Polygon the same way, cached in
|
- ViralAdBlitz (2026-11-15): VABShop Paid (level 1-5 shares) and Claimed logs read from Polygon the same way, cached in
|
||||||
/root/stackpol-indexer/vab-chain.json. These two caches are the only files it writes.
|
/root/stackpol-indexer/vab-chain.json (ViralAdSource 2026-11-17: + resharer cut and pot rewards, vas-chain.json; YourProgramBuilder ypb-chain.json; Video App Income vai-chain.json, its own reader vai_rows). These caches are the only files it writes.
|
||||||
It builds one snapshot (network totals, per-program totals, last 7 days, latest 300 payouts, a stack per opted-in member) and
|
It builds one snapshot (network totals, per-program totals, last 7 days, latest 300 payouts, a stack per opted-in member) and
|
||||||
POSTs it to https://stackpol.com/api/ingest with the key in /root/.stackpol-ingest-key. Nothing is written anywhere else.
|
POSTs it to https://stackpol.com/api/ingest with the key in /root/.stackpol-ingest-key. Nothing is written anywhere else.
|
||||||
The ledger shows each payout's username (Marty 2026-11-09); only opted-in members get a public stack page.
|
The ledger shows each payout's username (Marty 2026-11-09); only opted-in members get a public stack page.
|
||||||
@@ -55,6 +55,34 @@ VAB_START = 97324419 # deploy block (the app's SHOP_START_BLOCK)
|
|||||||
VAB_HOUSE = {VAB_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0xf0b9deee7d9768b1d89d30f30e095def2a9cf1db'} # + company (Tangem), keeper
|
VAB_HOUSE = {VAB_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0xf0b9deee7d9768b1d89d30f30e095def2a9cf1db'} # + company (Tangem), keeper
|
||||||
VAB_TOPICS = {'0x2932f3f87f2814df80b5152511ba1fed7a451f5fb3703cd5dd406de6e684dfcc': 'Paid', # Paid(uint256,address,uint256,uint8,uint8)
|
VAB_TOPICS = {'0x2932f3f87f2814df80b5152511ba1fed7a451f5fb3703cd5dd406de6e684dfcc': 'Paid', # Paid(uint256,address,uint256,uint8,uint8)
|
||||||
'0xf7a40077ff7a04c7e61f6f26fb13774259ddf1b6bce9ecf26a8276cdd3992683': 'Claimed'} # Claimed(address,address,uint256)
|
'0xf7a40077ff7a04c7e61f6f26fb13774259ddf1b6bce9ecf26a8276cdd3992683': 'Claimed'} # Claimed(address,address,uint256)
|
||||||
|
# 5xYourTeam (2026-11-15): DraftPosition on Polygon, read-only; same Paid/Claimed events as VABShop. Member payouts = Paid level 1-5
|
||||||
|
# (sponsor 25% + levels 2-5 5%) + Claimed by a member. Level 0 = company, level 6 = the Best Coach prize pot wallet: not counted.
|
||||||
|
FX_SHOP = '0x83bb982d8b485de1a24e7d313765dda48d5abc74'
|
||||||
|
FX_START = 97363529 # deploy block (the app's SHOP_START_BLOCK)
|
||||||
|
DH_SHOP = '0xed07ad7150ecba62689cf2480729753f2fa44e90' # DownlineHydra HydraPro (2026-11-15): same Paid/Claimed events as VABShop
|
||||||
|
DH_START = 97364036 # deploy block (the app's SHOP_START_BLOCK)
|
||||||
|
DH_HOUSE = {DH_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0xf2f54cf271e8942ecb02176f408cc08a2a1d5bca'} # + company (Tangem), keeper
|
||||||
|
FX_HOUSE = {FX_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x818daeedefbb33a1988b8b4ac76a8c1dd6e82c60', '0x196cfceb0229ee4b2f20a3350a5ec32b93b72ba8'} # + company, keeper, prize pot
|
||||||
|
# ViralAdSource (2026-11-17): VASShop on Polygon, read-only; same Paid/Claimed events as VABShop plus the reward pot. Member payouts =
|
||||||
|
# Paid kind 1-5 (10% level shares) and kind 6 (the 20% resharer cut), RewardPaid (a new-member reward from the pot, unless its push
|
||||||
|
# failed in that tx: then the later Claimed counts it), and Claimed by a member. Kind 0 = company; contract, company, keeper and relay excluded.
|
||||||
|
# YourProgramBuilder (2026-11-17): YPBShop on Polygon, read-only; same Paid/Claimed events as VABShop. Member payouts = Paid kind 1-5
|
||||||
|
# (sponsor 20% + four levels 5%) + Claimed by a member (a failed push is owed and counted when claimed). Kind 0 = company; contract, company, keeper excluded.
|
||||||
|
# Video App Income (2026-11-20): VideoAppIncome contract on Polygon, read-only. Its Paid event names the receiving POSITION, not a
|
||||||
|
# wallet: Paid(uint32 buyerId, uint32 toId, uint8 kind, uint256 amount), kind 0 = the 30% sponsor share, 1-5 = the 8% matrix levels.
|
||||||
|
# Every Paid event is a member payout (company shares are a separate CompanySplit event and are not read). The position's wallet is
|
||||||
|
# looked up once with member(toId) when the log is first seen and stored with it. Cache: vai-chain.json.
|
||||||
|
VAI_SHOP = '0x0cff5d57933812b0fbac4d1138aa6b0ce5bac201'
|
||||||
|
VAI_START = 97669974 # deploy block
|
||||||
|
VAI_PAID = '0x1953924ceb3951f9e9936e1ed523923640c00c51daa472fb1ab22b924f42f564'
|
||||||
|
YPB_SHOP = '0x44a02c5ece4e6eb0edc406a8020f289956803e2a'
|
||||||
|
YPB_START = 97486277 # deploy block (the app's SHOP_START_BLOCK)
|
||||||
|
YPB_HOUSE = {YPB_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x5453a3973ed54cd2687c1675b73f1be5dacf26c4'} # + company (Tangem), keeper
|
||||||
|
VAS_SHOP = '0x7efe7b6ac1e666555f70d005e2cf1637804c4f24'
|
||||||
|
VAS_START = 97473297 # deploy block (the app's SHOP_START_BLOCK)
|
||||||
|
VAS_HOUSE = {VAS_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0xc76ca7dd499338299c2b4bde2dc5c61bf2a97aae', '0x2fe1afedc6ba13fea4e820e7f4c67e6ea40dd9d6'} # + company (Tangem), keeper, relay
|
||||||
|
VAS_TOPICS = {'0xd1c8a663b78b68951e43495fb4824e0454105c7043f5fa8d570d140b5a73d48e': 'RewardPaid', # RewardPaid(uint256,address,uint256,uint256,uint256)
|
||||||
|
'0x8518389ba90468cb21477807ccd9bf28d0f41f2b3affa2f77a779786efa2cc04': 'PaymentFailed'} # PaymentFailed(uint256,address,uint256,uint8,uint8)
|
||||||
VBB_CONFIRM = 30 # blocks behind head
|
VBB_CONFIRM = 30 # blocks behind head
|
||||||
VBB_SPAN = 1000 # blocks per eth_getLogs (public RPC limit)
|
VBB_SPAN = 1000 # blocks per eth_getLogs (public RPC limit)
|
||||||
VBB_MAX_SPANS = 400 # per run; a long gap catches up over a few runs
|
VBB_MAX_SPANS = 400 # per run; a long gap catches up over a few runs
|
||||||
@@ -199,11 +227,14 @@ def vbb_rows(dry=False):
|
|||||||
last, len(logs), allwei / 1e18, len(prizes), len(rows), sum(r['pol'] for r in rows), ('; ' + note) if note else '')
|
last, len(logs), allwei / 1e18, len(prizes), len(rows), sum(r['pol'] for r in rows), ('; ' + note) if note else '')
|
||||||
|
|
||||||
|
|
||||||
def vab_rows(dry=False):
|
def vab_rows(dry=False, k='vab', shop=VAB_SHOP, start=VAB_START, house=VAB_HOUSE, cachefile='vab-chain.json', maxlevel=5, extra=None):
|
||||||
"""ViralAdBlitz member payouts, read-only on chain (same scan as VBB, no prize wallet). Returns (rows, note)."""
|
"""ViralAdBlitz (and, same events, 5xYourTeam, DownlineHydra, ViralAdSource) member payouts, read-only on chain (same scan as VBB,
|
||||||
cpath = os.path.join(HERE, 'vab-chain.json')
|
no prize wallet). maxlevel = highest Paid level/kind counted (ViralAdSource 6 = resharer); extra = more topics (ViralAdSource
|
||||||
|
RewardPaid + PaymentFailed). Returns (rows, note)."""
|
||||||
|
topics = dict(VAB_TOPICS, **(extra or {}))
|
||||||
|
cpath = os.path.join(HERE, cachefile)
|
||||||
cache = load(cpath, {}) or {}
|
cache = load(cpath, {}) or {}
|
||||||
last = int(cache.get('lastBlock') or VAB_START - 1)
|
last = int(cache.get('lastBlock') or start - 1)
|
||||||
logs = cache.get('logs') or [] # every Paid/Claimed log seen (all levels), so the counting rule can change without a rescan
|
logs = cache.get('logs') or [] # every Paid/Claimed log seen (all levels), so the counting rule can change without a rescan
|
||||||
bts = {}
|
bts = {}
|
||||||
|
|
||||||
@@ -219,16 +250,18 @@ def vab_rows(dry=False):
|
|||||||
spans = 0
|
spans = 0
|
||||||
while last < head and spans < VBB_MAX_SPANS:
|
while last < head and spans < VBB_MAX_SPANS:
|
||||||
frm, to = last + 1, min(head, last + VBB_SPAN)
|
frm, to = last + 1, min(head, last + VBB_SPAN)
|
||||||
for l in rpc('eth_getLogs', [{'address': VAB_SHOP, 'topics': [list(VAB_TOPICS)], 'fromBlock': hex(frm), 'toBlock': hex(to)}]) or []:
|
for l in rpc('eth_getLogs', [{'address': shop, 'topics': [list(topics)], 'fromBlock': hex(frm), 'toBlock': hex(to)}]) or []:
|
||||||
if l.get('removed') or str(l.get('address', '')).lower() != VAB_SHOP:
|
if l.get('removed') or str(l.get('address', '')).lower() != shop:
|
||||||
continue
|
continue
|
||||||
kind, t, data = VAB_TOPICS.get(l['topics'][0]), l['topics'], l.get('data') or '0x'
|
kind, t, data = topics.get(l['topics'][0]), l['topics'], l.get('data') or '0x'
|
||||||
key = (l['transactionHash'].lower(), int(l['logIndex'], 16))
|
key = (l['transactionHash'].lower(), int(l['logIndex'], 16))
|
||||||
if not kind or key in seen:
|
if not kind or key in seen:
|
||||||
continue
|
continue
|
||||||
n = int(l['blockNumber'], 16)
|
n = int(l['blockNumber'], 16)
|
||||||
if kind == 'Paid': # data: amount, level, depth
|
if kind in ('Paid', 'PaymentFailed'): # data: amount, level, depth
|
||||||
x = {'ev': 'Paid', 'to': '0x' + t[2][-40:].lower(), 'wei': str(int(data[2:66], 16)), 'level': int(data[66:130], 16), 'depth': int(data[130:194], 16)}
|
x = {'ev': kind, 'to': '0x' + t[2][-40:].lower(), 'wei': str(int(data[2:66], 16)), 'level': int(data[66:130], 16), 'depth': int(data[130:194], 16)}
|
||||||
|
elif kind == 'RewardPaid': # topics: nonce, to; data: usdCents, weiPaid, day
|
||||||
|
x = {'ev': 'RewardPaid', 'to': '0x' + t[2][-40:].lower(), 'wei': str(int(data[66:130], 16)), 'cents': int(data[2:66], 16)}
|
||||||
else:
|
else:
|
||||||
x = {'ev': 'Claimed', 'who': '0x' + t[1][-40:].lower(), 'to': '0x' + t[2][-40:].lower(), 'wei': str(int(data[2:66], 16))}
|
x = {'ev': 'Claimed', 'who': '0x' + t[1][-40:].lower(), 'to': '0x' + t[2][-40:].lower(), 'wei': str(int(data[2:66], 16))}
|
||||||
x.update({'tx': key[0], 'li': key[1], 'block': n, 'ts': btime(n)})
|
x.update({'tx': key[0], 'li': key[1], 'block': n, 'ts': btime(n)})
|
||||||
@@ -246,15 +279,70 @@ def vab_rows(dry=False):
|
|||||||
json.dump({'lastBlock': last, 'logs': logs, 'at': int(time.time())}, f)
|
json.dump({'lastBlock': last, 'logs': logs, 'at': int(time.time())}, f)
|
||||||
os.replace(tmp, cpath)
|
os.replace(tmp, cpath)
|
||||||
rows = []
|
rows = []
|
||||||
|
failed = {(x['tx'], x['to']) for x in logs if x['ev'] == 'PaymentFailed'} # a reward whose push failed is counted when Claimed
|
||||||
for x in logs:
|
for x in logs:
|
||||||
member = (x['ev'] == 'Paid' and 1 <= int(x.get('level') or 0) <= 5) or (x['ev'] == 'Claimed' and x.get('who') not in VAB_HOUSE)
|
member = (x['ev'] == 'Paid' and 1 <= int(x.get('level') or 0) <= maxlevel) or (x['ev'] == 'Claimed' and x.get('who') not in house) or (x['ev'] == 'RewardPaid' and (x['tx'], x['to']) not in failed)
|
||||||
if member and x['to'] not in VAB_HOUSE and int(x['wei']) > 0:
|
if member and x['to'] not in house and int(x['wei']) > 0:
|
||||||
rows.append({'k': 'vab', 'pol': int(x['wei']) / 1e18, 'tx': x['tx'], 'ts': ms(x['ts']), 'w': x['to'], 'gu': ''})
|
rows.append({'k': k, 'pol': int(x['wei']) / 1e18, 'tx': x['tx'], 'ts': ms(x['ts']), 'w': x['to'], 'gu': ''})
|
||||||
allwei = sum(int(x['wei']) for x in logs if x['ev'] == 'Paid')
|
allwei = sum(int(x['wei']) for x in logs if x['ev'] == 'Paid')
|
||||||
return rows, 'vab: scanned to block %d, %d contract logs (%.4f POL in all Paid events), %d member payouts %.4f POL%s' % (
|
return rows, k + ': scanned to block %d, %d contract logs (%.4f POL in all Paid events), %d member payouts %.4f POL%s' % (
|
||||||
last, len(logs), allwei / 1e18, len(rows), sum(r['pol'] for r in rows), ('; ' + note) if note else '')
|
last, len(logs), allwei / 1e18, len(rows), sum(r['pol'] for r in rows), ('; ' + note) if note else '')
|
||||||
|
|
||||||
|
|
||||||
|
def vai_rows(dry=False):
|
||||||
|
"""Video App Income member payouts (sponsor 30% + five matrix levels 8%), read-only on chain. Returns (rows, note)."""
|
||||||
|
cpath = os.path.join(HERE, 'vai-chain.json')
|
||||||
|
cache = load(cpath, {}) or {}
|
||||||
|
last = int(cache.get('lastBlock') or VAI_START - 1)
|
||||||
|
logs = cache.get('logs') or []
|
||||||
|
bts, accts = {}, {}
|
||||||
|
|
||||||
|
def btime(n):
|
||||||
|
if n not in bts:
|
||||||
|
b = rpc('eth_getBlockByNumber', [hex(n), False])
|
||||||
|
bts[n] = int(b['timestamp'], 16) if b and b.get('timestamp') else 0
|
||||||
|
return bts[n]
|
||||||
|
|
||||||
|
def account(pid):
|
||||||
|
if pid not in accts:
|
||||||
|
r = rpc('eth_call', [{'to': VAI_SHOP, 'data': '0xbfca75d1' + '%064x' % pid}, 'latest']) or '0x' # member(uint32): first word = wallet
|
||||||
|
accts[pid] = '0x' + r[2:66][-40:].lower() if len(r) >= 66 else ''
|
||||||
|
return accts[pid]
|
||||||
|
note = ''
|
||||||
|
try:
|
||||||
|
head = int(rpc('eth_blockNumber', []), 16) - VBB_CONFIRM
|
||||||
|
seen = {(x['tx'], x['li']) for x in logs}
|
||||||
|
spans = 0
|
||||||
|
while last < head and spans < VBB_MAX_SPANS:
|
||||||
|
frm, to = last + 1, min(head, last + VBB_SPAN)
|
||||||
|
for l in rpc('eth_getLogs', [{'address': VAI_SHOP, 'topics': [VAI_PAID], 'fromBlock': hex(frm), 'toBlock': hex(to)}]) or []:
|
||||||
|
if l.get('removed') or str(l.get('address', '')).lower() != VAI_SHOP:
|
||||||
|
continue
|
||||||
|
t, data = l['topics'], l.get('data') or '0x'
|
||||||
|
key = (l['transactionHash'].lower(), int(l['logIndex'], 16))
|
||||||
|
if key in seen or len(t) < 3:
|
||||||
|
continue
|
||||||
|
n, pid = int(l['blockNumber'], 16), int(t[2], 16)
|
||||||
|
w = account(pid)
|
||||||
|
if not w or int(w, 16) == 0:
|
||||||
|
raise RuntimeError('no wallet for position %d' % pid) # stop before this span is marked done; retried next run
|
||||||
|
logs.append({'ev': 'Paid', 'pos': pid, 'to': w, 'kind': int(data[2:66], 16), 'wei': str(int(data[66:130], 16)), 'tx': key[0], 'li': key[1], 'block': n, 'ts': btime(n)})
|
||||||
|
seen.add(key)
|
||||||
|
last = to
|
||||||
|
spans += 1
|
||||||
|
if last < head:
|
||||||
|
note = 'catching up, %d blocks to go' % (head - last)
|
||||||
|
except Exception as e:
|
||||||
|
note = 'chain read failed (kept the cached logs): %s' % e
|
||||||
|
if not dry:
|
||||||
|
tmp = cpath + '.tmp'
|
||||||
|
with open(tmp, 'w', encoding='utf-8', newline='\n') as f:
|
||||||
|
json.dump({'lastBlock': last, 'logs': logs, 'at': int(time.time())}, f)
|
||||||
|
os.replace(tmp, cpath)
|
||||||
|
rows = [{'k': 'vai', 'pol': int(x['wei']) / 1e18, 'tx': x['tx'], 'ts': ms(x['ts']), 'w': x['to'], 'gu': ''} for x in logs if int(x['wei']) > 0 and x['to'] != VAI_SHOP]
|
||||||
|
return rows, 'vai: scanned to block %d, %d Paid logs, %d member payouts %.4f POL%s' % (last, len(logs), len(rows), sum(r['pol'] for r in rows), ('; ' + note) if note else '')
|
||||||
|
|
||||||
|
|
||||||
def iap_wallet_users():
|
def iap_wallet_users():
|
||||||
"""{address_lower: username} from IAP accounts + positions, via the IAP container (its DATABASE_URL never leaves it)."""
|
"""{address_lower: username} from IAP accounts + positions, via the IAP container (its DATABASE_URL never leaves it)."""
|
||||||
c = subprocess.run(['docker', 'ps', '--format', '{{.Names}}'], capture_output=True, text=True).stdout.split()
|
c = subprocess.run(['docker', 'ps', '--format', '{{.Names}}'], capture_output=True, text=True).stdout.split()
|
||||||
@@ -340,6 +428,21 @@ def main():
|
|||||||
ar, anote = vab_rows(dry)
|
ar, anote = vab_rows(dry)
|
||||||
rows += ar
|
rows += ar
|
||||||
print(anote)
|
print(anote)
|
||||||
|
fr, fnote = vab_rows(dry, 'fx', FX_SHOP, FX_START, FX_HOUSE, 'fx-chain.json')
|
||||||
|
rows += fr
|
||||||
|
print(fnote)
|
||||||
|
hr, hnote = vab_rows(dry, 'dh', DH_SHOP, DH_START, DH_HOUSE, 'dh-chain.json')
|
||||||
|
rows += hr
|
||||||
|
print(hnote)
|
||||||
|
sr, snote = vab_rows(dry, 'vas', VAS_SHOP, VAS_START, VAS_HOUSE, 'vas-chain.json', 6, VAS_TOPICS)
|
||||||
|
rows += sr
|
||||||
|
print(snote)
|
||||||
|
yr, ynote = vab_rows(dry, 'ypb', YPB_SHOP, YPB_START, YPB_HOUSE, 'ypb-chain.json')
|
||||||
|
rows += yr
|
||||||
|
print(ynote)
|
||||||
|
ir, inote = vai_rows(dry)
|
||||||
|
rows += ir
|
||||||
|
print(inote)
|
||||||
# wallet -> username
|
# wallet -> username
|
||||||
wu = iap_wallet_users()
|
wu = iap_wallet_users()
|
||||||
lsd = voldir(CHAINS['ls'])
|
lsd = voldir(CHAINS['ls'])
|
||||||
@@ -406,10 +509,48 @@ def main():
|
|||||||
spins = [{'code': x['code'], 'size': x.get('size', ''), 'name': str(x.get('name') or '')[:60]} for x in bs
|
spins = [{'code': x['code'], 'size': x.get('size', ''), 'name': str(x.get('name') or '')[:60]} for x in bs
|
||||||
if str(x.get('owner', '')).lower() in mine and not x.get('paused') and any(b.get('active', True) for b in x.get('banners') or [])]
|
if str(x.get('owner', '')).lower() in mine and not x.get('paused') and any(b.get('active', True) for b in x.get('banners') or [])]
|
||||||
links = [{'code': x['code'], 'name': str(x.get('name') or '')[:60]} for x in rt
|
links = [{'code': x['code'], 'name': str(x.get('name') or '')[:60]} for x in rt
|
||||||
if str(x.get('owner', '')).lower() in mine and not x.get('paused') and any(d.get('active', True) for d in x.get('destinations') or [])]
|
if not x.get('kind') and str(x.get('owner', '')).lower() in mine and not x.get('paused') and any(d.get('active', True) for d in x.get('destinations') or [])]
|
||||||
stacks[un]['pro'] = {'spins': spins[:40], 'links': links[:20]}
|
stacks[un]['pro'] = {'spins': spins[:40], 'links': links[:20]}
|
||||||
|
# Video Spins (Marty 2026-11-23): a LinkSpin spin link of kind 'video' rotates the member's Social Tube video pages. The page shows
|
||||||
|
# ONE: the Video Spin with the most live videos, newest on a tie (play counts are not in this document). Posters come from Social Tube.
|
||||||
|
vs = []
|
||||||
|
for x in rt:
|
||||||
|
if x.get('kind') != 'video' or str(x.get('owner', '')).lower() not in mine or x.get('paused'):
|
||||||
|
continue
|
||||||
|
live = [d for d in (x.get('destinations') or []) if d.get('active', True) and not d.get('autoPaused')]
|
||||||
|
if live:
|
||||||
|
vs.append((len(live), x.get('created') or 0, x, live))
|
||||||
|
if vs:
|
||||||
|
n, _, x, live = max(vs, key=lambda t: (t[0], t[1]))
|
||||||
|
posters = [{'poster': str(d.get('poster'))[:200], 'label': str(d.get('label') or '')[:80]} for d in live
|
||||||
|
if str(d.get('poster') or '').startswith('https://socialtube.club/')][:3]
|
||||||
|
stacks[un]['pro']['video'] = {'code': x['code'], 'name': str(x.get('name') or '')[:60], 'count': n, 'posters': posters}
|
||||||
|
# My Stack POL (Marty 2026-11-19): the signed-in member area. Every paid member's own rows (newest first, up to 500), their totals
|
||||||
|
# (the same sums as their public stack), the wallets mapped to them, whether their page is on, plus IAP's explicit switches and Pro
|
||||||
|
# owners. Read only by /my for the member who is signed in; never rendered on a public page, so a switched-off member stays hidden.
|
||||||
|
wl = {}
|
||||||
|
for a, un in wu.items():
|
||||||
|
if a and un:
|
||||||
|
wl.setdefault(str(un).lower(), set()).add(str(a).lower())
|
||||||
|
members = {}
|
||||||
|
for r in rows:
|
||||||
|
un = r['u']
|
||||||
|
if not un:
|
||||||
|
continue
|
||||||
|
m = members.setdefault(un, {'total': 0.0, 'payments': 0, 'since': r['ts'], 'byProg': {}, 'rows': []})
|
||||||
|
m['total'] += r['pol']; m['payments'] += 1; m['since'] = min(m['since'], r['ts'])
|
||||||
|
b = m['byProg'].setdefault(r['k'], {'pol': 0.0, 'payments': 0}); b['pol'] += r['pol']; b['payments'] += 1
|
||||||
|
if len(m['rows']) < 500:
|
||||||
|
m['rows'].append({'k': r['k'], 'pol': round(r['pol'], 4), 'tx': r['tx'], 'ts': r['ts']})
|
||||||
|
for un, m in members.items():
|
||||||
|
m['total'] = round(m['total'], 4)
|
||||||
|
m['byProg'] = {k: {'pol': round(v['pol'], 4), 'payments': v['payments']} for k, v in m['byProg'].items()}
|
||||||
|
m['wallets'] = sorted(wl.get(un, set()))
|
||||||
|
m['page'] = un in stacks
|
||||||
|
switch = {str(un).lower(): bool(on) for un, on in (so.get('users', {}) if isinstance(so, dict) else {}).items()}
|
||||||
|
my = {'members': members, 'switch': switch, 'pro': sorted(pro)}
|
||||||
snap = {'v': 1, 'at': now, 'network': {'pol': round(sum(r['pol'] for r in rows), 4), 'payments': len(rows), 'wallets': len(wallets - {''})},
|
snap = {'v': 1, 'at': now, 'network': {'pol': round(sum(r['pol'] for r in rows), 4), 'payments': len(rows), 'wallets': len(wallets - {''})},
|
||||||
'last7': {'pol': round(sum(r['pol'] for r in l7), 4), 'payments': len(l7)}, 'programs': programs, 'recent': recent, 'progRecent': prog_recent, 'stacks': stacks}
|
'last7': {'pol': round(sum(r['pol'] for r in l7), 4), 'payments': len(l7)}, 'programs': programs, 'recent': recent, 'progRecent': prog_recent, 'stacks': stacks, 'my': my}
|
||||||
print('network %.2f POL, %d payments, %d wallets | last7 %.2f | stacks %s' % (snap['network']['pol'], snap['network']['payments'], snap['network']['wallets'], snap['last7']['pol'], ','.join(stacks) or '-'))
|
print('network %.2f POL, %d payments, %d wallets | last7 %.2f | stacks %s' % (snap['network']['pol'], snap['network']['payments'], snap['network']['wallets'], snap['last7']['pol'], ','.join(stacks) or '-'))
|
||||||
for k, v in sorted(programs.items(), key=lambda x: -x[1]['pol']):
|
for k, v in sorted(programs.items(), key=lambda x: -x[1]['pol']):
|
||||||
print(' %-4s %10.2f POL %6d payments %5d wallets' % (k, v['pol'], v['payments'], v['wallets']))
|
print(' %-4s %10.2f POL %6d payments %5d wallets' % (k, v['pol'], v['payments'], v['wallets']))
|
||||||
|
|||||||
Reference in New Issue
Block a user