YourProgramBuilder, the Seed Bed (Marty 2026-11-17: "keep fleshing it out"): STAGING build
Plant a program free (referral link with {id}, link check green / yellow / red, daily recheck, reports), members save their
referral IDs in its packet, a sponsor-first link (member page / ?r= / the hub sponsor line, then the planter), the sprout meter
to REVIEW_SAVES (DEFAULT 25) -> Marty's review queue -> approved packets exported for the CTB builder / DownlineHydra wild heads
with every saved ID. Dormant old programs confirmed by their owner, old-link redirects (oldrefs), Spotlight on YPBShop (NOT
deployed; DEFAULT $10 / 1,000 views, 20/5/5/5/5, company 60), verified views with Spotlight delivery, trust pack (ledger,
contract, toasts, Telegram card, terms / disclaimer / privacy, TrustClickz only), network footer row, chatbot, promo kit,
Guides, PolHunter slot, LinkSpin tracked-link and zone hooks, AI writer through the hub. Seed-catalog look from the approved
mockup. Tests: qa/unit.test.cjs 33/33, qa/e2e.mjs 121/121 on a local anvil chain.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
data
|
||||
qa/out
|
||||
.git
|
||||
.env
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
data/
|
||||
*.log
|
||||
qa/out/
|
||||
.env
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --no-audit --no-fund
|
||||
COPY . .
|
||||
RUN mkdir -p /app/data
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
EXPOSE 3000
|
||||
# a container that cannot boot is never swapped in (2026-10-08 rule)
|
||||
HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=4 CMD wget -qO- http://127.0.0.1:3000/health >/dev/null || exit 1
|
||||
CMD ["node","server.js"]
|
||||
@@ -0,0 +1,44 @@
|
||||
# YourProgramBuilder: the Seed Bed
|
||||
|
||||
yourprogrambuilder.com rebuild (Marty 2026-11-17: "I like the approach on YourProgramBuilder. Go ahead and keep fleshing it out more.").
|
||||
"Bring your program. The network grows it."
|
||||
|
||||
- **Plant**: a network member plants one program free (name, referral link with `{id}`, their own ID, what it is, free or paid to
|
||||
join, optional contract address). The link check (`linkcheck.js`): green shows, yellow waits for Marty's queue, red is refused;
|
||||
every live packet is rechecked daily; `REPORT_HOLD` member reports send it back to the queue. Programs already in the CTB builder
|
||||
(`seed/builder.seed.json`, the DownlineHydra snapshot) and network sites are refused.
|
||||
- **Sprout**: members save their referral ID in any packet (a whole pasted link works). A visitor through a member (their page
|
||||
`/<username>`, or `?r=`) sees that member's link first; a signed-in member sees the nearest saved ID up their hub sponsor line;
|
||||
then the planter's ID (`seedbed.sponsorLink`, DownlineHydra's wild-head rule).
|
||||
- **Transplant**: at `REVIEW_SAVES` (DEFAULT 25) saves from distinct confirmed network members (the planter counts as one) the packet
|
||||
enters Marty's review queue (`/admin`). Approved packets are exported by `GET /api/admin/export` in the CTB builder's form
|
||||
(`{affiliateid}`) with every saved ID (username, hub id, ID). This site never writes to another site: the add on CTB /
|
||||
DownlineHydra is done there.
|
||||
- **Spotlight** (DEFAULTS, the decision pack is unanswered): one-time $10 = 1,000 guaranteed verified views for one packet in the
|
||||
Spotlight places (top row of the bed, the strip on packet and member pages), on YPBShop (`../contracts`, NOT deployed): 20% sponsor,
|
||||
5% each levels 2 to 5, 60% company, immutable split, keeper-signed orders, no owner withdraw, 48-hour SKU timelock. Members earn
|
||||
free: anyone in the hub line with a linked wallet is paid (compression in `/api/my/order`).
|
||||
- **Old site**: old links (`/?<old>`, `index.php`, `splashpg.php`, `lcp.php`, `join.php`, the old member pages) 301 through
|
||||
`oldrefs.json` (`POST /api/admin/oldrefs`). Old member programs come in as dormant packets (`POST /api/admin/dormant`, hub id
|
||||
required) that only their owner can confirm with a `{id}` link.
|
||||
|
||||
Network rails: hub membership + usernames (`hubpeople.js`, `hubline.js`), network sign-in (`networksso.js`, the site only needs to
|
||||
be in the hub's `HUB_SSO_SITES`), hub events (`hubevents.js`), contract binds report (`hubreport.js`, `HUB_ENABLED`), trust pack
|
||||
(`/ledger`, `/contract`, toasts, Telegram card per Spotlight in `proof.js`, terms / disclaimer / privacy naming TrustClickz only),
|
||||
network footer row from the hub (`netsites.js`), chatbot (`chatbot.js` on the shared `chatcore` / `kb` / `netkb`), promo kit
|
||||
(`/promote`, `/api/promo-kit`), Guides (`/guides/*`), PolHunter embed slot (front page steps), LinkSpin tracked saved links
|
||||
(`lstrack.js`, `LS_TRACK=1` + a LinkSpin `ypb` partner) and ad zones (`LS_ZONES`), the AI writer through the hub
|
||||
(`hubadwriter.js`), the DownlineHydra "New in the network" feed (`/api/spotlight-feed`, not wired on DownlineHydra yet).
|
||||
MySQL is the store (`docstore.js`, `DOCSTORE_URL`); files only for local tests.
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
node qa/unit.test.cjs # 33: link-check colours, planting rules, ID cleaning
|
||||
node qa/e2e.mjs # 121: the whole product on a local anvil chain with the real YPBShop (needs forge build in ../contracts)
|
||||
```
|
||||
|
||||
## Staging
|
||||
|
||||
ypb.saasy.top (Coolify, own MySQL). STAGING=1, PAYOUTS=0, HUB_JOIN=0, HUB_ENABLED=0, no mail, no contract, no Telegram.
|
||||
Art: `python tools/pages.py` writes the pages; `node tools/art.mjs` renders the mark, OG image, proof cards and the promo kit.
|
||||
@@ -0,0 +1,84 @@
|
||||
// YourProgramBuilder's site assistant (the network pattern, 2026-11-15): what it knows. The engine is chatcore.js (the same on every
|
||||
// rebuilt site); retrieval also covers the other network sites through the hub (netkb.js), this site's entries first.
|
||||
// Every fact below was checked against this repo on KNOWLEDGE_DATE: config.js (threshold, Spotlight, split: DEFAULTS until Marty
|
||||
// answers the decision pack), seedbed.js (planting rules, sprout meter, review, sponsor-first link, export), linkcheck.js (green /
|
||||
// yellow / red), wire.js (verified views, Spotlight delivery), shop.js + ../contracts (YPBShop, not deployed), server.js, public pages.
|
||||
// HOUSE RULE: when a feature changes, update CANNED and FACTS in the same commit and bump KNOWLEDGE_DATE.
|
||||
// Plain words, no em dashes, never a promise of income, "SafePal or any other crypto wallet", never RM Circle, no caps shown.
|
||||
'use strict';
|
||||
const core = require('./chatcore');
|
||||
const C = require('./config').get();
|
||||
|
||||
const KNOWLEDGE_DATE = '2026-11-17';
|
||||
const URL_ = 'https://' + C.site;
|
||||
const SUPPORT = 'https://instantadpay.com/support';
|
||||
const SP = C.spotlight, LV = C.split.levelBps;
|
||||
const pct = bps => (bps / 100).toFixed(bps % 100 ? 1 : 0) + '%';
|
||||
const company = () => pct(10000 - LV.reduce((t, x) => t + x, 0));
|
||||
const levelsTxt = () => pct(LV[0]) + ' to the buyer\'s sponsor and ' + LV.slice(1).map(pct).join(' / ') + ' to levels 2 to ' + LV.length;
|
||||
const NOT_INCOME = 'YourProgramBuilder is a directory of programs, not an income opportunity: nothing is promised.';
|
||||
|
||||
const CANNED = [
|
||||
{ id: 'support', title: 'Talk to a person, or a problem with my account', q: ['How do I contact support?', 'My packet is missing', 'I need a real person'], tags: ['support', 'help', 'ticket', 'problem'],
|
||||
re: core.SUPPORT_RE, handoff: true,
|
||||
a: 'Network support handles every network site, YourProgramBuilder included: open ' + SUPPORT + ', say it is about YourProgramBuilder, and include the packet number (it is on the packet, for example No. 018) and your wallet address if it is about a Spotlight.' },
|
||||
{ id: 'about', title: 'What is YourProgramBuilder?', q: ['What is YourProgramBuilder?', 'What is the Seed Bed?', 'How does it work?'], tags: ['yourprogrambuilder', 'ypb', 'seed bed', 'overview'],
|
||||
re: /(what('s| is) (your ?program ?builder|ypb|the seed bed|this (site|place))|how does (your ?program ?builder|ypb|the seed bed|this site|it) work|explain (your ?program ?builder|this))/i,
|
||||
a: 'YourProgramBuilder is the Seed Bed: any network member can plant an outside program (its name, its referral link with {id} where the ID goes, what it is and what it costs to join), and members across the network save their own referral ID in it. When ' + C.reviewSaves + ' members have saved an ID, the packet goes to review for the Crypto Team Build Network builder, and every saved ID moves with it. The full guide: ' + URL_ + '/guides/how-it-works' },
|
||||
{ id: 'plant', title: 'How to plant a program', q: ['How do I add a program?', 'How do I plant a program?', 'Can I add my own program?'], tags: ['plant', 'add program', 'submit'],
|
||||
re: /(\bplant\b|add (a |my )?(program|site|opportunity)|submit (a |my )?program|list (my|a) program)/i,
|
||||
a: 'Sign in with your network account at ' + URL_ + '/my, then use Plant a program. You give the program a name, paste your referral link and replace your ID in it with {id} (for example https://program.example/?ref={id}), type your own ID, say in a sentence what it is and whether it is free or paid to join, and add the contract address if it is a crypto program. Planting is free: one packet per member at a time. Programs already in the Crypto Team Build Network builder are not planted again; save your ID for those on DownlineHydra.' },
|
||||
{ id: 'save', title: 'Saving my ID in a packet', q: ['How do I save my ID?', 'What does Save my ID do?', 'Who sees my link?'], tags: ['save', 'referral id', 'my link'],
|
||||
re: /(save (my )?(id|link|referral)|saved ids?|my (referral )?id\b|whose link|who sees my link)/i,
|
||||
a: 'Open a packet and tap Save my ID, then type your referral ID for that program (or paste your whole referral link: the ID is taken from it). Visitors who come through you (your member page ' + URL_ + '/<your username>) see your link first. Signed-in members see the link of the nearest person above them in their sponsor line who saved an ID, then the planter\'s. You can change or remove your ID any time.' },
|
||||
{ id: 'review', title: 'What happens at ' + C.reviewSaves + ' saves', q: ['What happens at ' + C.reviewSaves + ' saves?', 'What is a transplant?', 'How does a program get into the builder?'], tags: ['review', 'transplant', 'builder', 'threshold'],
|
||||
re: /(transplant|review queue|ready for review|get (it |my program )?(into|in) the builder|\b\d+ saves|sprout meter)/i,
|
||||
a: 'Each packet has a sprout meter: saved IDs from distinct confirmed network members, out of ' + C.reviewSaves + ' (the planter\'s own ID counts as one). At ' + C.reviewSaves + ' the packet goes to Marty\'s review queue and keeps sprouting while it waits. If he approves it, it is added to the Crypto Team Build Network builder, and so to DownlineHydra\'s wild heads, with every saved ID carried over. Reaching ' + C.reviewSaves + ' does not guarantee approval.' },
|
||||
{ id: 'check', title: 'The link check', q: ['Why is my packet not showing?', 'What is the link check?', 'My packet is held'], tags: ['link check', 'held', 'green', 'yellow', 'red'],
|
||||
re: /(link check|not showing|held|on hold|yellow|blocked|why (is|was) my (packet|program))/i,
|
||||
a: 'Every planted link is checked before it shows and again every day. Green shows in the Seed Bed straight away. Yellow (for example a redirect to another site, plain http, or words that need a look) waits for Marty\'s queue. Red (the link does not load, or it is a shortener or a private address) is refused. Members can report a packet; a few reports send it back to the queue.' },
|
||||
{ id: 'spotlight', title: 'What a Spotlight is', q: ['What is a Spotlight?', 'How much is a Spotlight?', 'Where does the Spotlight money go?'], tags: ['spotlight', 'price', 'split'],
|
||||
re: /\bspotlight/i,
|
||||
a: 'A Spotlight ($' + SP.usd + ', one-time, never a subscription) gives one packet ' + SP.views.toLocaleString('en-US') + ' guaranteed verified views in the Spotlight places: the top row of the Seed Bed and the Spotlight strip on packet and member pages. Paid in POL with SafePal or any other crypto wallet. The YPBShop contract splits it in the same transaction: ' + levelsTxt() + ' of the buyer\'s sponsor line (network members with a linked wallet; anyone without one is skipped and the share passes up), ' + company() + ' to the company plus any level with nobody to pay. The split is fixed in the contract. Every payment shows on ' + URL_ + '/ledger.' + (C.contractAddress ? '' : ' Spotlights are not on sale yet: the contract is not deployed.') },
|
||||
{ id: 'earn', title: 'Do I earn anything here?', q: ['Do I get paid?', 'Do I need to buy to earn?', 'How do sponsors earn?'], tags: ['earn', 'paid', 'commission', 'sponsor'],
|
||||
re: /(get paid|earn|commission|payout|do i need to buy)/i,
|
||||
a: 'Saving IDs and planting are free. When someone in your downline buys a Spotlight, the contract pays the sponsor line in the same transaction (' + levelsTxt() + '). You never need to buy a Spotlight to be paid: a network sign-in and a linked wallet are enough. ' + NOT_INCOME },
|
||||
{ id: 'sign-in', title: 'Signing in', q: ['How do I sign in?', 'Do I need an account?'], tags: ['sign in', 'member', 'wallet'],
|
||||
re: /(sign ?(in|up)|log ?in|register|account|not a member)/i,
|
||||
a: 'Sign in on ' + URL_ + '/my with your network account (InstantAdPay or LinkSpin, through the network sign-in) or with your wallet (a free signature that cannot move funds). Planting and saving IDs are for network members; joining the network is free.' },
|
||||
{ id: 'legit', title: 'Is YourProgramBuilder legit?', q: ['Is YourProgramBuilder legit?', 'Is this a scam?', 'Are the programs safe?'], tags: ['legit', 'scam', 'trust', 'contract', 'ledger'],
|
||||
re: /(\blegit|\bscam|\btrustworthy\b|is (it|this|your ?program ?builder|ypb) (safe|real)|are (the )?programs safe)/i,
|
||||
a: 'Two separate things. The programs in the Seed Bed are planted by members: they are outside programs, their link is checked every day, and you should read each one\'s terms before joining (anything in a packet is the planter\'s description, not a recommendation). The Spotlight payments go to the YPBShop contract on Polygon, which splits each one in the same transaction, has no owner withdraw, and its split can never change; SKU price changes wait 48 hours on chain. Every payment is on ' + URL_ + '/ledger. The guide: ' + URL_ + '/guides/is-it-legit' },
|
||||
{ id: 'guides', title: 'YourProgramBuilder guides', q: ['Is there a guide?', 'Where is the FAQ?', 'How do I get started?'], tags: ['guide', 'guides', 'faq', 'help', 'start'],
|
||||
re: /(\bguides?\b|\bfaq\b|get(ting)? started|how (do|can) i (start|begin)|tutorial)/i,
|
||||
a: 'The YourProgramBuilder guides: how it works ' + URL_ + '/guides/how-it-works, is it legit ' + URL_ + '/guides/is-it-legit, getting the most from your free account ' + URL_ + '/guides/free-account, planting a program that grows ' + URL_ + '/guides/planting, and the FAQ ' + URL_ + '/guides/faq. All of them: ' + URL_ + '/guides' },
|
||||
{ id: 'old', title: 'Old YourProgramBuilder accounts', q: ['I was a YourProgramBuilder member before', 'Does my old link work?', 'Where are my old programs?'], tags: ['old account', 'old link', 'old programs'],
|
||||
re: /(old (account|link|balance|member|program)|was a member|member before|before the rebuild)/i,
|
||||
a: 'Old YourProgramBuilder members are matched to the network by email and keep their sponsor. Old referral links open your new member page. Programs you added on the old site come back as dormant packets: sign in and confirm yours on My packets. Old balances were not carried over.' }
|
||||
];
|
||||
const FAQ = [
|
||||
{ id: 'f-network', title: 'YourProgramBuilder and the other network sites', source: 'faq', tags: ['network', 'one account', 'downlinehydra'],
|
||||
questions: ['Is YourProgramBuilder part of InstantAdPay?', 'How is it different from DownlineHydra?'],
|
||||
answer: 'YourProgramBuilder is part of the network: one network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, DownlineHydra, 5xYourTeam, Stack POL and Earners Corner. DownlineHydra shows the programs already in the Crypto Team Build Network builder; the Seed Bed is where new programs are planted and grow until they are ready for that builder.' },
|
||||
{ id: 'f-quota', title: 'How many programs can I plant?', source: 'faq', tags: ['quota', 'how many'],
|
||||
questions: ['How many programs can I plant?'],
|
||||
answer: 'One packet per member at a time, free. Remove yours to plant a different one. Saving IDs in other packets has no limit.' }
|
||||
];
|
||||
const FACTS = () => [
|
||||
'- WHAT IT IS: YourProgramBuilder (' + URL_ + '), the Seed Bed. PLANT: a network member plants one program free (name, referral link with {id}, their own ID, a sentence on what it is, free or paid to join with a cost note, optional contract address). Programs already in the CTB builder and network sites are refused (save IDs on DownlineHydra). SPROUT: members save their ID in any packet; visitors through a member see that member\'s link first, signed-in members see the nearest saved ID up their sponsor line, then the planter\'s. TRANSPLANT: at ' + C.reviewSaves + ' saves from distinct confirmed network members (planter included) the packet enters Marty\'s review; approved = added to the Crypto Team Build Network builder and DownlineHydra\'s wild heads with every saved ID. Not guaranteed.',
|
||||
'- LINK CHECK: before showing and every ' + C.recheckHours + ' hours. Green shows; yellow (redirect to another site, http, flagged words, a bot wall) waits for Marty; red (does not load, 404, shortener, private address, two failed rechecks) is blocked. ' + C.reportHold + ' member reports send a packet back to the queue.',
|
||||
'- SPOTLIGHT: one-time $' + SP.usd + ' = ' + SP.views.toLocaleString('en-US') + ' guaranteed verified views for one packet in the Spotlight places (top row of the Seed Bed, the Spotlight strip on packet and member pages), 1 to ' + SP.maxQty + ' per purchase; views not delivered on-site within ' + SP.deliverDays + ' days are finished in the network. Split on chain by YPBShop: ' + LV.map(pct).join(' / ') + ' to levels 1 to 5 of the buyer\'s sponsor line (network sign-in + linked wallet; the ineligible are skipped and the share passes up), ' + company() + ' company plus any empty level. Immutable split, no owner withdraw, SKU changes wait 48 hours. ' + (C.contractAddress ? 'Contract ' + C.contractAddress + '.' : 'NOT ON SALE YET: the contract is not deployed.') + ' Paid in POL with SafePal or any other crypto wallet.',
|
||||
'- VERIFIED VIEWS: page visible ' + C.visitSeconds + ' s, one view per visitor per packet per 24 h, never the planter\'s own, max ' + C.perIpDay + ' browsers per connection a day.',
|
||||
'- AI WRITER: on the planting form, "Write it from my link" reads the program\'s own page and suggests a name and a one-sentence description to edit (5 a day per member); nothing is saved until you plant.',
|
||||
'- GUIDES: ' + URL_ + '/guides (index), /guides/how-it-works, /guides/is-it-legit, /guides/free-account, /guides/planting, /guides/faq.',
|
||||
'- TRUST: ' + URL_ + '/ledger, ' + URL_ + '/contract, toasts of real events. Terms ' + URL_ + '/terms, Earnings Disclaimer ' + URL_ + '/disclaimer, Privacy ' + URL_ + '/privacy. Run by TrustClickz. SUPPORT: ' + SUPPORT + '. ' + NOT_INCOME
|
||||
].join('\n');
|
||||
|
||||
const SITE = {
|
||||
id: 'yourprogrambuilder', hubSite: 'yourprogrambuilder', netId: 'yourprogrambuilder', name: 'YourProgramBuilder', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE,
|
||||
dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS,
|
||||
intro: 'You are the assistant on YourProgramBuilder (' + URL_ + '), the Seed Bed: members plant outside programs, the network saves referral IDs in them, and the ones that grow go to review for the Crypto Team Build Network builder. It is part of a network of sites that share one account.',
|
||||
quickTopics: ['How do I plant a program?', 'How do I save my ID?', 'What happens at ' + C.reviewSaves + ' saves?', 'What is a Spotlight?']
|
||||
};
|
||||
function init() { return core.init(SITE); }
|
||||
module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE };
|
||||
@@ -0,0 +1,220 @@
|
||||
// The site assistant's engine (Marty 2026-11-15: a chatbot on every rebuilt network site), ported from LinkSpin's chatbot.js.
|
||||
// The site's own chatbot.js holds what it knows (CANNED instant answers + FACTS, written from that site's code); this file
|
||||
// holds how it answers, the same on every site:
|
||||
// 1. the knowledge base's instant answers (kb.js, seeded from CANNED; first matching pattern wins, no AI call)
|
||||
// 2. retrieval over the merged NETWORK knowledge base (this site's entries boosted, netkb.js), into the system prompt
|
||||
// 3. OpenRouter (deepseek/deepseek-v4-flash:nitro, reasoning OFF, retried once), house rules in the prompt and on the way out
|
||||
// Account problems go to the network support desk on InstantAdPay (handoff: true makes the widget offer it).
|
||||
// Routes: POST /api/chat, GET /api/chat/kb-stamp, admin GET/POST /api/admin/kb, GET/PUT/DELETE /api/admin/kb/<id>,
|
||||
// POST /api/admin/kb/test, GET /api/admin/kb/network (x-admin-token, the site's own isAdmin).
|
||||
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
const kb = require('./kb');
|
||||
const netkb = require('./netkb');
|
||||
|
||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||
let S = null; // the site: { id, hubSite, name, url, dataDir, canned, faq, facts(), about, supportUrl, linkFor, quickTopics }
|
||||
|
||||
function key() {
|
||||
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
|
||||
if (!S || !S.dataDir) return '';
|
||||
try { return fs.readFileSync(path.join(S.dataDir, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
|
||||
}
|
||||
const enabled = () => !!key();
|
||||
|
||||
// CANNED + FAQ in the shape kb.js stores (order keeps the first-match-wins sequence)
|
||||
function seeds() {
|
||||
return S.canned.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re ? c.re.source : '',
|
||||
handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(S.faq || []);
|
||||
}
|
||||
|
||||
const supportUrl = () => S.supportUrl || 'https://instantadpay.com/support';
|
||||
// asking for a person, or one person's own account problem: every site's first CANNED entry uses this (handoff: true)
|
||||
const SUPPORT_RE = /((contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|someone|a (human|person|real person))|real person|\bhuman\b|customer (service|support)|open a ticket|support (ticket|desk|team|email)|help ?desk|(my|the) (boost|purchase|payment|payout|order|account|sign.?in|log.?in|pro|upgrade|ad|banner|pick)s? (is |was |has |did |does )?(not|never|n.?t|missing|stuck|wrong|failed|broken|lost|gone)|(did ?n.?t|did not|never|has ?n.?t|have ?n.?t) (show|arriv|appear|receiv|get paid|go through|work|confirm)|i (was|got) (charged|scammed)|charged twice)/i;
|
||||
const HOUSE_RULES = () => `RULES:
|
||||
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page.
|
||||
- Your main job is ${S.name}. Questions about another network site: answer from that site's knowledge-base entry, say which site it is about, and give that site's link exactly as the entry gives it. Never mix two sites' prices, splits or rules.
|
||||
- NEVER promise or estimate income, and never state a maximum or total anyone can earn. This is advertising with a referral program, never an investment. Nobody earns unless real purchases happen in their line. Crypto payments are final.
|
||||
- Whenever ad credits come up, say: Ad credits buy advertising, not income.
|
||||
- Wallets: say "SafePal or any other crypto wallet". Never recommend MetaMask.
|
||||
- Never mention RM Circle. It is not part of this network.
|
||||
- No em dashes. If you do not know, say so plainly; never guess a price, a percentage or a rule.
|
||||
- Anything about one person's own account (a missing payout, a sign-in that will not work, a purchase that did not show, a bug) you cannot look up: say so and send them to network support at ${supportUrl()}.`;
|
||||
|
||||
function networkLine() {
|
||||
const list = netkb.sites();
|
||||
if (!list.length) return '';
|
||||
return '\nNETWORK SITES (one network account works across them; link to use for each):\n' + list.map(s => '- ' + s.name + ': ' + s.go).join('\n') + '\n';
|
||||
}
|
||||
function systemPrompt(kbBlock) {
|
||||
return S.intro + '\n\nFACTS (checked against this site\'s code on ' + S.knowledgeDate + '):\n' + S.facts() + '\n' + networkLine() + '\n' + HOUSE_RULES() + (kbBlock ? '\n\n' + kbBlock : '');
|
||||
}
|
||||
|
||||
function endpoint() {
|
||||
try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); }
|
||||
}
|
||||
function askOnce(message, historyText, kbBlock) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify({
|
||||
model: MODEL,
|
||||
reasoning: { enabled: false }, // deepseek-v4-flash reasons by default and can spend the whole max_tokens on it (2026-10-16)
|
||||
max_tokens: 320,
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt(kbBlock) },
|
||||
...(historyText ? [{ role: 'user', content: 'Earlier context: ' + String(historyText).slice(0, 800) }] : []),
|
||||
{ role: 'user', content: String(message).slice(0, 600) }
|
||||
]
|
||||
});
|
||||
const ep = endpoint();
|
||||
const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST',
|
||||
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body),
|
||||
'HTTP-Referer': S.url, 'X-Title': S.name + ' assistant' }, timeout: 30000 },
|
||||
res => {
|
||||
let d = '';
|
||||
res.on('data', c => { d += c; });
|
||||
res.on('end', () => {
|
||||
// OpenRouter can pad a slow upstream with keepalive lines before the JSON (IAP, 2026-09-17): find the object
|
||||
const i = d.indexOf('{'); let txt = '';
|
||||
try { txt = String(JSON.parse(i < 0 ? d : d.slice(i)).choices[0].message.content || '').trim(); }
|
||||
catch (e) { return reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(0, 150))); }
|
||||
if (!txt) return reject(new Error('openrouter ' + res.statusCode + ': empty content'));
|
||||
resolve(txt);
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.on('timeout', () => req.destroy(new Error('openrouter timeout')));
|
||||
req.end(body);
|
||||
});
|
||||
}
|
||||
async function askAI(message, historyText, kbBlock) {
|
||||
try { return await askOnce(message, historyText, kbBlock); }
|
||||
catch (e) { await new Promise(r => setTimeout(r, 700)); return askOnce(message, historyText, kbBlock); } // one provider dropping it is the usual cause
|
||||
}
|
||||
|
||||
// house rules on the way out, whatever the model wrote
|
||||
const RMC_RE = /\brm ?circle\b|rmcircle/i;
|
||||
function scrub(t) {
|
||||
let s = String(t || '').replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ');
|
||||
s = s.replace(/\*\*(.+?)\*\*/g, '$1').replace(/^#+\s*/gm, '');
|
||||
s = s.replace(/\bMeta ?Mask\b(\s*(,|or|and)\s*)?/gi, '').replace(/\s{2,}/g, ' ').trim();
|
||||
return s;
|
||||
}
|
||||
const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) ?not (see|check|look)|contact support|network support|support desk|\/support\b)/i;
|
||||
|
||||
async function answer(message, historyText) {
|
||||
const r = await answerRaw(message, historyText);
|
||||
if (r && typeof r.reply === 'string') {
|
||||
r.reply = scrub(r.reply);
|
||||
if (RMC_RE.test(r.reply)) r.reply = 'I can only help with ' + S.name + ' and the network sites. For anything else, network support at ' + supportUrl() + ' can point you the right way.';
|
||||
}
|
||||
return r;
|
||||
}
|
||||
async function answerRaw(message, historyText) {
|
||||
const msg = String(message || '').trim().slice(0, 600);
|
||||
if (!msg) return { error: 'Say something first.' };
|
||||
let hit = null, kbOk = true, 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); }
|
||||
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
|
||||
if (!kbOk) for (const c of S.canned) if (c.re && c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||
let kbBlock = '', kbIds = [], hits = [];
|
||||
try {
|
||||
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
|
||||
hits = await kb.context(query, 6);
|
||||
kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id);
|
||||
} catch (e) { console.error('kb search', e.message); }
|
||||
if (!enabled()) {
|
||||
// no AI: the best matching entry, if it is a clear match, else the honest fallback
|
||||
if (hits.length) { const e = hits[0].entry; return { reply: e.answer + (e.site ? ' More at ' + e.go : ''), kb: [e.id] }; }
|
||||
return { reply: S.fallback || ('Good question. The quick answers I have cover how ' + S.name + ' works, what it costs and how payouts work. For anything else, network support at ' + supportUrl() + ' will help.'), handoff: true };
|
||||
}
|
||||
try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); }
|
||||
catch (e) {
|
||||
console.error('chat AI failed', e.message);
|
||||
if (hits.length) { const x = hits[0].entry; return { reply: x.answer + (x.site ? ' More at ' + x.go : ''), kb: [x.id] }; }
|
||||
return { reply: 'I hit a snag answering that one, on our side. The live ledger at ' + S.url + '/ledger and the contract page at ' + S.url + '/contract cover most deep questions, or network support at ' + supportUrl() + ' will answer.', handoff: true };
|
||||
}
|
||||
}
|
||||
|
||||
// ---- rate limit: per visitor, in memory ----
|
||||
const hits = new Map();
|
||||
function limited(ip) {
|
||||
const now = Date.now(); const h = hits.get(ip) || { m: 0, mAt: now, d: 0, dAt: now };
|
||||
if (now - h.mAt > 60000) { h.m = 0; h.mAt = now; }
|
||||
if (now - h.dAt > 86400000) { h.d = 0; h.dAt = now; }
|
||||
h.m++; h.d++; hits.set(ip, h);
|
||||
if (hits.size > 20000) hits.clear();
|
||||
return h.m > 12 || h.d > 300;
|
||||
}
|
||||
const ipOf = req => String(req.headers['cf-connecting-ip'] || String(req.headers['x-forwarded-for'] || '').split(',')[0] || (req.socket && req.socket.remoteAddress) || 'x').trim();
|
||||
|
||||
// h: { json(res, code, obj, extra), readBody(req), isAdmin(req) }; returns true when it answered
|
||||
async function handle(req, res, p, u, h) {
|
||||
if (p === '/api/chat' && req.method === 'POST') {
|
||||
if (limited(ipOf(req))) { h.json(res, 429, { error: 'Give it a minute, then ask again.' }); return true; }
|
||||
const b = await h.readBody(req);
|
||||
const hist = Array.isArray(b.history) ? b.history.map(x => String(x || '')).join(' ').slice(-800) : String(b.history || '').slice(-800);
|
||||
const r = await answer(b.message, hist);
|
||||
if (r.reply && typeof S.finish === 'function') { try { r.reply = S.finish(r.reply); } catch (e) {} } // site hook: date-gated wording (Network Weekend 2026-11-17)
|
||||
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,72 @@
|
||||
// All runtime config comes from env (Coolify sets these). Read once.
|
||||
// YourProgramBuilder, "the Seed Bed" (yourprogrambuilder.com rebuild; Marty 2026-11-17: "I like the approach on YourProgramBuilder.
|
||||
// Go ahead and keep fleshing it out more."). An open intake for outside programs:
|
||||
// PLANT a network member plants a program free: name, referral link with {id}, what it is, cost to join, contract if crypto.
|
||||
// Every link is checked (linkcheck.js): green shows, yellow waits for Marty's queue, red is refused; rechecked daily.
|
||||
// SPROUT members save their referral ID in a packet. A visitor through a member sees that member's link first (DownlineHydra's
|
||||
// wild-head rule, wild.js), then up that member's sponsor line, then the planter's own ID.
|
||||
// TRANSPLANT at REVIEW_SAVES saves from distinct confirmed network members a packet enters Marty's review queue; approved packets
|
||||
// are exported for the Crypto Team Build Network builder and DownlineHydra's wild heads, carrying every saved ID.
|
||||
// Paid part (DEFAULTS, Marty has not answered the decision pack yet): one-time $10 Spotlight = 1,000 guaranteed verified views
|
||||
// for one packet, paid in POL to YPBShop (../contracts), split on chain in the same transaction: 20% sponsor, 5% each levels 2
|
||||
// to 5, 60% company; immutable split; members earn for free (a network sign-in + a linked wallet, no purchase needed).
|
||||
// No recurring charges, ever.
|
||||
const path = require('path');
|
||||
|
||||
let cfg = null;
|
||||
function get() {
|
||||
if (cfg) return cfg;
|
||||
const e = process.env;
|
||||
const num = (v, d, min, max) => { const n = Number(v); return Number.isFinite(n) && v !== '' && v != null ? Math.min(max, Math.max(min, n)) : d; };
|
||||
const int = (v, d, min, max) => Math.round(num(v, d, min, max));
|
||||
const addr = v => /^0x[0-9a-fA-F]{40}$/.test(String(v || '').trim()) ? require('ethers').getAddress(String(v).trim().toLowerCase()) : '';
|
||||
cfg = {
|
||||
port: Number(e.PORT || 3000),
|
||||
isProd: e.NODE_ENV === 'production',
|
||||
site: e.SITE_HOST || 'yourprogrambuilder.com',
|
||||
siteName: 'YourProgramBuilder',
|
||||
siteId: 'yourprogrambuilder', // hub site id, network sign-in audience, netsites id
|
||||
staging: e.STAGING === '1', // staging only: the admin "mark test member" switch
|
||||
dataDir: e.DATA_DIR || path.join(__dirname, 'data'),
|
||||
chainId: Number(e.CHAIN_ID || 137),
|
||||
chainName: e.CHAIN_NAME || 'Polygon',
|
||||
publicRpc: e.PUBLIC_RPC || 'https://polygon-bor-rpc.publicnode.com',
|
||||
walletConnectProjectId: (e.WALLETCONNECT_PROJECT_ID || '').trim(),
|
||||
// ---- the Seed Bed (DEFAULT 25 saves, decision pack 2026-11-17) ----
|
||||
reviewSaves: int(e.REVIEW_SAVES, 25, 2, 1000),
|
||||
plantQuota: int(e.PLANT_QUOTA, 1, 1, 20), // packets one member may have planted at once (the pack: "plants one program free")
|
||||
packet: { name: 40, desc: 200, cost: 40 },
|
||||
recheckHours: int(e.RECHECK_HOURS, 24, 1, 720), // every live packet's link is checked again this often
|
||||
reportHold: int(e.REPORT_HOLD, 3, 1, 100), // distinct member reports that move a packet back to Marty's queue
|
||||
viaDays: int(e.VIA_DAYS, 30, 1, 365), // how long a ?ref= / member page tag stays on a visitor (last touch)
|
||||
// ---- Spotlight (DEFAULTS: $10 = 1,000 views, one-time). The contract's SKU holds the real price; this is display copy and must match it.
|
||||
spotlight: { sku: int(e.SPOTLIGHT_SKU, 1, 1, 1000), usd: num(e.SPOTLIGHT_USD, 10, 0.01, 1000), views: int(e.SPOTLIGHT_VIEWS, 1000, 1, 1000000), maxQty: 10,
|
||||
deliverDays: int(e.DELIVER_DAYS, 30, 1, 365), row: int(e.SPOTLIGHT_ROW, 3, 1, 12) },
|
||||
// YPBShop split (DEFAULT 20 / 5 / 5 / 5 / 5, company 60; IMMUTABLE on the contract, read live from it when the contract is set)
|
||||
split: { levelBps: String(e.SPLIT_LEVEL_BPS || '2000,500,500,500,500').split(',').map(x => int(x, 0, 0, 9000)).slice(0, 5), maxDepth: 20 },
|
||||
hubJoin: e.HUB_JOIN === '1', // writes to the hub (join-all). OFF on staging: a dry check instead
|
||||
payouts: e.PAYOUTS === '1', // staging: OFF (no keeper key, no contract). Orders need KEEPER_KEY + CONTRACT_ADDRESS anyway
|
||||
// verified visitors (the VBB / ViralAdBlitz rules)
|
||||
visitSeconds: int(e.VISIT_SECONDS, 6, 2, 60),
|
||||
perIpDay: int(e.VISITS_PER_IP_DAY, 3, 1, 100),
|
||||
linkProbe: e.LINK_PROBE !== '0',
|
||||
explorer: String(e.EXPLORER || (Number(e.CHAIN_ID || 137) === 137 ? 'https://polygonscan.com' : '')).replace(/\/+$/, ''),
|
||||
// YPBShop (../contracts). KEEPER_KEY is read by shop.js only, never kept here.
|
||||
contractAddress: addr(e.CONTRACT_ADDRESS),
|
||||
companyWallet: addr(e.COMPANY_WALLET) || '0x7627Fc78876948AC9d95C1C9eB061E7D6d647b70', // Tangem (immutable in YPBShop)
|
||||
chainRpc: String(e.CHAIN_RPC || '').trim(),
|
||||
shopStartBlock: int(e.SHOP_START_BLOCK, 0, 0, 1e12),
|
||||
shopConfirmations: int(e.SHOP_CONFIRMATIONS, 10, 0, 1000),
|
||||
shopPollMs: int(e.SHOP_POLL_MS, 30000, 200, 3600000),
|
||||
voucherSeconds: int(e.VOUCHER_SECONDS, 1800, 60, 86400),
|
||||
iapBase: String(e.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''),
|
||||
lsBase: String(e.LS_URL || 'https://linkspin.app').replace(/\/+$/, ''),
|
||||
dhBase: String(e.DH_URL || 'https://downlinehydra.com').replace(/\/+$/, ''),
|
||||
joinUrl: String(e.JOIN_URL || 'https://instantadpay.com/join/{ref}'),
|
||||
networkLookupUrl: e.NETWORK_LOOKUP_URL !== undefined ? String(e.NETWORK_LOOKUP_URL).trim()
|
||||
: String(e.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '') + '/api/network/member'
|
||||
};
|
||||
return cfg;
|
||||
}
|
||||
|
||||
module.exports = { get, reset: () => { cfg = null; } };
|
||||
@@ -0,0 +1,46 @@
|
||||
services:
|
||||
yourprogrambuilder:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
PORT: 3000
|
||||
DATA_DIR: /app/data
|
||||
SITE_HOST: ${SITE_HOST:-yourprogrambuilder.com}
|
||||
STAGING: ${STAGING:-0}
|
||||
DOCSTORE_URL: ${DOCSTORE_URL:-}
|
||||
SESSION_SECRET: ${SESSION_SECRET:-}
|
||||
ADMIN_TOKEN: ${ADMIN_TOKEN:-}
|
||||
NETWORK_SSO_SECRET: ${NETWORK_SSO_SECRET:-}
|
||||
WALLETCONNECT_PROJECT_ID: ${WALLETCONNECT_PROJECT_ID:-}
|
||||
CONTRACT_ADDRESS: ${CONTRACT_ADDRESS:-}
|
||||
CHAIN_RPC: ${CHAIN_RPC:-}
|
||||
CHAIN_ID: ${CHAIN_ID:-137}
|
||||
SHOP_START_BLOCK: ${SHOP_START_BLOCK:-}
|
||||
KEEPER_KEY: ${KEEPER_KEY:-}
|
||||
PAYOUTS: ${PAYOUTS:-0}
|
||||
HUB_JOIN: ${HUB_JOIN:-0}
|
||||
HUB_URL: ${HUB_URL:-}
|
||||
HUB_SECRET: ${HUB_SECRET:-}
|
||||
HUB_SITE: ${HUB_SITE:-yourprogrambuilder}
|
||||
HUB_ENABLED: ${HUB_ENABLED:-0}
|
||||
HUB_SSO: ${HUB_SSO:-off}
|
||||
LS_TRACK: ${LS_TRACK:-0}
|
||||
LS_PARTNER: ${LS_PARTNER:-ypb}
|
||||
TG_TOKEN: ${TG_TOKEN:-}
|
||||
TG_CHAT: ${TG_CHAT:-}
|
||||
TG_PAY_TOPIC: ${TG_PAY_TOPIC:-}
|
||||
JOIN_URL: ${JOIN_URL:-}
|
||||
REVIEW_SAVES: ${REVIEW_SAVES:-25}
|
||||
LS_ZONES: ${LS_ZONES:-}
|
||||
DH_URL: ${DH_URL:-}
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||
VERIFIED_SOURCIFY: ${VERIFIED_SOURCIFY:-0}
|
||||
VERIFIED_POLYGONSCAN: ${VERIFIED_POLYGONSCAN:-0}
|
||||
AI_WRITER: ${AI_WRITER:-} # the AI ad writer runs on the hub (HUB_URL/HUB_SECRET); 0 hides the button
|
||||
volumes:
|
||||
- ypb-data:/app/data # the session secret only; all data lives in MySQL (DOCSTORE_URL)
|
||||
expose:
|
||||
- "3000"
|
||||
volumes:
|
||||
ypb-data:
|
||||
@@ -0,0 +1,191 @@
|
||||
// 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, LinkSpin, Downline Banners and VBB.
|
||||
'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)
|
||||
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() }); 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 (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) });
|
||||
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); }
|
||||
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };
|
||||
@@ -0,0 +1,54 @@
|
||||
// The network AI ad writer, asked through the hub (Marty 2026-11-17: "the AI generation of the ads worked really well. Let's go
|
||||
// ahead and do it on the other sites too."). The hub reads the member's page, asks the model and filters the copy
|
||||
// (network-hub lib/adwriter.js); this file only signs the call for this site's signed-in member and passes the answer on.
|
||||
// status(member?) -> {on, daily, left?} (cached 60 s; on: false when the hub is unset, unreachable or switched off)
|
||||
// write(member, url, limits) -> {ok, options: [{headline, line?}], url, cached, left} | {error (member-friendly), code, status, left?}
|
||||
// Signed as HUB_SITE with HUB_SECRET: X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body), like every /v1 call.
|
||||
// AI_WRITER=0 hides the button on this site. Nothing is posted: the member picks an option, edits it and saves it themselves.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DEFAULT_SITE = 'yourprogrambuilder';
|
||||
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const secret = () => String(process.env.HUB_SECRET || '').trim();
|
||||
const site = () => String(process.env.HUB_SITE || DEFAULT_SITE).trim();
|
||||
const configured = () => !/^(0|false|no|off)$/i.test(String(process.env.AI_WRITER || '').trim()) && !!hubUrl() && secret().length >= 32;
|
||||
|
||||
async function call(route, body, timeoutMs) {
|
||||
const raw = 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: 'POST', body: raw, signal: AbortSignal.timeout(timeoutMs),
|
||||
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': site(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
|
||||
let j = null; try { j = await r.json(); } catch (e) { j = null; }
|
||||
return { status: r.status, body: j || {} };
|
||||
}
|
||||
|
||||
let st = { at: 0, v: { on: false, daily: 0 } };
|
||||
async function status(member) {
|
||||
if (!configured()) return { on: false, daily: 0 };
|
||||
if (!member && Date.now() - st.at < 60000) return st.v;
|
||||
try {
|
||||
const r = await call('/v1/adwriter/status', member ? { member: String(member) } : {}, 3000);
|
||||
const v = r.status === 200 && r.body && typeof r.body.on === 'boolean' ? r.body : { on: false, daily: 0 };
|
||||
if (!member) st = { at: Date.now(), v: { on: v.on, daily: v.daily || 0 } };
|
||||
return v;
|
||||
} catch (e) { if (!member) st = { at: Date.now() - 45000, v: { on: false, daily: 0 } }; return { on: false, daily: 0 }; } // a down hub is asked again in 15 s
|
||||
}
|
||||
// the button shows only when the hub says the writer is on (60 s cache, never waits on a slow hub for long)
|
||||
async function enabled() { return (await status()).on === true; }
|
||||
|
||||
async function write(member, url, limits) {
|
||||
if (!configured()) return { error: 'The ad writer is switched off right now. You can still write your ad yourself.', code: 'off', status: 503 };
|
||||
try {
|
||||
const r = await call('/v1/adwriter', { member: String(member), url: String(url || '').trim().slice(0, 600), limits }, 75000);
|
||||
const b = r.body || {};
|
||||
if (r.status === 200 && b.ok && Array.isArray(b.options)) return { ok: true, options: b.options, url: b.url, cached: !!b.cached, left: b.left };
|
||||
if (r.status === 401 || r.status === 403 || !b.message) { console.error('hubadwriter: hub answered ' + r.status + ' ' + String(b.error || '')); return { error: 'The ad writer is busy right now. Try again in a minute, or write your ad yourself.', code: 'hub', status: 502 }; }
|
||||
return { error: String(b.message), code: b.error || b.code || 'error', status: r.status >= 400 && r.status < 600 ? r.status : 502, left: b.left };
|
||||
} catch (e) {
|
||||
console.error('hubadwriter: ' + (e.name === 'TimeoutError' || e.name === 'AbortError' ? 'timeout' : String(e.message).slice(0, 120)));
|
||||
return { error: 'The ad writer did not answer in time. Try again in a minute, or write your ad yourself.', code: 'hub', status: 504 };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { status, enabled, write, configured, _reset: () => { st = { at: 0, v: { on: false, daily: 0 } }; } };
|
||||
@@ -0,0 +1,135 @@
|
||||
// Network hub events for a wallet site (Marty 2026-11-16, "Yes do 1 and 2"). Byte-identical in Viral Banner Blitz, Downline Banners,
|
||||
// ViralAdBlitz, DownlineHydra and 5xYourTeam (like networksso.js): copy it whole, never edit one copy alone.
|
||||
//
|
||||
// The hub tells every hooked site what changed (POST /api/hub/events, the same hook InstantAdPay and LinkSpin take): X-Hub-Ts +
|
||||
// X-Hub-Sig = hex HMAC-SHA256(HUB_SECRET, ts + newline + raw body), 5-minute window. The hub only moves its cursor after a 2xx and
|
||||
// may send an event twice. This site acts on three events and ignores every other one:
|
||||
// member.signedout "Sign out everywhere" on any network site
|
||||
// member.blocked the hub blocked the person
|
||||
// member.erased the hub erased the person ({emailHash, walletHashes}: the person is gone from the hub, so no lookup)
|
||||
// Each one ends that person's sessions here. A wallet site keys sessions by wallet, so the person is mapped through the hub:
|
||||
// POST /v1/resolve {id} (signed as HUB_SITE) gives their main wallet and every contract wallet (contractWallets). An erased
|
||||
// person cannot be looked up any more: the event carries the SHA-256 of each of their wallets (and of their email) instead.
|
||||
// Only sessions made BEFORE the event end (a fresh sign-in after it stays), so a replay can never sign anyone out twice.
|
||||
// A failed lookup answers 503 so the hub sends the batch again; after 5 tries an event is set aside in the log.
|
||||
// Nothing here sends mail, posts or touches a banner, a payout or the chain: it only ends sign-in sessions.
|
||||
//
|
||||
// init({ dataDir, site, end }) where end({ type, personId, at, wallets, walletHashes, emailHash, match }) ends the sessions and
|
||||
// answers how many; match(session-like {address?, email?, wallet?, hubId?}) is the shared test (wallet, wallet hash, email
|
||||
// hash, hub id). Off when HUB_HOOK=0, or without HUB_URL and a 32+ character HUB_SECRET (then the route answers 404).
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const WALLET_RE = /^0x[0-9a-f]{40}$/, HASH_RE = /^[0-9a-f]{64}$/;
|
||||
const TRIES = 5, KEEP = 3000, SKEW = 2000;
|
||||
const ACTS = new Set(['member.signedout', 'member.blocked', 'member.erased']);
|
||||
let R = null, st = null, chain_ = Promise.resolve();
|
||||
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
|
||||
const BASE = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const SITE = () => String(process.env.HUB_SITE || (R && R.site) || '').trim().toLowerCase();
|
||||
const on = () => !/^(0|false|no|off)$/i.test(String(process.env.HUB_HOOK || '').trim()) && /^https?:\/\/[a-z0-9.:-]+$/i.test(BASE()) && SECRET().length >= 32;
|
||||
const lc = v => String(v == null ? '' : v).trim().toLowerCase();
|
||||
const sha = v => crypto.createHash('sha256').update(lc(v)).digest('hex');
|
||||
const FILE = () => path.join(R.dataDir, 'hubevents.json');
|
||||
|
||||
function load() {
|
||||
if (st) return st;
|
||||
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
||||
if (!st || typeof st !== 'object') st = {};
|
||||
st.done = st.done || {}; st.tries = st.tries || {}; st.log = st.log || [];
|
||||
st.stats = Object.assign({ batches: 0, events: 0, ended: 0, ignored: 0, skipped: 0, gaveUp: 0, refused: 0 }, st.stats || {});
|
||||
return st;
|
||||
}
|
||||
function save() { if (!R || !R.dataDir) return; try { const t = FILE() + '.tmp'; fs.writeFileSync(t, JSON.stringify(load())); fs.renameSync(t, FILE()); } catch (e) { console.error('hubevents save', e.message); } }
|
||||
function note(x) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, x)); if (s.log.length > 200) s.log = s.log.slice(-200); }
|
||||
function init(deps) { R = deps || {}; load(); }
|
||||
|
||||
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
|
||||
function verify(headers, raw) {
|
||||
if (SECRET().length < 32) return false;
|
||||
const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || '');
|
||||
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000 || !/^[0-9a-f]{64}$/.test(sig)) return false;
|
||||
const want = sign(ts, raw);
|
||||
return crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
|
||||
}
|
||||
// the hub person by hub id (null = the hub does not know them); throws when the hub does not answer
|
||||
async function resolveId(id) {
|
||||
const raw = JSON.stringify({ id }); const ts = String(Date.now());
|
||||
const r = await fetch(BASE() + '/v1/resolve', { method: 'POST', body: raw, signal: AbortSignal.timeout(10000),
|
||||
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) } });
|
||||
if (r.status !== 200) throw new Error('hub resolve ' + r.status);
|
||||
const j = await r.json(); return j && j.person && typeof j.person === 'object' ? j.person : null;
|
||||
}
|
||||
// every wallet the hub holds for a person: the main wallet and each contract's wallet
|
||||
function walletsOf(p) {
|
||||
const out = new Set(); if (!p) return [];
|
||||
if (WALLET_RE.test(lc(p.wallet))) out.add(lc(p.wallet));
|
||||
for (const w of Object.values(p.contractWallets || {})) if (WALLET_RE.test(lc(w))) out.add(lc(w));
|
||||
return [...out];
|
||||
}
|
||||
// the shared test: does this session / member belong to the person?
|
||||
function matcher(who) {
|
||||
const ws = new Set(who.wallets || []), hs = new Set(who.walletHashes || []), eh = who.emailHash || null, id = who.personId || null;
|
||||
return x => {
|
||||
if (!x) return false;
|
||||
for (const w of [x.address, x.wallet, x.hubWallet]) { const v = lc(w); if (WALLET_RE.test(v) && (ws.has(v) || hs.has(sha(v)))) return true; }
|
||||
if (eh && x.email && sha(x.email) === eh) return true;
|
||||
if (id && (x.hubId === id || x.key === id)) return true;
|
||||
return false;
|
||||
};
|
||||
}
|
||||
async function apply(ev) {
|
||||
if (!ACTS.has(ev.type) || !ev.personId) return 'ignored';
|
||||
const who = { type: ev.type, personId: String(ev.personId), at: Number(ev.at) || Date.now(), wallets: [], walletHashes: [], emailHash: null };
|
||||
if (ev.type === 'member.erased') {
|
||||
const d = ev.data || {};
|
||||
who.walletHashes = (Array.isArray(d.walletHashes) ? d.walletHashes : []).map(lc).filter(h => HASH_RE.test(h)).slice(0, 50);
|
||||
who.emailHash = HASH_RE.test(lc(d.emailHash)) ? lc(d.emailHash) : null;
|
||||
} else {
|
||||
const p = await resolveId(who.personId); // throws: the hub sends it again
|
||||
if (!p) return 'ignored';
|
||||
who.wallets = walletsOf(p);
|
||||
}
|
||||
who.before = who.at + SKEW; // sessions made after the event are fresh sign-ins and stay
|
||||
who.match = matcher(who);
|
||||
const n = Number(await R.end(who)) || 0;
|
||||
note({ type: ev.type, seq: ev.seq, sessions: n });
|
||||
if (n) { load().stats.ended += n; return 'applied'; }
|
||||
return 'none';
|
||||
}
|
||||
function prune() {
|
||||
const s = load(); const seqs = Object.keys(s.done).map(Number).sort((a, b) => a - b);
|
||||
for (const q of seqs.slice(0, Math.max(0, seqs.length - KEEP))) delete s.done[q];
|
||||
}
|
||||
async function handle(events) {
|
||||
const s = load(); s.stats.batches++; let failed = null;
|
||||
for (const ev of Array.isArray(events) ? events : []) {
|
||||
const seq = Number(ev && ev.seq); if (!seq) continue;
|
||||
if (s.done[seq]) { s.stats.skipped++; continue; }
|
||||
s.stats.events++;
|
||||
try {
|
||||
const r = await apply(ev);
|
||||
s.done[seq] = Date.now(); delete s.tries[seq];
|
||||
if (r === 'ignored') s.stats.ignored++;
|
||||
} catch (e) {
|
||||
s.tries[seq] = (s.tries[seq] || 0) + 1;
|
||||
console.error('hubevents', seq, ev.type, e.message);
|
||||
if (s.tries[seq] >= TRIES) { s.done[seq] = Date.now(); delete s.tries[seq]; s.stats.gaveUp++; note({ type: 'gave-up', seq, event: ev.type, error: String(e.message).slice(0, 160) }); continue; }
|
||||
failed = e; break;
|
||||
}
|
||||
}
|
||||
prune(); save();
|
||||
return failed ? { status: 503, body: { error: 'retry' } } : { status: 200, body: { ok: true } };
|
||||
}
|
||||
// the POST /api/hub/events handler -> { status, body }. Batches run one at a time.
|
||||
function receive(headers, raw) {
|
||||
if (!R || !on()) return Promise.resolve({ status: 404, body: { error: 'not found' } });
|
||||
if (!verify(headers || {}, String(raw || ''))) { load().stats.refused++; return Promise.resolve({ status: 401, body: { error: 'unauthorized' } }); }
|
||||
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return Promise.resolve({ status: 400, body: { error: 'bad json' } }); }
|
||||
const run = chain_.then(() => handle(b && b.events)); chain_ = run.catch(() => {}); return run;
|
||||
}
|
||||
function view() { const s = load(); return { on: on(), stats: s.stats, waiting: Object.keys(s.tries).length, log: s.log.slice(-20) }; }
|
||||
|
||||
module.exports = { init, receive, view, on, verify, walletsOf, matcher, sha, _reset: () => { st = null; chain_ = Promise.resolve(); } };
|
||||
@@ -0,0 +1,43 @@
|
||||
// A member's sponsor line from the network hub (the one source of truth, Marty 2026-11-13/14). Walks hubpeople.sponsorOf()
|
||||
// up to `max` places, nearest first: [{ depth, id, username, wallet }]. Used two ways:
|
||||
// - member pages (viraladblitz.com/<username>): the ads of the first 5 people above with a live ad here
|
||||
// - Boost vouchers: the wallets of the line, bound on chain on the buyer's first Boost (VABShop binds link by link)
|
||||
// Answers are cached 5 minutes per start person. {ok: false} = the hub did not answer all the way (the line is partial); the
|
||||
// caller decides (pages fall back to the last good line; vouchers are not signed on a partial line).
|
||||
'use strict';
|
||||
const hubpeople = require('./hubpeople');
|
||||
|
||||
const TTL = () => Number(process.env.HUB_CACHE_MS || 5 * 60000);
|
||||
const cache = new Map(); const lastGood = new Map();
|
||||
|
||||
async function walk(person, max) {
|
||||
const line = []; const seen = new Set([person.id]); let p = person;
|
||||
for (let depth = 1; depth <= max; depth++) {
|
||||
if (!p.sponsor || !p.sponsor.id) return { ok: true, line };
|
||||
if (seen.has(p.sponsor.id)) return { ok: true, line, loop: true }; // a loop in the hub data: stop
|
||||
// the raw hub answer (blocked people included) so the walk goes on past a blocked sponsor; callers skip `blocked` entries
|
||||
// (Boost orders: a blocked member earns nothing and the level passes up, Marty 2026-11-17)
|
||||
if (!/^h_[0-9a-f]{16}$/.test(String(p.sponsor.id))) return { ok: true, line };
|
||||
const r = await hubpeople.resolve({ id: String(p.sponsor.id) }); if (!r.ok) return { ok: false, line };
|
||||
if (!r.person) return { ok: true, line };
|
||||
seen.add(r.person.id);
|
||||
line.push({ depth, id: r.person.id, username: r.person.username ? String(r.person.username) : null, wallet: hubpeople.wallet(r.person), blocked: !!r.person.blocked });
|
||||
p = r.person;
|
||||
}
|
||||
return { ok: true, line };
|
||||
}
|
||||
|
||||
// start = { ref: username } | { wallet }. -> { ok, person, line, stale? }
|
||||
async function lineOf(start, max) {
|
||||
const k = JSON.stringify(start) + '|' + max; const hit = cache.get(k);
|
||||
if (hit && Date.now() - hit.at < TTL()) return hit.v;
|
||||
const me = start.wallet ? await hubpeople.byWallet(start.wallet) : await hubpeople.byRef(start.ref);
|
||||
let v;
|
||||
if (!me.ok) v = { ok: false, person: null, line: [] };
|
||||
else if (!me.person) v = { ok: true, person: null, line: [] };
|
||||
else { const w = await walk(me.person, max); v = { ok: w.ok, person: me.person, line: w.line }; }
|
||||
if (v.ok) { cache.set(k, { at: Date.now(), v }); lastGood.set(k, v); if (cache.size > 20000) cache.clear(); if (lastGood.size > 20000) lastGood.clear(); return v; }
|
||||
const lg = lastGood.get(k); return lg ? Object.assign({}, lg, { ok: false, stale: true }) : v;
|
||||
}
|
||||
|
||||
module.exports = { lineOf, walk, _reset: () => { cache.clear(); lastGood.clear(); } };
|
||||
@@ -0,0 +1,62 @@
|
||||
// Network hub lookups (Marty 2026-11-14: "want everything looped through the hub to verify membership"). The hub is the one
|
||||
// record per person across the network; this asks it who a username, wallet or hub id is:
|
||||
// POST /v1/resolve {ref: <username or wallet>} | {wallet} | {id: 'h_...'} -> {person: view or null}
|
||||
// signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body)), the same
|
||||
// scheme as hubreport.js. This site cannot see emails (seeEmails false): a person is {id, username, wallet, sponsor: {id, username}, blocked, ...}.
|
||||
// Answers (people and misses) are cached HUB_CACHE_MS (5 minutes). A failed call (timeout, refused, any non-200) is never
|
||||
// cached: it returns {ok: false} so the caller can fall back, and the hub is skipped for 30 seconds so pages never wait on it.
|
||||
// On unless HUB_LOOKUP=0; needs HUB_URL and a 32+ character HUB_SECRET (HUB_ENABLED only switches the shadow report).
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DEFAULT_SITE = 'yourprogrambuilder';
|
||||
const ADDR_RE = /^0x[0-9a-f]{40}$/;
|
||||
const TTL = () => Number(process.env.HUB_CACHE_MS || 5 * 60000);
|
||||
const TIMEOUT = () => Number(process.env.HUB_LOOKUP_TIMEOUT_MS || 2500);
|
||||
const on = () => !/^(0|false|no|off)$/i.test(String(process.env.HUB_LOOKUP || '').trim())
|
||||
&& !!String(process.env.HUB_URL || '').trim() && String(process.env.HUB_SECRET || '').trim().length >= 32;
|
||||
const cache = new Map(); let downUntil = 0; let lastError = null; const stats = { asked: 0, cached: 0, failed: 0 };
|
||||
|
||||
async function call(body) {
|
||||
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', String(process.env.HUB_SECRET).trim()).update(ts + '\n' + raw).digest('hex');
|
||||
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), TIMEOUT());
|
||||
try {
|
||||
const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + '/v1/resolve', { method: 'POST', body: raw, signal: ac.signal,
|
||||
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || DEFAULT_SITE).trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
|
||||
if (r.status !== 200) throw new Error('hub answered ' + r.status);
|
||||
const j = await r.json();
|
||||
if (!j || typeof j !== 'object' || !('person' in j)) throw new Error('hub answer has no person field');
|
||||
return j.person && typeof j.person === 'object' ? j.person : null;
|
||||
} finally { clearTimeout(t); }
|
||||
}
|
||||
|
||||
// {ok: true, person: view | null} when the hub answered; {ok: false} when it is off or unreachable (the caller falls back)
|
||||
async function resolve(body) {
|
||||
if (!on() || Date.now() < downUntil) return { ok: false };
|
||||
const k = JSON.stringify(body); const hit = cache.get(k);
|
||||
if (hit && Date.now() - hit.at < TTL()) { stats.cached++; return { ok: true, person: hit.person }; }
|
||||
stats.asked++;
|
||||
let person;
|
||||
try { person = await call(body); } catch (e) {
|
||||
stats.failed++; downUntil = Date.now() + Number(process.env.HUB_DOWN_MS || 30000);
|
||||
if (!lastError || Date.now() - lastError.at > 600000) console.error('hub lookup failed, falling back:', e.name === 'AbortError' ? 'timeout' : e.message);
|
||||
lastError = { at: Date.now(), error: e.name === 'AbortError' ? 'timeout' : String(e.message).slice(0, 120) };
|
||||
return { ok: false };
|
||||
}
|
||||
if (cache.size > 20000) cache.clear();
|
||||
cache.set(k, { at: Date.now(), person });
|
||||
if (person && person.id) cache.set(JSON.stringify({ id: person.id }), { at: Date.now(), person });
|
||||
return { ok: true, person };
|
||||
}
|
||||
|
||||
const wallet = p => (p && ADDR_RE.test(String(p.wallet || '').toLowerCase()) ? String(p.wallet).toLowerCase() : null);
|
||||
// a username or wallet -> person (a blocked person counts as unknown)
|
||||
async function byRef(ref) { const r = await resolve({ ref: String(ref || '').trim().toLowerCase() }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; }
|
||||
async function byWallet(w) { const r = await resolve({ wallet: String(w || '').trim().toLowerCase() }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; }
|
||||
async function byId(id) { if (!/^h_[0-9a-f]{16}$/.test(String(id || ''))) return { ok: true, person: null }; const r = await resolve({ id: String(id) }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; }
|
||||
// the person's network sponsor as a full person (with wallet), resolved through the hub by hub id. {ok, person: sponsor or null}
|
||||
async function sponsorOf(p) { if (!p || !p.sponsor || !p.sponsor.id) return { ok: true, person: null }; return byId(p.sponsor.id); }
|
||||
|
||||
function view() { return { on: on(), down: Date.now() < downUntil, cached: cache.size, stats, lastError }; }
|
||||
module.exports = { resolve, byRef, byWallet, byId, sponsorOf, wallet, view, on, _reset: () => { cache.clear(); downUntil = 0; } };
|
||||
@@ -0,0 +1,75 @@
|
||||
// Network hub report (the Downline Banners / VBB hubreport.js pattern, 2026-11-14). YourProgramBuilder members are wallets here, so every YPBShop Spotlight
|
||||
// goes to the hub by wallet:
|
||||
// the buyer's first purchase: POST /v1/contract-bind { contract: 'yourprogrambuilder', wallet, sponsorRef: <sponsor wallet>, spentCents, tx, at }
|
||||
// every later purchase: POST /v1/contract-spend { contract: 'yourprogrambuilder', wallet, cents, tx, at }
|
||||
// signed as HUB_SITE (default viraladsource) with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body)).
|
||||
// One way only: nothing the hub answers changes anything here. A wallet the hub does not know (404) is kept in `unknown` and asked
|
||||
// again every 6 hours (the member may link it on InstantAdPay later). Off unless HUB_ENABLED=1 with HUB_URL and a 32+ char HUB_SECRET.
|
||||
// State lives in hubreport.json (a MySQL document through docstore when DOCSTORE_URL is set).
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const CONTRACT = 'yourprogrambuilder';
|
||||
const ZERO = '0x0000000000000000000000000000000000000000';
|
||||
const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim())
|
||||
&& !!String(process.env.HUB_URL || '').trim() && String(process.env.HUB_SECRET || '').trim().length >= 32;
|
||||
const RECHECK = 6 * 3600000;
|
||||
let R = null, st = null, busy = false;
|
||||
const FILE = () => path.join(R.dataDir, 'hubreport.json');
|
||||
function load() {
|
||||
if (st) return st;
|
||||
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = {}; }
|
||||
st.sent = st.sent || {}; st.bound = st.bound || {}; st.unknown = st.unknown || {}; st.errors = st.errors || {}; st.log = st.log || [];
|
||||
return st;
|
||||
}
|
||||
function save() { try { fs.writeFileSync(FILE() + '.tmp', JSON.stringify(load())); fs.renameSync(FILE() + '.tmp', FILE()); } catch (e) { console.error('hubreport save', e.message); } }
|
||||
function note(x) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, x)); if (s.log.length > 200) s.log = s.log.slice(-200); }
|
||||
|
||||
async function post(route, body) {
|
||||
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', String(process.env.HUB_SECRET).trim()).update(ts + '\n' + raw).digest('hex');
|
||||
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 15000);
|
||||
try {
|
||||
const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + route, { method: 'POST', body: raw, signal: ac.signal,
|
||||
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || 'yourprogrambuilder').trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
|
||||
let j = null; try { j = await r.json(); } catch (e) {}
|
||||
return { status: r.status, body: j };
|
||||
} finally { clearTimeout(t); }
|
||||
}
|
||||
|
||||
async function tick() {
|
||||
if (!enabled() || busy) return; busy = true;
|
||||
try {
|
||||
const s = load(); const now = Date.now();
|
||||
const list = R.purchases().slice().sort((a, b) => (a.block || 0) - (b.block || 0) || (a.at || 0) - (b.at || 0));
|
||||
for (const p of list) {
|
||||
if (s.sent[p.key]) continue;
|
||||
const a = p.buyer;
|
||||
if (s.unknown[a] && now - s.unknown[a].at < RECHECK) continue;
|
||||
const tx = String(p.key).split(':')[0];
|
||||
const bind = !s.bound[a];
|
||||
const body = bind
|
||||
? { contract: CONTRACT, wallet: a, sponsorRef: p.sponsor && p.sponsor !== ZERO ? p.sponsor : '', spentCents: p.usdCents || 0, tx, at: p.at || now }
|
||||
: { contract: CONTRACT, wallet: a, cents: p.usdCents || 0, tx, at: p.at || now };
|
||||
let r; try { r = await post(bind ? '/v1/contract-bind' : '/v1/contract-spend', body); }
|
||||
catch (e) { s.errors[p.key] = { at: now, error: e.message }; break; } // hub unreachable: try again next tick
|
||||
if (r.status === 200) { s.sent[p.key] = { at: now, route: bind ? 'bind' : 'spend' }; if (bind) s.bound[a] = now; delete s.unknown[a]; delete s.errors[p.key]; note({ sent: p.key, bind }); }
|
||||
else if (r.status === 404) { s.unknown[a] = { at: now, sponsor: p.sponsor || null }; note({ unknown: a }); }
|
||||
else { s.errors[p.key] = { at: now, status: r.status, error: r.body && (r.body.error || r.body.message) }; note({ error: p.key, status: r.status }); if (r.status >= 500) break; }
|
||||
}
|
||||
save();
|
||||
} finally { busy = false; }
|
||||
}
|
||||
|
||||
// deps: { dataDir, purchases: () => [{ key, buyer, sponsor, usdCents, block, at }] }
|
||||
function init(deps) {
|
||||
R = deps; if (!enabled()) return; load(); save();
|
||||
const every = Math.max(200, Number(process.env.HUB_TICK_MS) || 60000);
|
||||
setTimeout(() => tick().catch(e => console.error('hubreport', e.message)), Math.min(20000, every)).unref();
|
||||
setInterval(() => tick().catch(e => console.error('hubreport', e.message)), every).unref();
|
||||
}
|
||||
function view() { if (!R) return { enabled: false }; const s = load(); return { enabled: enabled(), site: String(process.env.HUB_SITE || 'yourprogrambuilder').trim(), sent: Object.keys(s.sent).length, bound: Object.keys(s.bound).length, unknown: s.unknown, errors: s.errors, log: s.log.slice(-30) }; }
|
||||
|
||||
module.exports = { init, tick, view, enabled, CONTRACT };
|
||||
@@ -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 } };
|
||||
@@ -0,0 +1,55 @@
|
||||
// The link check every planted program goes through (the 11-07 rule from the decision pack: green shows, yellow goes to Marty's
|
||||
// queue, red is blocked; rechecked daily; members can report a packet).
|
||||
// verdict(flags, probe) pure: the colour for a packet from the editor's flags (myheads.validate) and the live probe answer
|
||||
// probe(url) the referral template with a sample ID, fetched from a public address only (safety.get: private
|
||||
// addresses refused, 6 s timeout, no body read), up to 3 redirects followed by hand
|
||||
// GREEN the page answers 2xx/3xx on https, stays on the same site (or a www/sub of it), and the text has no flags
|
||||
// YELLOW it works but something needs a person: spam-like words, a link in the description, all caps, plain http, a redirect to
|
||||
// another site, a 4xx that may be a bot wall (403/429), or a failed recheck of a packet that was green before (one miss)
|
||||
// RED refused or taken down: the probe cannot reach it, a 404/410/5xx, a private address, a shortener (myheads refuses those
|
||||
// before the probe), or two failed rechecks in a row
|
||||
'use strict';
|
||||
const safety = require('./safety');
|
||||
|
||||
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, '').replace(/\.$/, ''); } catch (e) { return ''; } };
|
||||
const sameSite = (a, b) => a === b || a.endsWith('.' + b) || b.endsWith('.' + a);
|
||||
const sample = url => String(url).replace(/\{id\}/g, 'ypbcheck');
|
||||
|
||||
async function probe(url) {
|
||||
let cur = sample(url); const start = hostOf(cur);
|
||||
if (!/^https:\/\//i.test(cur)) return { ok: true, http: true, status: null, host: start, note: 'plain http (not probed)' };
|
||||
for (let hop = 0; hop < 4; hop++) {
|
||||
const r = await safety.get(cur, 0, 6000);
|
||||
if (r.error === 'private') return { ok: false, hard: true, why: 'points to a private network address' };
|
||||
if (r.error) return { ok: false, why: 'could not be reached (' + r.error + ')' };
|
||||
if (r.status >= 300 && r.status < 400 && r.location) {
|
||||
let next; try { next = new URL(r.location, cur).toString(); } catch (e) { return { ok: false, hard: true, why: 'redirects somewhere invalid' }; }
|
||||
if (!/^https:\/\//i.test(next)) return { ok: true, status: r.status, host: hostOf(next), moved: !sameSite(hostOf(next), start), note: 'redirects to plain http' };
|
||||
cur = next; continue;
|
||||
}
|
||||
const fin = hostOf(cur);
|
||||
if (r.status === 403 || r.status === 429) return { ok: true, status: r.status, host: fin, moved: !sameSite(fin, start), wall: true };
|
||||
if (r.status >= 400) return { ok: false, hard: r.status === 404 || r.status === 410, status: r.status, why: 'answered ' + r.status };
|
||||
return { ok: true, status: r.status, host: fin, moved: !sameSite(fin, start) };
|
||||
}
|
||||
return { ok: false, why: 'redirects too many times' };
|
||||
}
|
||||
|
||||
// flags: [] from myheads.validate; pr: probe() answer (or { skipped: true } when probing is off); prev: the packet's last check
|
||||
function verdict(flags, pr, prev) {
|
||||
const why = (flags || []).slice();
|
||||
if (pr && pr.skipped) return { state: why.length ? 'yellow' : 'green', why, probed: false };
|
||||
if (!pr || !pr.ok) {
|
||||
const miss = ((prev && prev.misses) || 0) + 1;
|
||||
const r = (pr && pr.why) || 'could not be checked';
|
||||
// a packet that was green yesterday gets one miss as yellow (sites go down for a night); planting always needs a working link
|
||||
if (prev && prev.state === 'green' && !(pr && pr.hard) && miss < 2) return { state: 'yellow', why: why.concat(['recheck: ' + r]), misses: miss, probed: true };
|
||||
return { state: 'red', why: why.concat(['link ' + r]), misses: miss, probed: true };
|
||||
}
|
||||
if (pr.http) why.push('not https');
|
||||
if (pr.moved) why.push('redirects to another site (' + pr.host + ')');
|
||||
if (pr.wall) why.push('the site answered ' + pr.status + ' to the checker (may be a bot wall)');
|
||||
return { state: why.length ? 'yellow' : 'green', why, misses: 0, probed: true, status: pr.status || null };
|
||||
}
|
||||
|
||||
module.exports = { probe, verdict, hostOf, sameSite, sample };
|
||||
@@ -0,0 +1,80 @@
|
||||
// LinkSpin tracking on saved referral links (Marty 2026-11-15 "Yes this sounds great": every saved program link auto-becomes a
|
||||
// LinkSpin tracked link; the DownlineHydra / ViralAdSource module, here keyed by saved ID instead of by text ad).
|
||||
// When a member saves their ID in a packet, LinkSpin makes (or updates) a tracked link on that member's own LinkSpin account (every
|
||||
// hub member has one through join-all), source "YourProgramBuilder", sub-id = the packet (id 'ypb<packet>'), so LinkSpin Reports show
|
||||
// the clicks. /go/<packet> then sends to the tracked link, which lands on the member's own referral link. Per saved ID the member can
|
||||
// switch tracking off. Fail soft: if LinkSpin does not answer, or does not know this partner yet, the plain link is used and the
|
||||
// sweep tries again later. A tracked link is used only while it points at the member's current link.
|
||||
// The call: POST LS_URL/api/partner/<LS_PARTNER>/links, X-Net-Ts + X-Net-Sig = hex HMAC-SHA256('net.v1.' + ts + newline + raw body)
|
||||
// with NETWORK_SSO_SECRET. OFF unless LS_TRACK=1 (staging: off; LinkSpin needs a `ypb` PARTNER_LINKS entry first).
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
|
||||
let C = null, store = null, seedbed = null; const st = { ensured: 0, failed: 0, noAccount: 0, lastError: null, lastOkAt: 0, sweeps: 0 };
|
||||
const cache = new Map();
|
||||
const SITE = () => String(process.env.LS_PARTNER || 'ypb').trim();
|
||||
function init(cfg, st0, sb) { C = cfg; store = st0; seedbed = sb; }
|
||||
const base = () => String(process.env.LS_TRACK_URL || (C && C.lsBase) || '').replace(/\/+$/, '');
|
||||
const on = () => !!(C && process.env.LS_TRACK === '1' && String(process.env.NETWORK_SSO_SECRET || '').trim().length >= 32 && base());
|
||||
|
||||
async function post(body, ms) {
|
||||
const sec = String(process.env.NETWORK_SSO_SECRET || '').trim();
|
||||
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex');
|
||||
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), ms || 8000);
|
||||
try {
|
||||
const r = await fetch(base() + '/api/partner/' + SITE() + '/links', { method: 'POST', body: raw, signal: ac.signal, headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } });
|
||||
const j = await r.json().catch(() => ({})); return r.ok ? j : { error: j.error || 'LinkSpin answered ' + r.status };
|
||||
} catch (e) { return { error: 'LinkSpin did not answer.' }; } finally { clearTimeout(t); }
|
||||
}
|
||||
const nameOf = s => { const m = store.member(s.owner); return m && m.username ? String(m.username) : null; };
|
||||
const linkOf = (s, p) => p && s.refId ? seedbed.fill(p, s.refId) : '';
|
||||
function state(s, p) {
|
||||
if (!s) return null;
|
||||
if (s.track === false) return 'off';
|
||||
if (s.ls && s.ls.url === linkOf(s, p) && s.ls.link) return 'tracked';
|
||||
if (!nameOf(s)) return 'no-username';
|
||||
if (s.lsNoAccount && s.lsTry && Date.now() - s.lsTry < 86400000) return 'no-account';
|
||||
return on() ? 'pending' : 'off-site';
|
||||
}
|
||||
const wants = (s, p) => s && p && p.status === 'live' && s.refId && s.track !== false && !(s.ls && s.ls.url === linkOf(s, p) && s.ls.link) && !!nameOf(s);
|
||||
function dest(s, p) { return s && p && s.track !== false && s.ls && s.ls.link && s.ls.url === linkOf(s, p) ? s.ls.link : null; }
|
||||
const keep = s => store.putSave(s.packetId, s.owner, {});
|
||||
|
||||
async function ensureSave(s) {
|
||||
const p = s && store.packet(s.packetId);
|
||||
if (!on() || !wants(s, p)) return { skipped: true };
|
||||
const username = nameOf(s); const url = linkOf(s, p);
|
||||
const r = await post({ username, op: 'ensure', links: [{ id: 'ypb' + p.id, name: p.name, url }] });
|
||||
s.lsTry = Date.now();
|
||||
if (r.error) { st.failed++; st.lastError = String(r.error).slice(0, 160); s.lsErr = st.lastError; keep(s); return r; }
|
||||
if (r.account === false) { st.noAccount++; s.lsNoAccount = true; delete s.lsErr; keep(s); return r; }
|
||||
const l = r.links && r.links['ypb' + p.id];
|
||||
if (!l) { st.failed++; s.lsErr = String((r.errors && r.errors['ypb' + p.id]) || 'no link').slice(0, 160); keep(s); return r; }
|
||||
s.ls = { code: l.code, link: l.link, url, at: Date.now() }; delete s.lsErr; delete s.lsNoAccount;
|
||||
st.ensured++; st.lastOkAt = Date.now(); cache.delete(username.toLowerCase()); keep(s);
|
||||
return { ok: true, link: l.link };
|
||||
}
|
||||
async function sweep(max) {
|
||||
if (!on()) return 0; st.sweeps++; let n = 0;
|
||||
const backoff = Number(process.env.LS_RETRY_MS || 600000);
|
||||
for (const s of store.saves()) {
|
||||
if (n >= (max || 25)) break;
|
||||
const p = store.packet(s.packetId); if (!wants(s, p)) continue;
|
||||
if (s.lsTry && Date.now() - s.lsTry < (s.lsNoAccount ? 86400000 : backoff)) continue;
|
||||
n++; const r = await ensureSave(s).catch(() => ({ error: 'x' }));
|
||||
if (r && r.error === 'LinkSpin did not answer.') break;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
async function clicks(username) {
|
||||
if (!on() || !username) return null;
|
||||
const k = String(username).toLowerCase();
|
||||
const hit = cache.get(k); if (hit && Date.now() - hit.at < Number(process.env.LS_CACHE_MS || 300000)) return hit.v;
|
||||
const r = await post({ username, op: 'stats' }, 3000);
|
||||
const v = r.error || r.account === false ? null : (r.stats || {});
|
||||
cache.set(k, { at: Date.now(), v }); if (cache.size > 20000) cache.clear();
|
||||
return v;
|
||||
}
|
||||
function view() { return Object.assign({ on: on(), base: base(), partner: SITE() }, st); }
|
||||
module.exports = { init, ensureSave, sweep, clicks, dest, state, view, on };
|
||||
@@ -0,0 +1,101 @@
|
||||
// MY HEADS (Marty 2026-11-15): programs a member adds themselves (name, link, short description, category), shown to their
|
||||
// downline next to the wild heads. Free members: 1. Pro members: 4. Pure functions, no I/O, unit-tested in qa/unit.test.cjs.
|
||||
//
|
||||
// The link is either
|
||||
// - a template with {id} where the referral ID goes (https://mailer.example/?ref={id}) plus the owner's own ID: their downline
|
||||
// can then save their own ID for it, and a visitor sees the nearest saved ID up the line, ending at the owner's; or
|
||||
// - a full referral URL: everyone below sees exactly that link.
|
||||
// Checks before a head goes live (the old site auto-approved; we keep auto-approve but hold anything that looks wrong for the
|
||||
// admin queue): http(s) only, a real public hostname, no IP address, no shorteners, no network sites (they are heads already),
|
||||
// no program that is already a wild head (use the builder entry), no obviously spammy words, no links in the description.
|
||||
'use strict';
|
||||
const net = require('net');
|
||||
|
||||
const ID_RE = /^[A-Za-z0-9_.@+-]{1,64}$/;
|
||||
const PH = /\{(id|affil[a-z]*id)\}/gi;
|
||||
const PH1 = /\{(id|affil[a-z]*id)\}/i;
|
||||
const BAD_HOST = /(^|\.)(localhost|local|internal|lan|home|corp|onion|test|invalid|example)$/i;
|
||||
const SHORTENERS = /(^|\.)(bit\.ly|tinyurl\.com|t\.co|goo\.gl|is\.gd|cutt\.ly|ow\.ly|rebrand\.ly|shorturl\.at|rb\.gy|s\.id|t\.ly|v\.gd|bl\.ink|tiny\.cc|mylnks\.xyz|linktr\.ee|shorte\.st|adf\.ly|bitly\.com)$/i;
|
||||
// network sites are core heads, never "my heads" (and RM Circle stays a wild head only)
|
||||
const NETWORK = ['instantadpay.com', 'linkspin.app', 'downlinebanners.com', 'viralbannerblitz.com', 'viraladblitz.com', 'viraladsource.com', 'stackpol.com', 'earnerscorner.com',
|
||||
'downlinehydra.com', 'yourprogrambuilder.com', '5xyourteam.com', 'downlinescaler.com', 'cryptoteambuild.com', 'rmcircle.team', 'saasy.top', 'banner-line.com', 'polhunter.com'];
|
||||
const SPAM = /\b(casino|betting|porn|xxx|viagra|cialis|escort|payday loan|loan offer|forex signal|binary option|guaranteed (profit|income|returns?)|double your|get rich|make \$?\d+|\d+% (daily|per day|a day)|hyip|ponzi|crack(ed)? software|free followers)\b/i;
|
||||
|
||||
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, '').replace(/\.$/, ''); } catch (e) { return ''; } };
|
||||
const within = (h, list) => list.some(d => h === d || h.endsWith('.' + d));
|
||||
const DASHES = new RegExp('[' + String.fromCharCode(0x2013, 0x2014) + ']', 'g');
|
||||
const clean = (s, max) => String(s == null ? '' : s).replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(DASHES, '-').replace(/\s+/g, ' ').trim().slice(0, max);
|
||||
|
||||
// -> { error } or { ok, url (the template or full link, {affiliateid} normalized to {id}), template: bool, host }
|
||||
function checkLink(raw, ctx) {
|
||||
const s = String(raw || '').trim();
|
||||
if (!s) return { error: 'Paste your referral link.' };
|
||||
if (s.length > 500) return { error: 'That link is too long (500 characters max).' };
|
||||
if (/[\s<>"'`\\]/.test(s)) return { error: 'That link has spaces or characters a web address cannot have.' };
|
||||
const tpl = PH1.test(s); const probe = s.replace(PH, 'x');
|
||||
let u; try { u = new URL(probe); } catch (e) { return { error: 'That is not a valid web address. Start it with https://' }; }
|
||||
if (!/^https?:$/.test(u.protocol)) return { error: 'The link must start with https:// (or http://).' };
|
||||
if (u.username || u.password) return { error: 'The link cannot contain a username or password.' };
|
||||
const h = u.hostname.toLowerCase().replace(/\.$/, '');
|
||||
if (net.isIP(h.replace(/^\[|\]$/g, ''))) return { error: 'Use the program\'s domain name, not an IP address.' };
|
||||
if (!h.includes('.') || BAD_HOST.test(h) || !/^[a-z0-9.-]+$/.test(h)) return { error: 'The link must point to a public website.' };
|
||||
if (/\{(id|affil[a-z]*id)\}/i.test(s.split('?')[0].split('/').slice(0, 3).join('/'))) return { error: 'Put {id} in the path or after ?, not in the domain.' };
|
||||
if (SHORTENERS.test(h)) return { error: 'Use the program\'s real address, not a link shortener.' };
|
||||
const bare = h.replace(/^www\./, '');
|
||||
if (within(bare, NETWORK.concat((ctx && ctx.networkHosts) || []))) return { error: 'That is a network site. It is already a head of the hydra for everyone, with your sponsor line.' };
|
||||
if (ctx && ctx.wildHosts && within(bare, ctx.wildHosts)) return { error: 'That program is already a wild head in the builder. Save your ID for it in My wild heads instead.', wild: true };
|
||||
return { ok: true, url: s.replace(PH, '{id}'), template: tpl, host: bare };
|
||||
}
|
||||
|
||||
// a whole my head from the editor. -> { error, field } or { ok, head: { name, url, template, myId, desc, cat, host }, flags: [] }
|
||||
// flags = reasons to hold it for the admin instead of going live (an approved head is never re-held for the same text)
|
||||
function validate(b, ctx) {
|
||||
const L = Object.assign({ name: 40, desc: 160 }, ctx && ctx.limits);
|
||||
const name = clean(b.name, L.name + 1);
|
||||
if (name.length < 2) return { error: 'Give the program a name (2 to ' + L.name + ' characters).', field: 'name' };
|
||||
if (name.length > L.name) return { error: 'Keep the name to ' + L.name + ' characters.', field: 'name' };
|
||||
const desc = clean(b.desc, L.desc + 1);
|
||||
if (desc.length > L.desc) return { error: 'Keep the description to ' + L.desc + ' characters.', field: 'desc' };
|
||||
const lk = checkLink(b.url, ctx); if (lk.error) return Object.assign({ field: 'url' }, lk);
|
||||
let myId = '';
|
||||
if (lk.template) {
|
||||
myId = String(b.myId == null ? '' : b.myId).trim();
|
||||
if (!myId) return { error: 'Your link has {id} in it: type your own referral ID too, so your link works.', field: 'myId' };
|
||||
if (!ID_RE.test(myId)) return { error: 'Your referral ID can only have letters, numbers and . _ - @ +', field: 'myId' };
|
||||
}
|
||||
const cats = (ctx && ctx.cats) || [];
|
||||
const other = cats.find(c => /^other\b/i.test(String(c.short || c.name || ''))); // the seeded "Other programs", else 'other'
|
||||
const cat = cats.some(c => String(c.id) === String(b.cat)) ? String(b.cat) : other ? String(other.id) : 'other';
|
||||
const flags = [];
|
||||
const text = name + ' ' + desc;
|
||||
if (SPAM.test(text) || SPAM.test(lk.url)) flags.push('spam words');
|
||||
if (/https?:\/\/|www\.|\.[a-z]{2,6}\//i.test(desc)) flags.push('link in description');
|
||||
if (name.replace(/[^A-Za-z]/g, '').length >= 6 && name === name.toUpperCase()) flags.push('all caps');
|
||||
if (/(.)\1{5,}/.test(text) || /[!?$]{3,}/.test(text)) flags.push('shouting');
|
||||
if (lk.url.startsWith('http://')) flags.push('not https');
|
||||
return { ok: true, head: { name, url: lk.url, template: lk.template, myId, desc, cat, host: lk.host }, flags };
|
||||
}
|
||||
|
||||
// the link a head points at for someone: a template with the ID filled, or the full link
|
||||
function fill(head, id) { return head.template ? String(head.url).replace(PH, encodeURIComponent(String(id))) : String(head.url); }
|
||||
function homeUrl(head) { try { const u = new URL(String(head.url).replace(PH, 'x')); return u.origin + '/'; } catch (e) { return ''; } }
|
||||
|
||||
const quota = (isPro, C) => isPro ? C.pro : C.free;
|
||||
// the heads that count as shown for an owner: live ones, oldest first, at most the quota (the rest wait: over quota, or held)
|
||||
function shown(list, q) { return list.filter(h => h.status === 'live').sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0)).slice(0, Math.max(0, q)); }
|
||||
const used = list => list.filter(h => h.status !== 'removed').length;
|
||||
|
||||
// how deep a viewer sits below an owner in a chain entry: a signed-in member's chain starts at their sponsor (depth 1 = sponsor);
|
||||
// a page or ?ref= visitor's chain starts at the page owner (depth 0) and the visitor would join one level below them
|
||||
const levelsBelow = (entry, by) => by === 'sponsor' ? entry.depth : entry.depth + 1;
|
||||
const visibleAt = (entry, by, depth) => levelsBelow(entry, by) <= depth;
|
||||
|
||||
// a template head's link for a viewer: the nearest saved ID among the people between the viewer and the owner, else the owner's
|
||||
// chainBelow: chain entries nearer than the owner, nearest first; idOf(entry, headId) -> saved ID or ''
|
||||
function linkFor(head, ownerEntry, chainBelow, idOf) {
|
||||
if (!head.template) return { url: head.url, by: ownerEntry.username || null, depth: ownerEntry.depth, own: true };
|
||||
for (const p of chainBelow || []) { const id = idOf(p, head.id); if (id) return { url: fill(head, id), by: p.username || null, depth: p.depth, own: false }; }
|
||||
return { url: fill(head, head.myId), by: ownerEntry.username || null, depth: ownerEntry.depth, own: true };
|
||||
}
|
||||
|
||||
module.exports = { checkLink, validate, fill, homeUrl, quota, shown, used, levelsBelow, visibleAt, linkFor, hostOf, NETWORK, SPAM, SHORTENERS, ID_RE };
|
||||
@@ -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,106 @@
|
||||
// Shared network knowledge, site side (Marty 2026-11-15: every network site's chatbot answers about the whole network, with its
|
||||
// own site first). This site publishes its own knowledge-base entries to the network hub and reads the merged set back:
|
||||
// PUT HUB_URL/v1/kb {name, url, entries} replaces this site's set (the hub skips a set it already holds)
|
||||
// GET HUB_URL/v1/kb signed over an empty body, If-None-Match: the last version -> 304 when nothing changed
|
||||
// Signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + "\n" + raw body)), like hubreport.js.
|
||||
// The merged set is kept in memory and in DATA_DIR/netkb-cache.json (a MySQL document through docstore where the site has
|
||||
// DOCSTORE_URL; written only when the version changes), so a hub outage at boot still answers about the other sites.
|
||||
// Off when HUB_URL or a 32+ character HUB_SECRET is missing, or NETKB=0: the chatbot then answers about this site only.
|
||||
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline
|
||||
// Banners, Stack POL). Keep them identical.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const REFRESH_MS = 10 * 60 * 1000;
|
||||
let O = null; // { dataDir, site, name, url, netId, entries: async () => [...], linkFor: (url) => link }
|
||||
let merged = { version: '', sites: {}, entries: [] }, loadedAt = 0, publishedHash = '', pubTimer = null, timer = null;
|
||||
const stats = { published: 0, publishErrors: 0, reads: 0, notModified: 0, readErrors: 0, lastError: null, lastPublishAt: 0, lastReadAt: 0 };
|
||||
|
||||
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const secret = () => String(process.env.HUB_SECRET || '').trim();
|
||||
const siteName = () => String(process.env.HUB_SITE || (O && O.site) || '').trim();
|
||||
const enabled = () => process.env.NETKB !== '0' && !!hubUrl() && secret().length >= 32 && !!siteName();
|
||||
const cacheFile = () => (O && O.dataDir ? path.join(O.dataDir, 'netkb-cache.json') : null);
|
||||
|
||||
async function call(method, route, body, headers) {
|
||||
const raw = body === undefined ? '' : JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(15000),
|
||||
headers: Object.assign({ 'Content-Type': 'application/json', 'X-Hub-Site': siteName(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, headers || {}) });
|
||||
let j = null; if (r.status !== 304) { try { j = await r.json(); } catch (e) {} }
|
||||
return { status: r.status, body: j };
|
||||
}
|
||||
|
||||
// the entries this site shares: what the chatbot's knowledge base holds, minus the instant-answer patterns (those stay home)
|
||||
const shape = e => ({ id: String(e.id), title: e.title, questions: (e.questions || []).slice(0, 15), answer: e.answer, tags: (e.tags || []).slice(0, 15), link: e.link || (O && O.url) || undefined });
|
||||
async function publish() {
|
||||
if (!enabled() || !O || typeof O.entries !== 'function') return { skipped: true };
|
||||
const entries = (await O.entries()).filter(e => e && e.id && e.answer && !e.deleted).map(shape);
|
||||
const body = { name: O.name, url: O.url, entries };
|
||||
const h = crypto.createHash('sha1').update(JSON.stringify(body)).digest('hex');
|
||||
if (h === publishedHash) return { same: true };
|
||||
try {
|
||||
const r = await call('PUT', '/v1/kb', body);
|
||||
if (r.status !== 200) { stats.publishErrors++; stats.lastError = 'publish ' + r.status + ' ' + ((r.body && r.body.error) || ''); return { error: stats.lastError }; }
|
||||
publishedHash = h; stats.published++; stats.lastPublishAt = Date.now();
|
||||
return r.body;
|
||||
} catch (e) { stats.publishErrors++; stats.lastError = 'publish ' + e.message; return { error: e.message }; }
|
||||
}
|
||||
// an admin edit: publish a few seconds later (several quick edits go as one)
|
||||
function publishSoon() { if (pubTimer) return; pubTimer = setTimeout(() => { pubTimer = null; publish().catch(() => {}); }, 5000); if (pubTimer.unref) pubTimer.unref(); }
|
||||
|
||||
function readCache() {
|
||||
const f = cacheFile(); if (!f) return;
|
||||
try { const d = JSON.parse(fs.readFileSync(f, 'utf8')); if (d && Array.isArray(d.entries)) { merged = d; loadedAt = 0; } } catch (e) {}
|
||||
}
|
||||
function writeCache() {
|
||||
const f = cacheFile(); if (!f) return;
|
||||
try { fs.writeFileSync(f + '.tmp', JSON.stringify(merged)); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('netkb cache', e.message); }
|
||||
}
|
||||
async function refresh() {
|
||||
if (!enabled()) return { skipped: true };
|
||||
try {
|
||||
const r = await call('GET', '/v1/kb', undefined, merged.version ? { 'If-None-Match': '"' + merged.version + '"' } : {});
|
||||
stats.lastReadAt = Date.now();
|
||||
if (r.status === 304) { stats.notModified++; loadedAt = Date.now(); return { same: true }; }
|
||||
if (r.status !== 200 || !r.body || !Array.isArray(r.body.entries)) { stats.readErrors++; stats.lastError = 'read ' + r.status; return { error: stats.lastError }; }
|
||||
merged = { version: String(r.body.version || ''), sites: r.body.sites || {}, entries: r.body.entries }; loadedAt = Date.now(); stats.reads++;
|
||||
writeCache();
|
||||
return { version: merged.version, count: merged.entries.length };
|
||||
} catch (e) { stats.readErrors++; stats.lastError = 'read ' + e.message; return { error: e.message }; }
|
||||
}
|
||||
|
||||
// other sites' entries, ready for the chatbot's index: id "<site>:<id>", plus where they come from and the link to send people to
|
||||
function remote() {
|
||||
const me = siteName(); const out = [];
|
||||
for (const e of merged.entries || []) {
|
||||
if (!e || e.site === me) continue;
|
||||
const s = (merged.sites || {})[e.site] || {};
|
||||
const url = s.url || e.link || '';
|
||||
out.push({ id: e.site + ':' + e.id, title: e.title, questions: e.questions || [], answer: e.answer, tags: e.tags || [],
|
||||
site: e.site, siteName: s.name || e.site, siteUrl: url, go: (O && typeof O.linkFor === 'function' && url ? O.linkFor(url) : '') || url });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// the network's sites as the hub knows them (name, link), this one left out
|
||||
function sites() {
|
||||
const me = siteName();
|
||||
return Object.entries(merged.sites || {}).filter(([k]) => k !== me).map(([k, s]) => ({ site: k, name: s.name || k, url: s.url || '', go: (O && typeof O.linkFor === 'function' && s.url ? O.linkFor(s.url) : '') || s.url || '', count: s.count || 0 }));
|
||||
}
|
||||
|
||||
// opts: { dataDir, site (hub site id), name, url, entries: async () => [...], linkFor: url => tracked link }
|
||||
function init(opts) {
|
||||
O = opts || {}; readCache();
|
||||
if (!enabled()) return;
|
||||
const first = setTimeout(async () => { await publish().catch(() => {}); await refresh().catch(() => {}); }, Math.max(0, Number(process.env.NETKB_FIRST_MS) || 8000));
|
||||
if (first.unref) first.unref();
|
||||
timer = setInterval(async () => { await refresh().catch(() => {}); if (!publishedHash) await publish().catch(() => {}); }, Math.max(1000, Number(process.env.NETKB_REFRESH_MS) || REFRESH_MS));
|
||||
if (timer.unref) timer.unref();
|
||||
}
|
||||
function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt }, stats); }
|
||||
function _set(m) { merged = m; } // tests
|
||||
|
||||
const version = () => merged.version || '';
|
||||
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, _set };
|
||||
@@ -0,0 +1,61 @@
|
||||
// The network sites list for the footer's "Part of the network" line (Marty 2026-11-14 trust pack).
|
||||
// One source: the hub's public GET /v1/network-sites (HUB_URL). Cached 10 minutes, refreshed in the background, never waits on a
|
||||
// slow hub (2.5 s timeout), and falls back to the same built-in list. Never RM Circle, never the games.
|
||||
// The same file lives in every network site (InstantAdPay, LinkSpin, Downline Banners, VBB, ViralAdBlitz, Stack POL).
|
||||
const FALLBACK = [
|
||||
{ id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' },
|
||||
{ id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' },
|
||||
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' },
|
||||
{ id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' },
|
||||
{ id: 'viraladblitz', name: 'ViralAdBlitz', url: 'https://viraladblitz.com' },
|
||||
{ id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
|
||||
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }
|
||||
];
|
||||
const TTL = 10 * 60 * 1000;
|
||||
let cache = { at: 0, list: FALLBACK, from: 'fallback' };
|
||||
let inflight = null;
|
||||
|
||||
const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, '');
|
||||
function clean(list) {
|
||||
if (!Array.isArray(list)) return null;
|
||||
const ok = list.filter(s => s && typeof s.name === 'string' && /^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(s.url || '')))
|
||||
.slice(0, 30).map(s => ({ id: String(s.id || s.name).toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 30), name: String(s.name).slice(0, 60), url: String(s.url).replace(/\/+$/, '') }));
|
||||
return ok.length ? ok : null;
|
||||
}
|
||||
function refresh() {
|
||||
if (inflight || process.env.NETWORK_SITES_HUB === '0') return inflight;
|
||||
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500);
|
||||
inflight = fetch(hubUrl() + '/v1/network-sites', { signal: ac.signal })
|
||||
.then(r => (r.ok ? r.json() : null))
|
||||
.then(j => { const l = clean(j); if (l) cache = { at: Date.now(), list: l, from: 'hub' }; else cache.at = Date.now(); })
|
||||
.catch(() => { cache.at = Date.now() - TTL + 60 * 1000; }) // hub down: try again in a minute, keep the last good list
|
||||
.finally(() => { clearTimeout(t); inflight = null; });
|
||||
return inflight;
|
||||
}
|
||||
function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list; }
|
||||
// Tracked links (Marty 2026-11-14: "make sure each of these sites is its own traffic source and link spun so we can track it"): each
|
||||
// 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.
|
||||
// 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', viraladsource: 'nwvas', fivex: 'nw5x', downlinehydra: 'nwdh', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
||||
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 ''; } };
|
||||
function selfId(req, l) {
|
||||
const env = String(process.env.NETWORK_SITE_ID || '').trim().toLowerCase(); if (env) return env;
|
||||
const h = String((req && req.headers && (req.headers['x-forwarded-host'] || req.headers.host)) || '').split(',')[0].trim().toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '');
|
||||
const m = h && (l || list()).find(s => hostOf(s.url) === h); return m ? m.id : '';
|
||||
}
|
||||
// the LinkSpin-tracked link to site `id` sent from site `from` (from = id: the site's own promo kit); extra = { s1: member username, s2: one path segment }
|
||||
function tracked(id, from, extra) {
|
||||
const code = CODES[id]; if (!code || !from) return '';
|
||||
const q = new URLSearchParams({ src: from }); for (const [k, v] of Object.entries(extra || {})) if (v) q.set(k, String(v));
|
||||
return linksBase() + '/r/' + code + '?' + q.toString();
|
||||
}
|
||||
function withGo(l, me) { return l.map(s => { const go = me && s.id !== me ? tracked(s.id, me) : ''; return go ? Object.assign({}, s, { go }) : s; }); }
|
||||
// GET /api/network-sites: public, cacheable, the same answer on every page
|
||||
function handle(req, res) {
|
||||
const l = list();
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' });
|
||||
res.end(JSON.stringify(withGo(l, selfId(req, l))));
|
||||
}
|
||||
module.exports = { list, handle, refresh, tracked, selfId, withGo, CODES, FALLBACK, _state: () => cache };
|
||||
@@ -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; } };
|
||||
@@ -0,0 +1,240 @@
|
||||
{
|
||||
"name": "viraladblitz",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "viraladblitz",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"ethers": "^6.13.0",
|
||||
"mysql2": "^3.11.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@adraffy/ens-normalize": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz",
|
||||
"integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@noble/curves": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.2.0.tgz",
|
||||
"integrity": "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "1.3.2"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "1.3.2",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz",
|
||||
"integrity": "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.7.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz",
|
||||
"integrity": "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.19.2"
|
||||
}
|
||||
},
|
||||
"node_modules/aes-js": {
|
||||
"version": "4.0.0-beta.5",
|
||||
"resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.5.tgz",
|
||||
"integrity": "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"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/ethers": {
|
||||
"version": "6.17.0",
|
||||
"resolved": "https://registry.npmjs.org/ethers/-/ethers-6.17.0.tgz",
|
||||
"integrity": "sha512-BpyrpIPJ3ydEVow8zGaz1DuPS7YU8DcWxuBnY9a0UA/lvAPwrMr+EPXsfrul628SRaekPNeIM4UFh/91GWZang==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/ethers-io/"
|
||||
},
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://www.buymeacoffee.com/ricmoo"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@adraffy/ens-normalize": "1.11.1",
|
||||
"@noble/curves": "1.2.0",
|
||||
"@noble/hashes": "1.3.2",
|
||||
"@types/node": "22.7.5",
|
||||
"aes-js": "4.0.0-beta.5",
|
||||
"tslib": "2.7.0",
|
||||
"ws": "8.21.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"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/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-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/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/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/sql-escaper": {
|
||||
"version": "1.5.2",
|
||||
"resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.5.2.tgz",
|
||||
"integrity": "sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg==",
|
||||
"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/tslib": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
|
||||
"integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.19.8",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz",
|
||||
"integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.21.0",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
|
||||
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": ">=5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "viraladsource",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "ViralAdSource (viraladsource.com rebuild): free text ads that spread by reshares, each ad with its own family tree; rewards for verified results only (VASShop on Polygon).",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "node --watch server.js",
|
||||
"qa": "node qa/e2e.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"ethers": "^6.13.0",
|
||||
"mysql2": "^3.11.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Promo kit (the VBB / ViralAdSource pattern): the ONE place the YourProgramBuilder creatives and swipe copy live. Published as a
|
||||
// public JSON feed, GET /api/promo-kit?u=<network username or wallet>, read by /promote and by InstantAdPay's promo center
|
||||
// ("Network sites"). Facts come from config.js. Copy rules: a directory of programs, not income; nothing is promised; no em dashes;
|
||||
// no earnings caps; wallets = "SafePal or any other crypto wallet".
|
||||
// Creatives: public/art/kit/ypb-<angle>-<shape>.png, rendered by tools/kit-art.mjs (neutral names: no size tokens, no ad words).
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const C = require('./config').get();
|
||||
const netsites = require('./netsites');
|
||||
|
||||
const KIT_DIR = path.join(__dirname, 'public', 'art', 'kit');
|
||||
const SHAPES = { tile: [125, 125, 'Square button'], strip: [468, 60, 'Strip'], leader: [728, 90, 'Leaderboard'], box: [300, 250, 'Box'], panel: [336, 280, 'Large box'],
|
||||
tower: [160, 600, 'Skyscraper'], social: [1200, 630, 'Social share'], square: [1080, 1080, 'Square post'] };
|
||||
const ANGLES = { plant: 'Bring your program', grow: 'Save your ID, grow the bed', spot: 'Spotlight a packet' };
|
||||
|
||||
function copy() {
|
||||
return {
|
||||
lines: [
|
||||
'Bring your program. The network grows it. Plant it free in the Seed Bed and let members save their IDs. {{LINK}}',
|
||||
'One place to find the programs your network actually joins, with your own referral link first for everyone you bring. {{LINK}}',
|
||||
'YourProgramBuilder: plant a program, save your IDs, and see which ones grow into the Crypto Team Build Network builder. {{LINK}}'
|
||||
],
|
||||
headlines: ['Bring your program. The network grows it.', 'Plant it free in the Seed Bed', 'Your link first, for everyone you bring', 'Watch a program sprout'],
|
||||
email: { subject: 'Plant your program in the Seed Bed',
|
||||
body: ['Hi,', '', 'YourProgramBuilder is the network\'s Seed Bed. Plant a program you like (its name and your referral link), and members across the network save their own ID in it.', '',
|
||||
'Anyone who comes through you sees your link first. When ' + C.reviewSaves + ' members have saved an ID, the program goes to review for the Crypto Team Build Network builder, and every saved ID moves with it.', '',
|
||||
'It is a directory of programs, not an income opportunity. Read each program\'s own terms before you join.', '', '{{LINK}}'].join('\n') },
|
||||
posts: [
|
||||
'Most builders are a list one person edits. The Seed Bed is open: plant a program, the network saves IDs in it, and the ones that grow are reviewed for the CTB builder. Free.' + '\n\n{{LINK}}',
|
||||
'Spotlight a packet: $' + C.spotlight.usd + ' one-time for ' + C.spotlight.views.toLocaleString('en-US') + ' guaranteed views at the top of the Seed Bed. Paid in POL with SafePal or any other crypto wallet.' + '\n\n{{LINK}}'
|
||||
]
|
||||
};
|
||||
}
|
||||
const NOTE = 'A directory of programs, not an income opportunity. Nothing is promised.';
|
||||
const REF_RE = /^(?:[A-Za-z0-9_.-]{2,40}|0x[0-9a-fA-F]{40})$/;
|
||||
const base = () => 'https://' + C.site;
|
||||
let files = null;
|
||||
function creatives() {
|
||||
if (files) return files;
|
||||
let names = []; try { names = fs.readdirSync(KIT_DIR).filter(f => /^ypb-[a-z]+-[a-z]+\.png$/.test(f)); } catch (e) {}
|
||||
const out = [];
|
||||
for (const angle of Object.keys(ANGLES)) for (const shape of Object.keys(SHAPES)) {
|
||||
const f = 'ypb-' + angle + '-' + shape + '.png'; if (!names.includes(f)) continue;
|
||||
const [w, h, label] = SHAPES[shape];
|
||||
out.push({ key: angle + '-' + shape, angle, angleLabel: ANGLES[angle], shape, label, w, h, url: base() + '/art/kit/' + f });
|
||||
}
|
||||
return (files = out);
|
||||
}
|
||||
function kit(u) {
|
||||
const ref = REF_RE.test(String(u || '')) ? String(u) : '';
|
||||
const link = ref && !/^0x/i.test(ref) ? base() + '/' + encodeURIComponent(ref) : base() + '/' + (ref ? '?ref=' + encodeURIComponent(ref) : '');
|
||||
const q = ref ? '?ref=' + encodeURIComponent(ref) : '';
|
||||
// the LinkSpin-tracked network link (netsites CODES) when LinkSpin has one for this site; until then the plain member page
|
||||
const track = seg => netsites.tracked(C.siteId, C.siteId, { s1: ref, s2: seg });
|
||||
const share = (ref && !/^0x/i.test(ref) ? track(ref) : track('')) || link;
|
||||
const fill = s => s.split('{{LINK}}').join(share);
|
||||
const t = copy();
|
||||
return {
|
||||
v: 1, site: C.site, name: C.siteName, updated: '2026-11-17', username: ref || null,
|
||||
tagline: 'Bring your program. The network grows it.',
|
||||
links: [
|
||||
{ key: 'page', label: 'Your page', url: link, tracked: share },
|
||||
{ key: 'plant', label: 'Plant a program', url: base() + '/my' + q + (q ? '&' : '?') + 'tab=plant', tracked: track('plant') || null },
|
||||
{ key: 'ledger', label: 'Live ledger', url: base() + '/ledger' + q, tracked: track('ledger') || null }
|
||||
],
|
||||
linkTemplate: base() + '/{username}', trackedTemplate: netsites.tracked(C.siteId, C.siteId) ? netsites.tracked(C.siteId, C.siteId) + '&s1={username}' : null,
|
||||
creatives: creatives().map(c => Object.assign({}, c, { link: share, html: '<a href="' + share + '" target="_blank" rel="noopener"><img src="' + c.url + '" width="' + c.w + '" height="' + c.h + '" alt="YourProgramBuilder"></a>' })),
|
||||
lines: t.lines.map(fill), headlines: t.headlines, email: { subject: t.email.subject, body: fill(t.email.body) }, posts: t.posts.map(fill),
|
||||
note: NOTE, promotePage: base() + '/promote'
|
||||
};
|
||||
}
|
||||
function handle(req, res, u, sendFile) {
|
||||
if (u.pathname === '/promote' && (req.method === 'GET' || req.method === 'HEAD') && sendFile) { sendFile(res, path.join(__dirname, 'public', 'promote.html')); return true; }
|
||||
if (u.pathname !== '/api/promo-kit') return false;
|
||||
const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type' };
|
||||
if (req.method === 'OPTIONS') { res.writeHead(204, cors); res.end(); return true; }
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
|
||||
res.writeHead(200, Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' }, cors));
|
||||
res.end(JSON.stringify(kit(u.searchParams.get('u')))); return true;
|
||||
}
|
||||
module.exports = { kit, handle, creatives, SHAPES, ANGLES, copy };
|
||||
@@ -0,0 +1,106 @@
|
||||
// Trust pack (Marty 2026-11-14, standing for every network site): live ledger, contract proof, toasts, a Telegram photo card per sale.
|
||||
// - ledger(): every Spotlight (the Purchase events shop.js recorded) with its split read from the receipt: each sponsor level
|
||||
// (kinds 1..5, with the person's place in the compressed line) and the company; plus delivery (views so far). Never an email.
|
||||
// - contract(): live facts for /contract (owner, company, keeper, paused, split, SKU and any pending SKU change with its 48 h
|
||||
// eta), cached 5 minutes. Without a contract (staging) it answers the planned values marked as not deployed.
|
||||
// - Telegram: one photo card per Spotlight to TG_CHAT / TG_PAY_TOPIC (off unless TG_TOKEN and TG_CHAT are set; staging leaves them empty).
|
||||
'use strict';
|
||||
const store = require('./store');
|
||||
const docstore = require('./docstore');
|
||||
|
||||
const CARDS = ['/art/proof/ypb-proof-plate.png', '/art/proof/ypb-proof-bed.png'];
|
||||
const st = { posted: 0, skipped: 0, failed: 0, lastError: null };
|
||||
let C = null, shop = null, wire = null;
|
||||
const sent = new Set();
|
||||
const once = k => { if (sent.has(k)) return false; sent.add(k); if (sent.size > 5000) sent.clear(); return true; };
|
||||
function init(cfg, deps) { C = cfg; shop = deps.shop; wire = deps.wire; }
|
||||
const on = () => !!(process.env.TG_TOKEN && process.env.TG_CHAT);
|
||||
const lc = a => String(a || '').toLowerCase();
|
||||
const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : '';
|
||||
function nameLocal(addr) { const m = store.member(lc(addr)); return m && m.username ? m.username : null; }
|
||||
const who = a => nameLocal(a) ? '@' + nameLocal(a) : short(lc(a));
|
||||
const pol = wei => { const v = Number(BigInt(wei || 0) / 10n ** 12n) / 1e6; return v >= 100 ? v.toFixed(2) : v.toFixed(4); };
|
||||
const usd = cents => '$' + (Number(cents || 0) / 100).toFixed(2);
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c]));
|
||||
const KIND = k => k === 0 ? 'company' : 'level ' + k;
|
||||
|
||||
function split(x) {
|
||||
if (Array.isArray(x.pays) && x.pays.length) return x.pays;
|
||||
return [{ kind: 0, depth: 0, to: lc(C.companyWallet), wei: String(x.companyPaid || '0') }];
|
||||
}
|
||||
function rows() { return Object.entries((store.state() && store.state().purchases) || {}).map(([k, x]) => Object.assign({ key: k, tx: k.split(':')[0] }, x)); }
|
||||
function ledger(n) {
|
||||
const lim = Math.min(200, Math.max(1, Number(n) || 50));
|
||||
const list = rows().map(x => {
|
||||
const p = x.packetId ? store.packet(x.packetId) : null; const dv = wire.spotView(x);
|
||||
return { kind: 'spotlight', tx: x.tx, at: (x.blockAt ? x.blockAt * 1000 : x.at) || null, orderId: x.orderId, buyer: x.buyer, buyerName: nameLocal(x.buyer), qty: x.qty, views: x.views,
|
||||
usdCents: x.usdCents, weiPaid: x.weiPaid, packet: p ? { id: p.id, name: p.name } : null, delivery: { views: dv.views, delivered: dv.delivered, status: dv.status },
|
||||
pays: split(x).map(q => ({ kind: q.kind, label: KIND(q.kind), depth: q.depth, to: q.to, name: q.to ? nameLocal(q.to) : null, wei: q.wei, failed: q.failed || undefined })) };
|
||||
}).sort((a, b) => (b.at || 0) - (a.at || 0));
|
||||
let wei = 0n, cents = 0, spots = 0, levels = 0n;
|
||||
for (const x of rows()) { spots += Number(x.qty) || 1; cents += Number(x.usdCents) || 0; try { wei += BigInt(x.weiPaid || 0); } catch (e) {} for (const q of split(x)) if (q.kind >= 1 && q.kind <= 5) { try { levels += BigInt(q.wei); } catch (e) {} } }
|
||||
return { contract: C.contractAddress || null, explorer: C.explorer, items: list.slice(0, lim), totals: { spotlights: spots, orders: list.length, usdCents: cents, weiPaid: wei.toString(), levelsWei: levels.toString() } };
|
||||
}
|
||||
|
||||
let cCache = null;
|
||||
async function contract() {
|
||||
if (cCache && Date.now() - cCache.at < 300000) return cCache.v;
|
||||
const v = { address: C.contractAddress || null, chainId: C.chainId, explorer: C.explorer, deployed: false, planned: true,
|
||||
split: { levelBps: C.split.levelBps, maxDepth: C.split.maxDepth }, spotlight: { usd: C.spotlight.usd, views: C.spotlight.views }, skuDelayHours: 48,
|
||||
company: lc(C.companyWallet), verified: { sourcify: process.env.VERIFIED_SOURCIFY === '1', polygonscan: process.env.VERIFIED_POLYGONSCAN === '1' }, ownerNote: "Marty's Tangem hardware wallet", live: false };
|
||||
if (shop && shop.watching()) {
|
||||
try {
|
||||
const one = f => shop.call(f).then(r => r[0]);
|
||||
const [owner, company, keeper, paused, totalOwed, orderCount, delay] = await Promise.all(['owner', 'company', 'keeper', 'paused', 'totalOwed', 'orderCount', 'SKU_DELAY'].map(one));
|
||||
const r = await shop.liveRules(C.spotlight.sku);
|
||||
Object.assign(v, { owner: lc(owner), company: lc(company), keeper: lc(keeper), paused: !!paused, totalOwedWei: totalOwed.toString(), orderCount: Number(orderCount), skuDelayHours: Number(delay) / 3600,
|
||||
live: true, deployed: true, planned: false, readAt: Date.now() });
|
||||
if (r) { v.split = { levelBps: r.levelBps, maxDepth: 20 }; v.sku = r.sku; v.pendingSku = r.pending; }
|
||||
} catch (e) { v.error = 'The chain did not answer just now. Try again in a minute.'; }
|
||||
}
|
||||
cCache = { at: Date.now(), v }; if (v.error) cCache.at = Date.now() - 240000;
|
||||
return v;
|
||||
}
|
||||
|
||||
async function tg(method, body) {
|
||||
const base = String(process.env.TG_API || 'https://api.telegram.org').replace(/\/+$/, '');
|
||||
const b = Object.assign({ chat_id: process.env.TG_CHAT, parse_mode: 'HTML' }, body);
|
||||
if (process.env.TG_PAY_TOPIC) b.message_thread_id = Number(process.env.TG_PAY_TOPIC);
|
||||
const r = await fetch(base + '/bot' + process.env.TG_TOKEN + '/' + method, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(b), signal: AbortSignal.timeout(15000) });
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (!j.ok) { st.failed++; st.lastError = String(j.description || r.status).slice(0, 160); return false; }
|
||||
return true;
|
||||
}
|
||||
function caption(x) {
|
||||
const w = wire.weekStats(); const p = x.packetId ? store.packet(x.packetId) : null;
|
||||
const lines = ['\u{1F331} <b>YourProgramBuilder</b>', '\u{2600}\u{FE0F} ' + esc(who(x.buyer)) + ' spotlighted ' + (p ? '"' + esc(p.name) + '"' : 'a packet') + ' · ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL) · ' + Number(x.views || 0).toLocaleString('en-US') + ' guaranteed views'];
|
||||
for (const q of split(x)) {
|
||||
if (q.kind === 0) lines.push('\u{1F3E6} YourProgramBuilder: ' + pol(q.wei) + ' POL');
|
||||
else lines.push((q.failed ? '⚠️ ' : '\u{1F4B8} ') + 'Level ' + q.kind + ': ' + pol(q.wei) + ' POL → ' + esc(who(q.to)) + (q.failed ? ' (bounced, waits in the contract to claim)' : ''));
|
||||
}
|
||||
lines.push('Paid by the contract in this same transaction.');
|
||||
lines.push('\u{1F4CA} This week: ' + w.spotlights + ' Spotlights · ' + w.saves + ' saved IDs · ' + w.vclicks + ' verified clicks');
|
||||
lines.push('· <a href="' + esc(C.explorer) + '/tx/' + esc(x.tx) + '">Verify on Polygonscan</a> · <a href="https://' + esc(C.site) + '/ledger">Live ledger</a>');
|
||||
return lines.join('\n');
|
||||
}
|
||||
let card = 0;
|
||||
function onPurchase(rec, tx) {
|
||||
const x = Object.assign({ tx }, rec);
|
||||
(async () => {
|
||||
try {
|
||||
const sp = await shop.readSplit(tx, rec.orderId);
|
||||
if (sp) { const S = store.state(); const k = Object.keys(S.purchases || {}).find(k2 => k2.startsWith(lc(tx) + ':') && S.purchases[k2].orderId === rec.orderId);
|
||||
if (k) { Object.assign(S.purchases[k], { pays: sp.pays }); store.save(); } Object.assign(x, { pays: sp.pays }); }
|
||||
} catch (e) {}
|
||||
if (!on()) return;
|
||||
const at = (rec.blockAt ? rec.blockAt * 1000 : rec.at) || Date.now();
|
||||
if (Date.now() - at > 2 * 3600000) { st.skipped++; return; }
|
||||
if (!once('p:' + lc(tx) + ':' + rec.orderId) || !(await docstore.claim('ypbtg:' + lc(tx) + ':' + rec.orderId))) return;
|
||||
const photo = (process.env.TG_PHOTO_BASE ? String(process.env.TG_PHOTO_BASE).replace(/\/+$/, '') : 'https://' + C.site) + CARDS[card++ % CARDS.length];
|
||||
const text = caption(x);
|
||||
let ok = await tg('sendPhoto', { photo, caption: text }); if (!ok) ok = await tg('sendMessage', { text, disable_web_page_preview: true });
|
||||
if (ok) st.posted++;
|
||||
})().catch(e => { st.failed++; st.lastError = String(e.message).slice(0, 160); });
|
||||
}
|
||||
function view() { return Object.assign({ telegram: on(), topic: process.env.TG_PAY_TOPIC || null }, st); }
|
||||
module.exports = { init, ledger, contract, onPurchase, caption, split, view, on, CARDS };
|
||||
@@ -0,0 +1,37 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Admin | YourProgramBuilder</title>
|
||||
<meta name="description" content="YourProgramBuilder admin.">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Admin | YourProgramBuilder"><meta property="og:description" content="YourProgramBuilder admin."><meta property="og:url" content="https://yourprogrambuilder.com/admin">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="" data-no-zones="1">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<div class="page">
|
||||
<h1>Admin</h1>
|
||||
<section class="panel"><div class="row"><input type="text" id="tok" placeholder="Admin token" style="max-width:340px"><button class="btn sm ink" id="go" type="button">Open</button><button class="btn sm" id="recheck" type="button">Recheck links now</button><a class="btn sm" id="exportBtn" href="#">Export approved (JSON)</a></div><p id="status" class="note" hidden></p></section>
|
||||
<section class="panel"><h2>Status</h2><div class="stats" id="aStats"></div><pre id="aRaw" style="white-space:pre-wrap;font-size:12px;max-height:240px;overflow:auto"></pre></section>
|
||||
<section class="panel"><h2>Ready for review</h2><p class="muted">Packets that reached the threshold. Approve to transplant (exported for the CTB builder and DownlineHydra with every saved ID), or reject (stays in the Seed Bed).</p><div id="qReview" class="stack"></div></section>
|
||||
<section class="panel"><h2>Held: link check and reports</h2><div id="qHeld" class="stack"></div></section>
|
||||
<section class="panel"><h2>Transplanted</h2><div id="qApproved" class="stack"></div></section>
|
||||
<section class="panel" id="testBox" hidden><h2>Staging: test members</h2><div class="row"><input type="text" id="tAddr" placeholder="0x wallet" style="max-width:420px"><input type="text" id="tName" placeholder="username" style="max-width:200px"><button class="btn sm" id="tGo" type="button">Mark as a test network member</button></div></section>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/admin.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 7.3 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 492 KiB |
|
After Width: | Height: | Size: 683 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 18 KiB |
@@ -0,0 +1 @@
|
||||
<svg width="34" height="34" viewBox="0 0 34 34" xmlns="http://www.w3.org/2000/svg"><rect x="1" y="1" width="32" height="32" rx="8" fill="#22844A"/><path d="M17 27V15" stroke="#F6FAF1" stroke-width="3" stroke-linecap="round"/><path d="M17 17c0-5 4-8 9-8 0 5-4 8-9 8z" fill="#FFE6A0"/><path d="M17 20c0-4-3-6-8-6 0 4 3 6 8 6z" fill="#F6FAF1"/></svg>
|
||||
|
After Width: | Height: | Size: 347 B |
|
After Width: | Height: | Size: 505 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 506 KiB |
@@ -0,0 +1,40 @@
|
||||
// Admin (Marty): status, the review queue (approve = transplant, reject), held packets (link check yellow / red, reports), the export
|
||||
// for the CTB builder / DownlineHydra, a link recheck, and the staging-only test-member switch. The token stays in this tab only.
|
||||
(function () {
|
||||
const $ = YPB.$, esc = YPB.esc;
|
||||
let tok = ''; try { tok = sessionStorage.getItem('ypb.admin') || ''; } catch (e) {}
|
||||
$('tok').value = tok;
|
||||
const api = (url, body) => fetch(url, body ? { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-admin-token': tok }, body: JSON.stringify(body) } : { headers: { 'x-admin-token': tok } }).then(r => r.json());
|
||||
function row(x, acts) {
|
||||
const chk = x.check ? x.check.state + (x.check.why && x.check.why.length ? ': ' + x.check.why.join('; ') : '') : 'not checked';
|
||||
return '<div class="panel" style="border-width:1.5px"><div class="row" style="justify-content:space-between"><b>No. ' + esc(x.no) + ' ' + esc(x.name) + '</b><span class="mono" style="font-size:12px">' + esc(x.status) + ' / ' + esc(x.stage) + ' / ' + x.saves + ' of ' + x.need + ' saves</span></div>'
|
||||
+ '<p class="muted" style="font-size:14px;margin:6px 0">' + esc(x.desc) + '</p><p style="font-size:13px;margin:0 0 6px"><span class="mono">' + esc(x.url) + '</span> (planter ID ' + esc(x.ownerId || '') + ', @' + esc(x.planter || '?') + ')</p>'
|
||||
+ '<p style="font-size:13px;margin:0 0 6px">Link check: ' + esc(chk) + (x.flags && x.flags.length ? ' | flags: ' + esc(x.flags.join(', ')) : '') + (x.heldWhy ? ' | held: ' + esc(x.heldWhy) : '') + '</p>'
|
||||
+ (x.reports && x.reports.length ? '<p style="font-size:13px;margin:0 0 6px">Reports: ' + x.reports.map(r => esc(r.reason + (r.note ? ' (' + r.note + ')' : '') + ' by ' + r.by)).join('; ') + '</p>' : '')
|
||||
+ '<div class="row"><input type="text" placeholder="note (optional)" data-note="' + x.id + '" style="max-width:260px">' + acts.map(a => '<button class="btn sm" type="button" data-act="' + a + '" data-id="' + x.id + '">' + a + '</button>').join('') + '</div></div>';
|
||||
}
|
||||
async function load() {
|
||||
try { sessionStorage.setItem('ypb.admin', tok); } catch (e) {}
|
||||
const s = await api('/api/admin/status');
|
||||
if (s.error) { YPB.status('Wrong token.', 'err'); return; }
|
||||
YPB.status('', '');
|
||||
$('aStats').innerHTML = [['Shown', s.packets.shown], ['Held', s.packets.held], ['In review', s.packets.review], ['Transplanted', s.packets.approved], ['Dormant', s.packets.dormant], ['Saved IDs', s.saves], ['Members', s.members], ['Old links', s.oldrefs]].map(v => '<div class="stat"><b>' + YPB.n(v[1]) + '</b><span>' + v[0] + '</span></div>').join('');
|
||||
$('aRaw').textContent = JSON.stringify({ config: s.config, shop: s.shop, hub: s.hub, hubLookup: s.hubLookup, sso: s.sso, linkspin: s.linkspin, docstore: s.docstore, adWriter: s.adWriter }, null, 1);
|
||||
$('testBox').hidden = !s.testSwitch;
|
||||
const q = await api('/api/admin/queue');
|
||||
$('qReview').innerHTML = q.review.length ? q.review.map(x => row(x, ['approve', 'reject', 'hold', 'remove'])).join('') : '<p class="muted">Nothing in review.</p>';
|
||||
$('qHeld').innerHTML = q.held.length ? q.held.map(x => row(x, ['show', 'recheck', 'remove'])).join('') : '<p class="muted">Nothing held.</p>';
|
||||
$('qApproved').innerHTML = q.approved.length ? q.approved.map(x => row(x, ['reopen'])).join('') : '<p class="muted">Nothing transplanted yet.</p>';
|
||||
document.querySelectorAll('[data-act]').forEach(b => { b.onclick = async () => {
|
||||
b.disabled = true; const note = (document.querySelector('[data-note="' + b.dataset.id + '"]') || {}).value || '';
|
||||
const r = await api('/api/admin/packet', { id: Number(b.dataset.id), action: b.dataset.act, note }); YPB.status(r.error || 'Done: ' + b.dataset.act, r.error ? 'err' : 'ok'); load(); }; });
|
||||
}
|
||||
$('go').onclick = () => { tok = $('tok').value.trim(); load(); };
|
||||
$('recheck').onclick = async () => { const r = await api('/api/admin/recheck', { max: 50 }); YPB.status(r.error || 'Rechecked ' + r.checked + ' packets.', r.error ? 'err' : 'ok'); load(); };
|
||||
$('exportBtn').onclick = async e => {
|
||||
e.preventDefault(); const r = await api('/api/admin/export?all=1');
|
||||
const blob = new Blob([JSON.stringify(r, null, 1)], { type: 'application/json' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'ypb-transplants-' + new Date().toISOString().slice(0, 10) + '.json'; a.click();
|
||||
};
|
||||
$('tGo').onclick = async () => { const r = await api('/api/admin/test-member', { address: $('tAddr').value.trim(), username: $('tName').value.trim() || undefined }); YPB.status(r.error || 'Marked ' + r.member.address + ' as a test network member.', r.error ? 'err' : 'ok'); };
|
||||
if (tok) load();
|
||||
})();
|
||||
@@ -0,0 +1,37 @@
|
||||
// One-time Spotlights through YPBShop. The server builds the signed buy() call for the signed-in member (POST /api/my/order: the hub
|
||||
// sponsor line + the packet); the member's own wallet sends it. After it confirms the page waits for the watcher to record it.
|
||||
window.YPBBuy = (function () {
|
||||
const fmtPol = (wei, d) => { const k = d || 4; const s = (BigInt(wei) * 10n ** BigInt(k) / 10n ** 18n).toString().padStart(k + 1, '0'); return s.slice(0, -k) + '.' + s.slice(-k); };
|
||||
async function quote(qty) { return YPB.getJSON('/api/quote?qty=' + (qty || 1)); }
|
||||
async function run(o) {
|
||||
const say = o.say || YPB.status;
|
||||
const c = await YPB.getConfig();
|
||||
if (!c.shop || !c.shop.live) throw new Error('Spotlights are not on sale yet.');
|
||||
const me = await YPB.getJSON('/api/me');
|
||||
if (!me.signedIn) throw new Error('Sign in on My packets first.');
|
||||
say('Connecting your wallet...');
|
||||
const addr = String(await YPBWallet.activeAddress(await YPBWallet.connect()) || '').toLowerCase();
|
||||
if (!addr) throw new Error('No wallet connected. Tap Buy again and pick SafePal or any other crypto wallet.');
|
||||
if (addr !== me.address) throw new Error('Your wallet is connected as ' + YPB.short(addr) + ', but your YourProgramBuilder account is ' + YPB.short(me.address) + '. Switch your wallet app to ' + YPB.short(me.address) + ', or sign out and sign in with ' + YPB.short(addr) + '.');
|
||||
const od = await YPB.post('/api/my/order', { qty: o.qty || 1, packetId: o.packetId });
|
||||
if (od.error) throw new Error(od.error);
|
||||
const value = BigInt(od.value);
|
||||
try { const bal = await YPBWallet.balance(addr); if (bal < value) throw new Error('This wallet holds ' + fmtPol(bal) + ' POL. The Spotlight needs about ' + fmtPol(value) + ' POL plus a little gas. Add POL on Polygon and try again.'); }
|
||||
catch (e) { if (/holds/.test(e.message)) throw e; }
|
||||
say('Confirm the payment in your wallet: about ' + fmtPol(value) + ' POL ($' + od.usd + '). Anything above the exact price comes straight back in the same transaction.');
|
||||
const hash = await YPBWallet.sendTx(od.to, od.data, od.value);
|
||||
const link = c.explorer ? c.explorer + '/tx/' + hash : '';
|
||||
say('Payment sent. Waiting for the Polygon network to confirm it...');
|
||||
const r = await YPBWallet.waitTx(hash);
|
||||
if (r.status !== '0x1') throw new Error('The transaction did not go through, so nothing was charged except gas. ' + (link ? 'Details: ' + link : ''));
|
||||
YPB.post('/api/my/paid', {}).catch(() => {});
|
||||
say('Confirmed on Polygon. Your Spotlight shows on My packets within about a minute.', 'ok');
|
||||
for (let i = 0; i < 72; i++) {
|
||||
await new Promise(res => setTimeout(res, 5000));
|
||||
if (i % 4 === 3) YPB.post('/api/my/paid', {}).catch(() => {});
|
||||
try { if (await o.done()) return { hash, link, recorded: true }; } catch (e) {}
|
||||
}
|
||||
return { hash, link, recorded: false };
|
||||
}
|
||||
return { run, quote, fmtPol };
|
||||
})();
|
||||
@@ -0,0 +1,46 @@
|
||||
/* Site assistant widget in the YourProgramBuilder seed catalog look (ypb.css): forest ink header, rounded paper panel, tangerine send, leaf chips.
|
||||
The overrides at the end of this file set the look; the shared widget rules above stay as on every network site. */
|
||||
#scChat{--sc-bg:var(--card,#fff);--sc-ink:var(--ink,#0A1F6B);--sc-sub:var(--sub,#3E4C7A);--sc-head:var(--royal,#0A1F6B);--sc-head-ink:#fff;
|
||||
--sc-accent:var(--red,#E3141E);--sc-accent-ink:#fff;--sc-me:var(--royal2,#12308F);--sc-me-ink:#fff;--sc-bot:var(--tint,#E1EBFF);--sc-line:var(--line,#C9D6F5);
|
||||
--sc-chip:var(--gtint,#FFF3CC);--sc-chip-ink:var(--gold-ink,#7A5B00);--sc-gold:var(--gold,#FFC21A);
|
||||
--sc-font:var(--body,Inter,system-ui,sans-serif);--sc-headfont:var(--head,'Chakra Petch',system-ui,sans-serif);--sc-cut:polygon(0 0,calc(100% - 14px) 0,100% 14px,100% 100%,14px 100%,0 calc(100% - 14px));
|
||||
position:fixed;right:18px;bottom:18px;z-index:80;font-family:var(--sc-font)}
|
||||
#scBtn{width:58px;height:58px;border:0;cursor:pointer;background:var(--sc-accent);color:var(--sc-accent-ink);display:flex;align-items:center;justify-content:center;
|
||||
clip-path:polygon(0 0,calc(100% - 12px) 0,100% 12px,100% 100%,12px 100%,0 calc(100% - 12px));box-shadow:0 6px 18px rgba(6,26,102,.35)}
|
||||
#scBtn:hover{background:#C70F18}
|
||||
#scBtn:focus-visible{outline:3px solid var(--sc-gold);outline-offset:3px}
|
||||
#scChat.open #scBtn{background:var(--sc-head)}
|
||||
/* the panel sets display:flex, which would beat the hidden attribute: closing must win */
|
||||
#scPanel[hidden]{display:none}
|
||||
#scPanel{position:absolute;right:0;bottom:72px;width:370px;max-width:calc(100vw - 32px);height:540px;max-height:calc(100vh - 110px);display:flex;flex-direction:column;
|
||||
background:var(--sc-bg);color:var(--sc-ink);clip-path:var(--sc-cut);border:1px solid var(--sc-line);box-shadow:0 18px 48px rgba(6,26,102,.3)}
|
||||
.sc-head{display:flex;align-items:flex-start;gap:10px;padding:14px 16px;background:var(--sc-head);color:var(--sc-head-ink);border-bottom:3px solid var(--sc-gold)}
|
||||
.sc-head>div{flex:1;min-width:0}
|
||||
.sc-title{display:block;font-family:var(--sc-headfont);font-size:18px;letter-spacing:.02em}
|
||||
.sc-sub{display:block;font-size:12.5px;opacity:.8}
|
||||
#scClose{background:transparent;border:0;color:inherit;font-size:26px;line-height:1;cursor:pointer;padding:0 2px}
|
||||
.sc-msgs{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:9px}
|
||||
.sc-m{max-width:88%;padding:9px 12px;font-size:14.5px;line-height:1.45;word-wrap:break-word;overflow-wrap:anywhere}
|
||||
.sc-m.bot{align-self:flex-start;background:var(--sc-bot);color:var(--sc-ink);clip-path:polygon(0 0,100% 0,100% 100%,8px 100%,0 calc(100% - 8px))}
|
||||
.sc-m.me{align-self:flex-end;background:var(--sc-me);color:var(--sc-me-ink);clip-path:polygon(0 0,calc(100% - 8px) 0,100% 8px,100% 100%,0 100%)}
|
||||
.sc-m a{color:inherit;text-decoration:underline}
|
||||
.sc-m.wait{opacity:.6}
|
||||
.sc-cta{display:inline-block;background:var(--sc-accent);color:var(--sc-accent-ink)!important;text-decoration:none!important;font-weight:700;padding:8px 14px;
|
||||
clip-path:polygon(0 0,calc(100% - 8px) 0,100% 8px,100% 100%,8px 100%,0 calc(100% - 8px))}
|
||||
.sc-handoff{background:transparent!important;padding:0!important}
|
||||
.sc-topics{display:flex;flex-wrap:wrap;gap:6px;padding:0 14px 8px}
|
||||
.sc-topics button{background:var(--sc-chip);color:var(--sc-chip-ink);border:1px solid var(--sc-gold);font:600 12.5px var(--sc-font);padding:5px 10px;cursor:pointer}
|
||||
.sc-input{display:flex;gap:8px;padding:10px 12px;border-top:1px solid var(--sc-line)}
|
||||
.sc-input input{flex:1;min-width:0;border:1px solid var(--sc-line);padding:10px 12px;font:15px var(--sc-font);color:var(--sc-ink);background:#fff}
|
||||
.sc-input input:focus{outline:2px solid var(--blue,#1F66FF);outline-offset:-1px}
|
||||
.sc-input button{background:var(--sc-accent);color:var(--sc-accent-ink);border:0;font:700 14px var(--sc-font);padding:0 16px;cursor:pointer;
|
||||
clip-path:polygon(0 0,calc(100% - 8px) 0,100% 8px,100% 100%,8px 100%,0 calc(100% - 8px))}
|
||||
.sc-human{display:block;text-align:center;font-size:12.5px;color:var(--sc-sub);padding:0 0 10px}
|
||||
@media (max-width:600px){#scChat{right:12px;bottom:12px}#scBtn{width:52px;height:52px}#scPanel{bottom:64px;height:calc(100vh - 100px)}}
|
||||
/* YourProgramBuilder seed catalog look */
|
||||
#scChat{--sc-ink:#12291F;--sc-sub:#4A6457;--sc-head:#12291F;--sc-accent:#F2620F;--sc-accent-ink:#FFFFFF;--sc-me:#1B4A33;--sc-bot:#F6FAF1;--sc-line:#D3E3CB;--sc-chip:#E9F2E2;--sc-chip-ink:#1B6E3C;--sc-gold:#22844A;
|
||||
--sc-font:'Atkinson Hyperlegible',system-ui,sans-serif;--sc-headfont:'Young Serif',Georgia,serif;--sc-cut:none}
|
||||
#scChat #scBtn{clip-path:none;border-radius:50%;box-shadow:0 6px 18px rgba(18,41,31,.35)}
|
||||
#scChat #scBtn:hover{background:#D9540A}
|
||||
#scChat #scPanel{clip-path:none;border-radius:18px;overflow:hidden;border:2px solid #12291F}
|
||||
#scChat .sc-m.bot,#scChat .sc-m.me{clip-path:none;border-radius:14px}#scChat [class*="sc-"]{clip-path:none}#scChat .sc-chip,#scChat button{border-radius:10px}
|
||||
@@ -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=20261115d'; 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,143 @@
|
||||
// Shared page helpers (YPB namespace, the network common.js pattern): header, footer (legal, company line, the network line from the
|
||||
// hub), verified visits, seed-packet cards, toasts of real events, the network ad zones, small formatters. The look lives in ypb.css.
|
||||
window.YPB = (function () {
|
||||
let cfgP = null, vt = null;
|
||||
const I = window.YPBI || {};
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const getConfig = () => cfgP || (cfgP = fetch('/api/config').then(r => r.json()));
|
||||
const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : '';
|
||||
const framed = (() => { try { return window.top !== window.self; } catch (e) { return true; } })();
|
||||
const n = x => Number(x || 0).toLocaleString('en-US');
|
||||
const pct = bps => (Number(bps || 0) / 100).toFixed(Number(bps) % 100 ? 1 : 0) + '%';
|
||||
const usd = c => '$' + (Number(c || 0) / 100).toFixed(2);
|
||||
const month = t => t ? new Date(t).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric' }).toUpperCase() : '';
|
||||
function status(msg, cls, id) { const el = $(id || 'status'); if (!el) return; el.hidden = !msg; el.className = 'note ' + (cls || ''); el.textContent = msg || ''; if (msg) el.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); }
|
||||
async function getJSON(url, opts) { const r = await fetch(url, opts); let j = {}; try { j = await r.json(); } catch (e) {} if (!r.ok && !j.error) j.error = 'Request failed (' + r.status + ')'; j._status = r.status; return j; }
|
||||
const post = (url, body) => getJSON(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
|
||||
const MARK = '<svg width="34" height="34" viewBox="0 0 34 34" aria-hidden="true"><rect x="1" y="1" width="32" height="32" rx="8" fill="var(--leaf)"/><path d="M17 27V15" stroke="var(--paper)" stroke-width="3" stroke-linecap="round"/><path d="M17 17c0-5 4-8 9-8 0 5-4 8-9 8z" fill="var(--butter)"/><path d="M17 20c0-4-3-6-8-6 0 4 3 6 8 6z" fill="var(--paper)"/></svg>';
|
||||
function renderNav(active) {
|
||||
const h = document.createElement('header'); h.className = 'top wrap';
|
||||
const links = [['/', 'Seed Bed'], ['/my?tab=plant', 'Plant a program'], ['/transplanted', 'Transplanted'], ['/spotlight', 'Spotlight'], ['/guides', 'Guides'], ['/my', 'My packets']];
|
||||
h.innerHTML = '<a class="skip" href="#main">Skip to content</a><a class="brand" href="/" aria-label="YourProgramBuilder, the Seed Bed">' + MARK + '<span>YourProgramBuilder</span></a>'
|
||||
+ '<nav class="links" aria-label="Main">' + links.map(l => '<a href="' + l[0] + '"' + (l[0] === active ? ' aria-current="page"' : '') + '>' + l[1] + '</a>').join('') + '</nav>'
|
||||
+ '<a class="signin" id="navSign" href="/my">Sign in with the network</a>';
|
||||
document.body.prepend(h);
|
||||
getConfig().then(c => { if (c.staging) { const b = document.createElement('div'); b.className = 'stage-bar wrap'; b.textContent = 'Staging copy for testing. No payouts, no mail, no contract: nothing here is real money.'; h.after(b); } }).catch(() => {});
|
||||
getJSON('/api/me').then(m => { if (m.signedIn) { const a = $('navSign'); if (a) a.textContent = m.username ? '@' + m.username : short(m.address); } }).catch(() => {});
|
||||
if (framed) document.querySelectorAll('a[href^="/my"]').forEach(a => { a.target = '_blank'; a.rel = 'noopener'; });
|
||||
}
|
||||
// the click relay: placement + the visitor's verified token once their visit has verified (+ the member whose page this is)
|
||||
const goHref = (id, p, r) => '/go/' + id + '?p=' + encodeURIComponent(p || 'site') + (r ? '&r=' + encodeURIComponent(r) : '') + (vt ? '&v=' + vt : '');
|
||||
function decorate() { document.querySelectorAll('a[data-go]').forEach(a => { a.href = goHref(a.dataset.go, a.dataset.p, a.dataset.r); }); }
|
||||
const stageTag = x => x.stage === 'approved' ? '<span class="tag ok">Transplanted</span>' : x.stage === 'review' ? '<span class="tag ok">Ready for review</span>' : '';
|
||||
// a seed packet. o = { place, r (member), spot, extra (html) }
|
||||
function packetCard(x, o) {
|
||||
o = o || {}; const spot = o.spot || !!x.spotlight;
|
||||
const pctv = Math.min(100, Math.round(100 * (x.saves || 0) / (x.need || 25)));
|
||||
const tags = [];
|
||||
if (x.spotlight) tags.push('<span class="tag sp">Spotlight ' + n(x.spotlight.delivered) + ' / ' + n(x.spotlight.views) + ' views</span>');
|
||||
tags.push(stageTag(x));
|
||||
if (x.check === 'green') tags.push('<span class="tag ok">Link checked</span>');
|
||||
tags.push('<span class="tag">' + (x.cost === 'free' ? 'Free to join' : esc(x.costText || 'Paid')) + '</span>');
|
||||
if (x.contract) tags.push('<span class="tag">Contract listed</span>');
|
||||
const by = x.mine ? 'your ID is saved' : x.own ? 'you planted this' : x.stage === 'review' ? 'in Marty\'s review queue' : x.planter ? 'planted by @' + esc(x.planter) : 'sponsor link first';
|
||||
return '<article class="pk' + (spot ? ' spotlit' : '') + '"><div class="fold"></div><div class="body">'
|
||||
+ '<div class="no"><span>PACKET No. ' + esc(x.no) + ' · SOWN ' + esc(month(x.sownAt)) + '</span>' + (I.iconOrganic || '') + '</div>'
|
||||
+ '<div class="meta">' + tags.filter(Boolean).join('') + '</div>'
|
||||
+ '<h3><a href="/p/' + x.id + (o.r ? '?r=' + encodeURIComponent(o.r) : '') + '">' + esc(x.name) + '</a></h3><p>' + esc(x.desc) + '</p>'
|
||||
+ '<div class="meter"><div class="lbl"><span>Saved IDs</span><span>' + n(x.saves) + ' / ' + n(x.need) + '</span></div><div class="bar" role="img" aria-label="' + n(x.saves) + ' of ' + n(x.need) + ' saved IDs"><span style="width:' + pctv + '%"></span></div></div>'
|
||||
+ '<div class="row"><a class="save' + (x.mine ? ' done' : '') + '" href="/p/' + x.id + (o.r ? '?r=' + encodeURIComponent(o.r) : '') + '#save">' + (I.iconSprout || '') + (x.mine ? 'ID saved' : 'Save my ID') + '</a>'
|
||||
+ '<a class="by" data-go="' + x.id + '" data-p="' + esc(o.place || 'card') + '"' + (o.r ? ' data-r="' + esc(o.r) + '"' : '') + ' target="_blank" rel="noopener sponsored nofollow" href="' + goHref(x.id, o.place, o.r) + '">Visit ' + esc(x.host) + '</a></div>'
|
||||
+ (o.extra || '') + '</div></article>';
|
||||
}
|
||||
// the page's data and its verified visit: packets come with a ticket; after visitSeconds of the page being visible the visit is sent once
|
||||
async function wire(page, q) {
|
||||
const src = document.referrer || '';
|
||||
let hunt = /[?&#]ph=/.test(location.search + location.hash); try { hunt = hunt || !!sessionStorage.getItem('ph.token'); } catch (e) {}
|
||||
const d = await getJSON('/api/wire?page=' + encodeURIComponent(page) + (q || '') + (src ? '&src=' + encodeURIComponent(src) : '') + (hunt ? '&hunt=1' : ''));
|
||||
if (d.ticket) {
|
||||
const need = (d.seconds || 6) * 1000; let seen = 0, last = Date.now(), sent = false;
|
||||
const iv = setInterval(async () => {
|
||||
const now = Date.now(); if (document.visibilityState === 'visible') seen += now - last; last = now;
|
||||
if (!sent && seen >= need) { sent = true; clearInterval(iv); const r = await post('/api/visit/seen', { ticket: d.ticket, visibleMs: seen }).catch(() => ({})); if (r.vt) { vt = r.vt; decorate(); } document.dispatchEvent(new CustomEvent('ypb:verified', { detail: r })); }
|
||||
}, 500);
|
||||
document.addEventListener('visibilitychange', () => { last = Date.now(); });
|
||||
}
|
||||
return d;
|
||||
}
|
||||
function spotRow(el, d, r) { if (!el) return; const f = d.spotlights || []; el.hidden = !f.length; if (f.length) el.querySelector('.bed').innerHTML = f.map(x => packetCard(x, { place: 'spot', spot: true, r })).join(''); }
|
||||
const NET = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
|
||||
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['viraladblitz', 'ViralAdBlitz', 'https://viraladblitz.com'], ['viraladsource', 'ViralAdSource', 'https://viraladsource.com'], ['downlinehydra', 'DownlineHydra', 'https://downlinehydra.com'],
|
||||
['fivex', '5xYourTeam', 'https://5xyourteam.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(a => ({ id: a[0], name: a[1], url: a[2] }));
|
||||
const HERE = { id: 'yourprogrambuilder', name: 'YourProgramBuilder', url: 'https://yourprogrambuilder.com' };
|
||||
function netLine(el) {
|
||||
if (!el) return;
|
||||
const paint = list => { el.innerHTML = '<b>Part of the network</b> One account across the network: ' + list.map(s => s.id === 'yourprogrambuilder'
|
||||
? '<span class="here" aria-current="page">' + esc(s.name) + '</span>' : '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>').join(''); };
|
||||
paint(NET.concat([HERE]));
|
||||
fetch('/api/network-sites').then(r => r.json()).then(l => { if (Array.isArray(l) && l.length) paint(l.some(s => s.id === 'yourprogrambuilder') ? l : l.concat([HERE])); }).catch(() => {});
|
||||
}
|
||||
function renderFooter() {
|
||||
const f = document.createElement('footer'); f.className = 'foot wrap';
|
||||
f.innerHTML = '<p><b>YourProgramBuilder</b> The Seed Bed: bring your program, the network grows it. A directory of programs, not an income opportunity. Nothing is promised.</p>'
|
||||
+ '<p><a href="/">Seed Bed</a><a href="/my?tab=plant">Plant a program</a><a href="/transplanted">Transplanted</a><a href="/spotlight">Spotlight</a><a href="/promote">Promote</a><a href="/guides">Guides</a><a href="/guides/faq">FAQ</a></p>'
|
||||
+ '<p class="netline"></p>'
|
||||
+ '<p>© 2026 TrustClickz <a href="/terms">Terms</a><a href="/disclaimer">Earnings disclaimer</a><a href="/privacy">Privacy</a><a href="/contract">Contract</a><a href="/ledger">Ledger</a><a href="https://instantadpay.com/support?from=yourprogrambuilder" target="_blank" rel="noopener">Support</a></p>';
|
||||
document.body.appendChild(f);
|
||||
netLine(f.querySelector('.netline'));
|
||||
toasts();
|
||||
}
|
||||
let toastsOn = false;
|
||||
function toasts() {
|
||||
if (toastsOn || /^\/admin/.test(location.pathname)) return; toastsOn = true;
|
||||
const seen = new Set(); let first = true;
|
||||
const box = document.createElement('div'); box.className = 'toasts'; box.setAttribute('aria-live', 'polite'); document.body.appendChild(box);
|
||||
const who = c => c.name ? '@' + esc(c.name) : 'A member';
|
||||
const show = c => {
|
||||
const el = document.createElement('a'); el.className = 'toast';
|
||||
if (c.kind === 'spotlight') { el.href = '/ledger'; el.innerHTML = '<b>' + who(c) + ' spotlighted ' + esc(c.packet || 'a packet') + '</b><br><span>split on chain by the contract</span>'; }
|
||||
else if (c.kind === 'save') { el.href = '/p/' + c.id; el.innerHTML = '<b>' + who(c) + ' saved an ID</b><br><span>in ' + esc(c.packet) + '</span>'; }
|
||||
else if (c.kind === 'review') { el.href = '/p/' + c.id; el.innerHTML = '<b>' + esc(c.packet) + ' is ready for review</b><br><span>enough members saved an ID</span>'; }
|
||||
else { el.href = '/p/' + c.id; el.innerHTML = '<b>' + who(c) + ' planted a program</b><br><span>' + esc(c.packet) + '</span>'; }
|
||||
box.appendChild(el); requestAnimationFrame(() => el.classList.add('in'));
|
||||
setTimeout(() => { el.classList.remove('in'); setTimeout(() => el.remove(), 400); }, 7000);
|
||||
};
|
||||
const tick = async () => {
|
||||
const d = await getJSON('/api/recent').catch(() => null); const all = (d && d.items) || [];
|
||||
const fresh = all.filter(c => !seen.has(c.key)); all.forEach(c => seen.add(c.key));
|
||||
const list = first ? fresh.slice(0, 1) : fresh.reverse(); first = false;
|
||||
list.slice(0, 3).forEach((c, i) => setTimeout(() => show(c), 1500 + i * 8000));
|
||||
};
|
||||
tick(); setInterval(tick, 25000);
|
||||
}
|
||||
const polOf = (w, d) => { try { const k = BigInt(w || 0); const v = Number(k / 10n ** 12n) / 1e6; return v.toFixed(d != null ? d : (v >= 100 ? 2 : 4)); } catch (e) { return '0'; } };
|
||||
const when = t => t ? new Date(t).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : '';
|
||||
async function copy(text, btn) { try { await navigator.clipboard.writeText(text); if (btn) { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => { btn.textContent = o; }, 1600); } } catch (e) { if (btn) { btn.textContent = 'Select the text to copy it'; } } }
|
||||
return { I, MARK, $, esc, getConfig, short, framed, status, getJSON, post, n, pct, usd, month, renderNav, renderFooter, packetCard, wire, spotRow, decorate, goHref, polOf, when, copy };
|
||||
})();
|
||||
// every page: header, footer and the numbers from /api/config
|
||||
(function () {
|
||||
const boot = () => {
|
||||
YPB.renderNav(document.body.dataset.nav || ''); YPB.renderFooter();
|
||||
document.querySelectorAll('[data-icon]').forEach(el => { const svg = YPB.I[el.dataset.icon]; if (svg) el.outerHTML = svg; });
|
||||
YPB.getConfig().then(c => {
|
||||
const lv = (c.split || {}).levelBps || []; const sp = c.spotlight || {};
|
||||
const V = { need: String(c.reviewSaves), spotUsd: '$' + sp.usd, spotViews: YPB.n(sp.views), sponsor: YPB.pct(lv[0]), levels: lv.slice(1).map(YPB.pct).join(' / '), lvlEach: YPB.pct(lv[1]),
|
||||
company: YPB.pct(10000 - lv.reduce((t, x) => t + x, 0)), recheck: String(c.recheckHours), deliverDays: String(sp.deliverDays), quota: String(c.plantQuota) };
|
||||
document.querySelectorAll('[data-cfg]').forEach(el => { const k = el.dataset.cfg; if (V[k] != null) el.textContent = V[k]; });
|
||||
// network ad zones (the ViralAdSource pattern): LinkSpin zones on Marty's LinkSpin account, ids from LS_ZONES (none until made)
|
||||
const Z = c.zones || {}; if (!Z.footWide || /^\/admin/.test(location.pathname) || document.body.dataset.noZones) return;
|
||||
const zone = (el, id) => { el.className = 'net-zone'; el.style.cssText = 'margin:18px auto;text-align:center;max-width:100%'; el.innerHTML = '<div style="font-size:11px;letter-spacing:1px;opacity:.7;margin-bottom:4px">Network</div>'; const s = document.createElement('script'); s.async = true; s.src = 'https://linkspin.app/z.js'; s.setAttribute('data-zone', id); el.appendChild(s); };
|
||||
const za = document.createElement('div'); document.querySelector('footer.foot').before(za); zone(za, window.innerWidth >= 760 ? Z.footWide : (Z.footPhone || Z.footWide));
|
||||
if (location.pathname === '/ledger' && Z.ledger) { const d = document.createElement('div'); const t = document.getElementById('ledgerBox'); if (t) { t.after(d); zone(d, Z.ledger); } }
|
||||
}).catch(() => {});
|
||||
};
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
|
||||
})();
|
||||
// Network Weekend ribbon: netweekend.js paints it only while a network event is live (dates from the hub through /api/network-deals)
|
||||
(function () {
|
||||
if (/^\/admin/.test(location.pathname)) return;
|
||||
try { if (window.top !== window) return; } catch (e) { return; }
|
||||
var s = document.createElement('script'); s.src = '/assets/netweekend.js?v=20261117'; s.defer = true; s.setAttribute('data-site', 'yourprogrambuilder'); document.head.appendChild(s);
|
||||
})();
|
||||
@@ -0,0 +1,20 @@
|
||||
// The Seed Bed (front page): the Spotlight row, the bed of packets with its filters, the verified visit, the PolHunter slot.
|
||||
(async function () {
|
||||
const $ = YPB.$;
|
||||
let d = { bed: [] };
|
||||
try { d = await YPB.wire('front'); } catch (e) {}
|
||||
YPB.spotRow($('spots'), d);
|
||||
const bed = d.bed || [];
|
||||
let f = 'all';
|
||||
const keep = x => f === 'all' || (f === 'sprouting' && x.stage === 'sprouting') || (f === 'review' && x.stage === 'review') || (f === 'free' && x.cost === 'free') || (f === 'crypto' && !!x.contract);
|
||||
const paint = () => {
|
||||
const l = bed.filter(keep);
|
||||
$('bedList').innerHTML = l.length ? l.map(x => YPB.packetCard(x, { place: 'bed' })).join('')
|
||||
: '<p class="empty">' + (bed.length ? 'No packet matches that filter yet.' : 'The Seed Bed is ready for its first program. <a href="/my?tab=plant">Plant yours, free</a>.') + '</p>';
|
||||
YPB.decorate();
|
||||
};
|
||||
document.querySelectorAll('.filters .chip').forEach(b => { b.onclick = () => { f = b.dataset.f; document.querySelectorAll('.filters .chip').forEach(x => x.setAttribute('aria-pressed', String(x === b))); paint(); }; });
|
||||
paint();
|
||||
// PolHunter embed (the network pattern): the find code hides in one of the three steps. The mission is added in polhunter.com/admin at go-live.
|
||||
const ph = document.createElement('script'); ph.async = true; ph.src = 'https://polhunter.com/embed.js'; ph.setAttribute('data-slots', '3'); ph.setAttribute('data-selector', '#how .step'); document.body.appendChild(ph);
|
||||
})();
|
||||
@@ -0,0 +1,14 @@
|
||||
// A member's page (/<username>): the packets they planted or saved an ID in, each opening with their link (the ref tag is set by the server).
|
||||
(async function () {
|
||||
const $ = YPB.$, esc = YPB.esc;
|
||||
const name = decodeURIComponent(location.pathname.slice(1).replace(/\/$/, ''));
|
||||
const d = await YPB.wire('member', '&u=' + encodeURIComponent(name)).catch(() => ({ error: 'x' }));
|
||||
if (d.error || !d.member) { $('mList').innerHTML = '<p class="empty">' + esc(d.error || 'No network member by that name.') + '</p>'; return; }
|
||||
const m = d.member;
|
||||
$('mTitle').textContent = '@' + m.username + '\'s programs';
|
||||
document.title = '@' + m.username + '\'s programs | YourProgramBuilder';
|
||||
if (d.joinUrl) $('mJoin').href = d.joinUrl;
|
||||
$('mList').innerHTML = m.packets.length ? m.packets.map(x => YPB.packetCard(x, { place: 'member', r: m.username })).join('') : '<p class="empty">@' + esc(m.username) + ' has not saved an ID in the Seed Bed yet. <a href="/">Browse the Seed Bed</a>.</p>';
|
||||
YPB.spotRow($('spots'), d, m.username);
|
||||
YPB.decorate();
|
||||
})();
|
||||
@@ -0,0 +1,98 @@
|
||||
// My packets (the member dashboard): sign in (network account through the hub, or wallet), my packet (status, link check, sprout
|
||||
// meter, edit / remove), dormant old programs to confirm, the planting form with the AI writer, my saved IDs, Spotlights and earnings.
|
||||
(async function () {
|
||||
const $ = YPB.$, esc = YPB.esc;
|
||||
YPB.wire('other').catch(() => {});
|
||||
const c = await YPB.getConfig().catch(() => ({}));
|
||||
const me = await YPB.getJSON('/api/me');
|
||||
const qs = new URLSearchParams(location.search);
|
||||
if (!me.signedIn) {
|
||||
try { const ss = await YPB.getJSON('/api/sso/status'); if (ss && ss.check) { location.replace('/sso/start?mode=check&to=' + encodeURIComponent(location.pathname + location.search)); return; } } catch (e) {}
|
||||
$('signin').hidden = false; if (c.joinUrl) $('joinLink').href = c.joinUrl;
|
||||
$('walletBtn').onclick = async () => {
|
||||
try { YPB.status('Check your wallet for the sign-in message.', '', 'status'); await YPBWallet.signIn(); location.reload(); }
|
||||
catch (e) { YPB.status(String(e && e.message || e).slice(0, 300), 'err'); }
|
||||
};
|
||||
return;
|
||||
}
|
||||
$('dash').hidden = false;
|
||||
$('logout').onclick = async () => { await YPB.post('/api/auth/logout'); location.reload(); };
|
||||
$('logoutAll').onclick = async () => { $('logoutAll').disabled = true; await YPB.post('/api/auth/logout-everywhere'); location.reload(); };
|
||||
const tabs = document.querySelectorAll('[data-tab]');
|
||||
const show = t => { tabs.forEach(b => b.setAttribute('aria-pressed', String(b.dataset.tab === t))); document.querySelectorAll('[data-pane]').forEach(p => { p.hidden = p.dataset.pane !== t; }); };
|
||||
tabs.forEach(b => { b.onclick = () => show(b.dataset.tab); });
|
||||
show(['plant', 'saved', 'spot'].includes(qs.get('tab')) ? qs.get('tab') : 'packets');
|
||||
(c.cats || []).forEach(k => { const o = document.createElement('option'); o.value = k.id; o.textContent = k.name; $('cat').appendChild(o); });
|
||||
$('cat').value = '0';
|
||||
const costPicked = () => document.querySelector('input[name=cost]:checked').value;
|
||||
document.querySelectorAll('input[name=cost]').forEach(r => { r.onchange = () => { $('costRow').hidden = costPicked() !== 'paid'; }; });
|
||||
|
||||
let d = null;
|
||||
const CHECK = { green: '<span class="tag ok">Link check green</span>', yellow: '<span class="tag warn">Link check yellow: waiting for a person</span>', red: '<span class="tag bad">Link check red: not shown</span>' };
|
||||
const stageTag = x => x.stage === 'review' ? '<span class="tag ok">In review</span>' : x.stage === 'approved' ? '<span class="tag ok">Transplanted</span>' : x.stage === 'rejected' ? '<span class="tag">Not added this time</span>' : '';
|
||||
function packetBox(x) {
|
||||
const pctv = Math.min(100, Math.round(100 * x.saves / x.need));
|
||||
const notes = x.check && x.check.why && x.check.why.length ? '<p class="muted" style="font-size:14px">Check notes: ' + esc(x.check.why.join('; ')) + '</p>' : '';
|
||||
return '<div class="panel" style="border-width:1.5px;margin-top:10px">'
|
||||
+ '<div class="row" style="justify-content:space-between"><h3 style="font-size:22px">' + (x.status === 'live' ? '<a href="/p/' + x.id + '">' + esc(x.name) + '</a>' : esc(x.name)) + '</h3><span class="mono" style="font-size:12px">PACKET No. ' + esc(x.no) + '</span></div>'
|
||||
+ '<p class="meta" style="margin:8px 0">' + (CHECK[x.check && x.check.state] || '') + (x.status === 'held' ? '<span class="tag warn">Held' + (x.heldWhy ? ': ' + esc(x.heldWhy) : '') + '</span>' : '') + stageTag(x) + '</p>'
|
||||
+ notes + (x.decidedNote ? '<p class="muted" style="font-size:14px">Note: ' + esc(x.decidedNote) + '</p>' : '')
|
||||
+ '<div class="meter"><div class="lbl"><span>Saved IDs</span><span>' + YPB.n(x.saves) + ' / ' + YPB.n(x.need) + '</span></div><div class="bar"><span style="width:' + pctv + '%"></span></div></div>'
|
||||
+ '<p class="muted" style="font-size:14px;margin-top:8px">' + YPB.n(x.views) + ' verified views, ' + YPB.n(x.clicks) + ' verified clicks' + (x.spotlight ? ', Spotlight ' + YPB.n(x.spotlight.delivered) + ' / ' + YPB.n(x.spotlight.views) + ' views' : '') + '</p>'
|
||||
+ '<div class="row"><button class="btn sm" type="button" data-edit="' + x.id + '">Edit</button>' + (x.stage !== 'approved' ? '<button class="btn sm" type="button" data-remove="' + x.id + '">Remove</button>' : '') + (x.status === 'live' ? '<a class="btn sm" href="/spotlight?p=' + x.id + '">Spotlight it</a>' : '') + '</div></div>';
|
||||
}
|
||||
async function load() {
|
||||
d = await YPB.getJSON('/api/my');
|
||||
if (d.error) return YPB.status(d.error, 'err');
|
||||
$('who').innerHTML = 'Signed in as ' + (d.username ? '<b>@' + esc(d.username) + '</b>' : esc(YPB.short(d.address))) + (d.netVerified ? ', network member' : ', <a href="' + esc(d.joinUrl) + '">join the network free</a> to plant and save IDs') + (d.test ? ' (staging test member)' : '');
|
||||
$('myStats').innerHTML = [['Packets planted', d.packets.length], ['IDs saved', d.saved.length], ['Clicks to my links', d.saved.reduce((t, s) => t + (s.clicks || 0), 0)], ['Spotlights bought', d.spotlights.length]].map(s => '<div class="stat"><b>' + YPB.n(s[1]) + '</b><span>' + s[0] + '</span></div>').join('');
|
||||
if (d.page) { $('pageBox').hidden = false; $('pageUrl').textContent = d.page; $('copyPage').onclick = e => YPB.copy(d.page, e.target); }
|
||||
$('myPackets').innerHTML = d.packets.length ? d.packets.map(packetBox).join('') : '<p class="muted">Nothing planted yet. <a href="/my?tab=plant" data-go-tab="plant">Plant a program</a>.</p>';
|
||||
document.querySelectorAll('[data-go-tab]').forEach(a => { a.onclick = e => { e.preventDefault(); show(a.dataset.goTab); }; });
|
||||
document.querySelectorAll('[data-edit]').forEach(b => { b.onclick = () => edit(d.packets.find(x => x.id === Number(b.dataset.edit))); });
|
||||
document.querySelectorAll('[data-remove]').forEach(b => { b.onclick = async () => { b.disabled = true; const r = await YPB.post('/api/my/packet/remove', { id: Number(b.dataset.remove) }); if (r.error) { b.disabled = false; return YPB.status(r.error, 'err'); } load(); }; });
|
||||
if (d.dormant && d.dormant.length) {
|
||||
$('dormant').hidden = false;
|
||||
$('dormant').innerHTML = '<b>Your programs from the old YourProgramBuilder</b><br>' + d.dormant.map(x => esc(x.name) + ' <span class="muted">(' + esc(x.url) + ')</span> <button class="btn sm" type="button" data-dorm="' + x.id + '">Confirm it</button>').join('<br>')
|
||||
+ '<p class="muted" style="font-size:14px;margin:8px 0 0">Confirming opens the planting form with your old link: put {id} where your ID goes, then plant it. It counts as your packet.</p>';
|
||||
document.querySelectorAll('[data-dorm]').forEach(b => { b.onclick = () => { const x = d.dormant.find(y => y.id === Number(b.dataset.dorm)); reset(); $('dormantId').value = x.id; $('url').value = x.url; $('name').value = x.name; $('plantTitle').textContent = 'Confirm your old program'; show('plant'); }; });
|
||||
} else $('dormant').hidden = true;
|
||||
$('savedRows').innerHTML = d.saved.length ? d.saved.map(s => '<tr><td>' + (s.shown ? '<a href="/p/' + s.packetId + '">' + esc(s.name) + '</a>' : esc(s.name) + ' <span class="muted">(not shown now)</span>') + '</td><td class="mono">' + esc(s.refId) + '</td><td class="n">' + YPB.n(s.saves) + '</td><td class="n">' + YPB.n(s.clicks) + '</td><td>' + esc(s.stage) + '</td></tr>').join('')
|
||||
: '<tr><td colspan="5" class="muted">Open any packet in the <a href="/#bed">Seed Bed</a> and tap Save my ID.</td></tr>';
|
||||
$('spotRows').innerHTML = d.spotlights.length ? d.spotlights.map(b => '<tr><td>' + esc(YPB.when(b.at)) + '</td><td>Packet ' + esc(b.packetId || '?') + '</td><td class="n">' + YPB.n(b.delivered) + ' / ' + YPB.n(b.views) + '</td><td>' + esc(b.status) + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">No Spotlights bought yet.</td></tr>';
|
||||
$('earnStats').innerHTML = '<div class="stat"><b>' + YPB.polOf(d.earned.wei) + '</b><span>POL paid to you by Spotlights</span></div>';
|
||||
$('earnRows').innerHTML = d.earned.items.length ? d.earned.items.map(i => '<tr><td>' + esc(YPB.when(i.at)) + '</td><td>Level ' + i.kind + '</td><td class="n">' + YPB.polOf(i.wei) + ' POL' + (i.failed ? ' (waiting to claim)' : '') + '</td><td>' + (i.buyerName ? '@' + esc(i.buyerName) : '') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">Nothing yet. Nothing is promised.</td></tr>';
|
||||
}
|
||||
function reset() { $('plantForm').reset(); $('editId').value = ''; $('dormantId').value = ''; $('cancelEdit').hidden = true; $('costRow').hidden = true; $('plantTitle').textContent = 'Plant a program'; $('plantBtn').textContent = 'Plant it'; $('cat').value = '0'; }
|
||||
function edit(x) {
|
||||
reset(); $('editId').value = x.id; $('url').value = x.url; $('myId').value = x.ownerId || ''; $('name').value = x.name; $('desc').value = x.desc;
|
||||
document.querySelector('input[name=cost][value=' + (x.cost === 'paid' ? 'paid' : 'free') + ']').checked = true; $('costRow').hidden = x.cost !== 'paid'; $('costText').value = x.costText || '';
|
||||
$('contract').value = x.contract || ''; $('cat').value = x.cat || '0'; $('plantTitle').textContent = 'Edit packet No. ' + x.no; $('plantBtn').textContent = 'Save the changes'; $('cancelEdit').hidden = false; show('plant');
|
||||
}
|
||||
$('cancelEdit').onclick = () => { reset(); show('packets'); };
|
||||
$('plantForm').onsubmit = async e => {
|
||||
e.preventDefault(); $('plantBtn').disabled = true; YPB.status('Checking your link...', '');
|
||||
const body = { id: $('editId').value || undefined, dormant: $('dormantId').value || undefined, url: $('url').value.trim(), myId: $('myId').value.trim(), name: $('name').value, desc: $('desc').value,
|
||||
cost: costPicked(), costText: $('costText').value, contract: $('contract').value.trim(), cat: $('cat').value };
|
||||
const r = await YPB.post('/api/my/plant', body); $('plantBtn').disabled = false;
|
||||
if (r.error) { YPB.status(r.error, 'err'); const f = r.field && $(r.field); if (f && f.focus) f.focus(); return; }
|
||||
const pk = r.packet; const no = String(pk.id).padStart(3, '0');
|
||||
YPB.status(pk.check === 'green' ? 'Planted. Packet No. ' + no + ' is in the Seed Bed now.' : 'Planted. Packet No. ' + no + ' waits for a person to look at it first (' + pk.why.join('; ') + ').', pk.check === 'green' ? 'ok' : 'warn');
|
||||
reset(); await load();
|
||||
};
|
||||
// the AI writer (through the hub): a name and a one-sentence description from the program's own page; picking one fills the form
|
||||
if (c.aiWriter) {
|
||||
$('aiBox').hidden = false;
|
||||
$('aiWrite').onclick = async () => {
|
||||
const box = $('aiList'), url = $('url').value.trim();
|
||||
if (!/^https?:\/\//i.test(url)) { box.innerHTML = '<p class="note err">Put your referral link in the first box first.</p>'; return; }
|
||||
$('aiWrite').disabled = true; box.innerHTML = '<p class="muted" style="margin:8px 0 0">Reading the program page...</p>';
|
||||
const r = await YPB.post('/api/my/adwriter', { url }); $('aiWrite').disabled = false;
|
||||
if (r.error) { box.innerHTML = '<p class="note err">' + esc(r.error) + '</p>'; return; }
|
||||
box.innerHTML = r.options.map((o, i) => '<button type="button" class="btn sm" style="margin:8px 8px 0 0;text-align:left" data-ai="' + i + '"><b>' + esc(o.headline) + '</b>' + (o.line ? ': ' + esc(o.line) : '') + '</button>').join('')
|
||||
+ '<p class="muted" style="font-size:13px;margin:8px 0 0">' + (r.left != null ? r.left + ' writes left today. ' : '') + 'Pick one, then change any words you like.</p>';
|
||||
box.querySelectorAll('[data-ai]').forEach(b => { b.onclick = () => { const o = r.options[Number(b.dataset.ai)]; $('name').value = String(o.headline || '').slice(0, 40); if (o.line) $('desc').value = String(o.line).slice(0, 200); }; });
|
||||
};
|
||||
}
|
||||
await load();
|
||||
})();
|
||||
@@ -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
|
||||
})();
|
||||
@@ -0,0 +1,40 @@
|
||||
// A packet: the card, Save my ID (network members), whose link a visitor gets, the report button, recent savers, the Spotlight strip.
|
||||
(async function () {
|
||||
const $ = YPB.$, esc = YPB.esc;
|
||||
const id = Number((location.pathname.match(/^\/p\/(\d+)/) || [])[1]);
|
||||
const c = await YPB.getConfig().catch(() => ({}));
|
||||
const d = await YPB.wire('packet', '&id=' + id).catch(() => ({ error: 'x' }));
|
||||
if (d.error || !d.packet) { $('pk').innerHTML = '<p class="note err">' + esc(d.error || 'That packet is not in the Seed Bed right now.') + '</p>'; return; }
|
||||
const x = d.packet;
|
||||
document.title = x.name + ' | YourProgramBuilder';
|
||||
$('pk').innerHTML = YPB.packetCard(x, { place: 'packet', extra: '<p style="font-size:13px">Link checked ' + esc(YPB.when(x.checkedAt)) + '. Planted ' + esc(YPB.when(x.sownAt)) + (x.planter ? ' by @' + esc(x.planter) : '') + '. ' + YPB.n(x.clicks) + ' verified clicks.' + (x.contract ? ' Contract: <span class="mono">' + esc(x.contract) + '</span>' + (c.explorer ? ' (<a href="' + esc(c.explorer) + '/address/' + esc(x.contract) + '" target="_blank" rel="noopener">look it up</a>)' : '') : '') + '</p>' });
|
||||
const who = x.linkFallback === null ? '@' + esc(x.linkBy) + '\'s link (the nearest person in your line who saved an ID).' : x.linkFallback === 'planter' ? 'The planter\'s link' + (x.linkBy ? ' (@' + esc(x.linkBy) + ')' : '') + ': nobody in your line has saved an ID yet.' : 'The program\'s home page: no ID saved yet.';
|
||||
$('linkWho').innerHTML = 'You get ' + who;
|
||||
$('visitBtn').dataset.go = x.id; $('visitBtn').dataset.p = 'packet'; $('visitBtn').href = YPB.goHref(x.id, 'packet');
|
||||
YPB.decorate();
|
||||
if (x.recent && x.recent.length) { $('savers').hidden = false; $('saverList').textContent = x.recent.map(n => '@' + n).join(', '); }
|
||||
YPB.spotRow($('spots'), d);
|
||||
const me = await YPB.getJSON('/api/me');
|
||||
if (!me.signedIn) { $('saveSignin').hidden = false; if (c.joinUrl) $('joinLink').href = c.joinUrl; $('saveSignin').querySelector('a').href = '/sso/start?mode=go&to=' + encodeURIComponent(location.pathname); }
|
||||
else if (x.own) { $('save').querySelector('p').textContent = 'You planted this packet: your ID is the planter\'s ID. Change it on My packets.'; }
|
||||
else {
|
||||
$('saveForm').hidden = false;
|
||||
$('idHint').textContent = 'letters, numbers and . _ - @ + only';
|
||||
if (d.mySave) { $('refId').value = d.mySave.refId; $('track').checked = d.mySave.track; $('removeBtn').hidden = false; $('saveBtn').textContent = 'Update my ID'; }
|
||||
const send = async refId => {
|
||||
YPB.status('Saving...', '');
|
||||
const r = await YPB.post('/api/my/save', { packetId: x.id, refId, track: $('track').checked });
|
||||
if (r.error) return YPB.status(r.error + (r.join ? ' ' : ''), 'err');
|
||||
if (r.removed) { YPB.status('Your ID was removed from this packet.', 'ok'); $('removeBtn').hidden = true; $('refId').value = ''; return; }
|
||||
YPB.status('Saved. Your link: ' + r.link + '. This packet has ' + r.saves + ' of ' + r.need + ' saved IDs' + (r.review ? ' and is now in the review queue.' : '.'), 'ok');
|
||||
$('removeBtn').hidden = false; $('saveBtn').textContent = 'Update my ID';
|
||||
};
|
||||
$('saveForm').onsubmit = e => { e.preventDefault(); send($('refId').value.trim()); };
|
||||
$('removeBtn').onclick = () => send('');
|
||||
}
|
||||
$('reportForm').onsubmit = async e => {
|
||||
e.preventDefault();
|
||||
const r = await YPB.post('/api/report', { packetId: x.id, reason: $('reason').value, note: $('reportNote').value });
|
||||
YPB.status(r.error || (r.already ? 'You already reported this packet. Thank you.' : 'Thank you. A person will look at it.'), r.error ? 'err' : 'ok', 'reportStatus');
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,50 @@
|
||||
// The small pages: transplanted, ledger, contract, promote (one file; each part runs only on its own page).
|
||||
(async function () {
|
||||
const $ = YPB.$, esc = YPB.esc, path = location.pathname.replace(/\/$/, '');
|
||||
const c = await YPB.getConfig().catch(() => ({}));
|
||||
if (path === '/transplanted') {
|
||||
const d = await YPB.getJSON('/api/transplanted');
|
||||
$('inReview').textContent = d.inReview ? d.inReview + ' more ' + (d.inReview === 1 ? 'packet is' : 'packets are') + ' in review now.' : '';
|
||||
$('tList').innerHTML = (d.items || []).length ? d.items.map(x => YPB.packetCard(x, { place: 'transplanted' })).join('') : '<p class="empty">Nothing transplanted yet. The first packet to reach ' + YPB.n(c.reviewSaves) + ' saved IDs goes to review.</p>';
|
||||
YPB.decorate(); return;
|
||||
}
|
||||
if (path === '/ledger') {
|
||||
const d = await YPB.getJSON('/api/ledger?n=100');
|
||||
const t = d.totals || {};
|
||||
$('ledgerStats').innerHTML = [['Spotlights', YPB.n(t.spotlights)], ['Paid in, USD', YPB.usd(t.usdCents)], ['Paid in, POL', YPB.polOf(t.weiPaid)], ['Paid to sponsor lines, POL', YPB.polOf(t.levelsWei)]].map(s => '<div class="stat"><b>' + s[1] + '</b><span>' + s[0] + '</span></div>').join('');
|
||||
const who = (n, a) => n ? '@' + esc(n) : esc(YPB.short(a));
|
||||
$('rows').innerHTML = (d.items || []).length ? d.items.map(x => '<tr><td>' + esc(YPB.when(x.at)) + (d.explorer ? '<br><a href="' + esc(d.explorer) + '/tx/' + esc(x.tx) + '" target="_blank" rel="noopener">tx</a>' : '') + '</td><td>' + who(x.buyerName, x.buyer) + '</td><td>' + (x.packet ? '<a href="/p/' + x.packet.id + '">' + esc(x.packet.name) + '</a>' : '') + '</td><td class="n">' + YPB.usd(x.usdCents) + '<br>' + YPB.polOf(x.weiPaid) + ' POL</td><td>'
|
||||
+ x.pays.map(p => esc(p.label) + ': ' + YPB.polOf(p.wei) + ' POL' + (p.kind ? ' to ' + who(p.name, p.to) : '') + (p.failed ? ' (waiting to claim)' : '')).join('<br>') + '</td><td>' + YPB.n(x.delivery.delivered) + ' / ' + YPB.n(x.delivery.views) + '<br><span class="muted">' + esc(x.delivery.status) + '</span></td></tr>').join('')
|
||||
: '<tr><td colspan="6" class="muted">' + (d.contract ? 'No Spotlights yet.' : 'No Spotlights yet: the YPBShop contract is not deployed. Every payment will show here with its transaction.') + '</td></tr>';
|
||||
return;
|
||||
}
|
||||
if (path === '/contract') {
|
||||
const d = await YPB.getJSON('/api/contract');
|
||||
const lv = (d.split || {}).levelBps || [];
|
||||
const company = YPB.pct(10000 - lv.reduce((t, x) => t + x, 0));
|
||||
const rows = [
|
||||
['Status', d.deployed ? 'Deployed on Polygon' : 'Not deployed yet. These are the planned values; nothing can be bought until it is.'],
|
||||
['Address', d.address ? '<span class="mono">' + esc(d.address) + '</span>' + (d.explorer ? ' (<a href="' + esc(d.explorer) + '/address/' + esc(d.address) + '#code" target="_blank" rel="noopener">Polygonscan</a>)' : '') : 'not deployed'],
|
||||
['Verified source', d.verified && (d.verified.sourcify || d.verified.polygonscan) ? [d.verified.polygonscan ? 'Polygonscan' : '', d.verified.sourcify ? 'Sourcify' : ''].filter(Boolean).join(' and ') : 'after deploy'],
|
||||
['Split', lv.map((b, i) => 'level ' + (i + 1) + ' ' + YPB.pct(b)).join(', ') + ', company ' + company + ' (immutable)'],
|
||||
['Spotlight', d.sku ? YPB.usd(d.sku.usdCents) + ' for ' + YPB.n(d.sku.views) + ' views' + (d.sku.active ? '' : ' (switched off)') : '$' + (d.spotlight || {}).usd + ' for ' + YPB.n((d.spotlight || {}).views) + ' views (planned)'],
|
||||
['Price changes', 'wait ' + d.skuDelayHours + ' hours on chain' + (d.pendingSku ? '. Pending: ' + YPB.usd(d.pendingSku.usdCents) + ' for ' + YPB.n(d.pendingSku.views) + ' views, from ' + YPB.when(d.pendingSku.eta * 1000) : '')],
|
||||
['Company wallet', '<span class="mono">' + esc(d.company || '') + '</span>'],
|
||||
['Owner', d.owner ? '<span class="mono">' + esc(d.owner) + '</span> (' + esc(d.ownerNote) + ')' : esc(d.ownerNote) + ' (after deploy)'],
|
||||
['Paused', d.deployed ? (d.paused ? 'yes (new Spotlights stopped; claims stay open)' : 'no') : 'n/a']];
|
||||
if (d.error) rows.push(['Note', esc(d.error)]);
|
||||
$('cBox').innerHTML = '<div class="tbl" style="margin:0"><table><tbody>' + rows.map(r => '<tr><th style="width:34%">' + r[0] + '</th><td>' + r[1] + '</td></tr>').join('') + '</tbody></table></div>';
|
||||
return;
|
||||
}
|
||||
if (path === '/promote') {
|
||||
const me = await YPB.getJSON('/api/me');
|
||||
const k = await YPB.getJSON('/api/promo-kit' + (me.signedIn && me.username ? '?u=' + encodeURIComponent(me.username) : ''));
|
||||
const link = (k.links || [])[0]; $('myLink').textContent = link ? link.tracked || link.url : ''; $('copyLink').onclick = e => YPB.copy($('myLink').textContent, e.target);
|
||||
const box = t => '<div class="sharebox" style="margin-top:8px"><span>' + esc(t) + '</span><button class="btn sm" type="button" data-copy>Copy</button></div>';
|
||||
$('lines').innerHTML = (k.lines || []).concat(k.posts || []).map(box).join('');
|
||||
$('email').innerHTML = '<p><b>' + esc(k.email.subject) + '</b></p>' + box(k.email.body);
|
||||
$('creatives').innerHTML = (k.creatives || []).length ? k.creatives.map(x => '<div><p class="muted" style="margin:0 0 4px">' + esc(x.angleLabel + ', ' + x.label + ' ' + x.w + 'x' + x.h) + '</p><img src="' + esc(x.url) + '" width="' + x.w + '" height="' + x.h + '" alt="YourProgramBuilder" loading="lazy" style="height:auto">' + box(x.html) + '</div>').join('') : '<p class="muted">Banners are on their way.</p>';
|
||||
$('kitNote').textContent = k.note || '';
|
||||
document.querySelectorAll('[data-copy]').forEach(b => { b.onclick = () => YPB.copy(b.previousElementSibling.textContent, b); });
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,21 @@
|
||||
// The Spotlight page: pick a packet and a quantity; closed with a clear note until YPBShop is deployed.
|
||||
(async function () {
|
||||
const $ = YPB.$, esc = YPB.esc;
|
||||
const c = await YPB.getConfig().catch(() => ({}));
|
||||
const d = await YPB.getJSON('/api/packets').catch(() => ({ items: [] }));
|
||||
const want = Number(new URLSearchParams(location.search).get('p'));
|
||||
$('pkPick').innerHTML = (d.items || []).map(x => '<option value="' + x.id + '"' + (x.id === want ? ' selected' : '') + '>No. ' + esc(x.no) + ' ' + esc(x.name) + '</option>').join('') || '<option value="">No packets in the Seed Bed yet</option>';
|
||||
if (!c.shop || !c.shop.live) { $('notYet').hidden = false; return; }
|
||||
$('buyBtn').disabled = false;
|
||||
const q = async () => { const r = await YPBBuy.quote(Number($('qty').value) || 1); $('quote').textContent = r.error || ('About ' + YPBBuy.fmtPol(r.wei) + ' POL for $' + r.usd + ' (' + YPB.n(r.views) + ' views).'); };
|
||||
$('qty').oninput = q; q();
|
||||
$('buyForm').onsubmit = async e => {
|
||||
e.preventDefault(); $('buyBtn').disabled = true;
|
||||
try {
|
||||
const packetId = Number($('pkPick').value); const before = (await YPB.getJSON('/api/my')).spotlights.length;
|
||||
const r = await YPBBuy.run({ qty: Number($('qty').value) || 1, packetId, done: async () => (await YPB.getJSON('/api/my')).spotlights.length > before });
|
||||
YPB.status(r.recorded ? 'Your Spotlight is live. Track its views on My packets.' : 'Paid and confirmed. It shows on My packets as soon as the watcher records it.' + (r.link ? ' ' + r.link : ''), 'ok');
|
||||
} catch (err) { YPB.status(String(err && err.message || err).slice(0, 400), 'err'); }
|
||||
$('buyBtn').disabled = false;
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,233 @@
|
||||
// YourProgramBuilder wallet sign-in: the VBB / Downline Banners / ViralAdBlitz wallet.js (same AppKit build, chain guard, dead-session recovery)
|
||||
// with its buy flow (2026-11-14): sendTx() hard-guards the chain, sets Polygon's fee floor from /api/gas and recovers a dead
|
||||
// WalletConnect session once; waitTx() polls /api/tx; balance() is the pre-flight check. The page builds the call on the server.
|
||||
window.YPBWallet = (function () {
|
||||
const pad = v => BigInt(v).toString(16).padStart(64, '0');
|
||||
const padAddr = a => { if (!a) return pad(0); if (!/^0x[0-9a-fA-F]{40}$/.test(a)) throw new Error('Bad address: ' + a); return a.slice(2).toLowerCase().padStart(64, '0'); };
|
||||
// Normalize a chainId to a decimal number. eth_chainId is meant to return a
|
||||
// hex string, but some wallets return a number or a decimal string — compare
|
||||
// numerically so a wallet's shape never crashes the flow.
|
||||
const chainNum = v => {
|
||||
if (v == null) return NaN;
|
||||
if (typeof v === 'number') return v;
|
||||
const s = String(v).trim();
|
||||
return /^0x/i.test(s) ? parseInt(s, 16) : parseInt(s, 10);
|
||||
};
|
||||
const APPKIT_URL = 'https://cdn.jsdelivr.net/npm/@reown/appkit-cdn@1.8.23/dist/appkit.js';
|
||||
|
||||
let modal = null, akPromise = null, provider = null;
|
||||
|
||||
async function initAppKit(c) {
|
||||
if (modal) return modal;
|
||||
if (akPromise) return akPromise;
|
||||
akPromise = (async () => {
|
||||
const mod = await import(APPKIT_URL);
|
||||
const { createAppKit, WagmiAdapter, networks } = mod;
|
||||
const netMap = { 80002: networks.polygonAmoy, 137: networks.polygon, 31337: networks.hardhat || networks.localhost };
|
||||
const base = netMap[Number(c.chainId)] || networks.polygonAmoy;
|
||||
// Override the chain's RPC with our clean public endpoint. AppKit's built-in
|
||||
// networks advertise the WalletConnect RPC proxy
|
||||
// (rpc.walletconnect.org/v1/?chainId=…&projectId=…) as the chain RPC, and
|
||||
// wallets reject that query-string URL as "Invalid URL" when adding/switching
|
||||
// the network: the cause of Trust's "Invalid URL", MetaMask's switch loop,
|
||||
// and the failed mobile buy (the chain switch never completed).
|
||||
const rpc = String(c.rpc || '').trim();
|
||||
const net = rpc ? Object.assign({}, base, { rpcUrls: { default: { http: [rpc] }, public: { http: [rpc] } } }) : base;
|
||||
// Accept the wallet's usual networks too, so AppKit doesn't trap the user in
|
||||
// its own "Switch Network" modal — that modal loops on a testnet the wallet
|
||||
// can't auto-add. We switch to `net` ourselves (wallet_addEthereumChain adds
|
||||
// + switches in one step) and sendTx hard-guards the chain before signing.
|
||||
const allNets = [net];
|
||||
for (const k of ['polygon', 'mainnet']) {
|
||||
try { const n = networks[k]; if (n && n.id !== net.id) allNets.push(n); } catch (e) {}
|
||||
}
|
||||
const projectId = String(c.walletConnectProjectId || '').trim();
|
||||
const wagmiAdapter = new WagmiAdapter({ networks: allNets, projectId });
|
||||
modal = createAppKit({
|
||||
adapters: [wagmiAdapter], networks: allNets, projectId, defaultNetwork: net,
|
||||
metadata: { name: 'YourProgramBuilder', description: 'The Seed Bed: bring your program, the network grows it.',
|
||||
url: location.origin, icons: [location.origin + '/art/icon-192.png'] },
|
||||
features: { analytics: false, email: false, socials: [] },
|
||||
// Picker order: wallets without Trust's balance-proportion block go first.
|
||||
// Trust Wallet is NOT excluded; it just drops out of the featured row into
|
||||
// "All wallets" (Marty, 2026-09-09: move Trust to the bottom, not off).
|
||||
featuredWalletIds: [
|
||||
'0b415a746fb9ee99cce155c2ceca0c6f6061b1dbca2d722b3ba16381d0562150', // SafePal (recommended, listed first)
|
||||
'c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96', // MetaMask
|
||||
'a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393', // Phantom
|
||||
'fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa' // Coinbase Wallet
|
||||
]
|
||||
});
|
||||
return modal;
|
||||
})();
|
||||
return akPromise;
|
||||
}
|
||||
|
||||
function currentAddress() { try { return (modal && modal.getAddress && modal.getAddress()) || null; } catch (e) { return null; } }
|
||||
|
||||
function waitForConnection(timeoutMs) {
|
||||
if (currentAddress()) return Promise.resolve(currentAddress());
|
||||
return new Promise((resolve, reject) => {
|
||||
let done = false, unsub = null;
|
||||
const finish = (addr, err) => { if (done) return; done = true; try { unsub && unsub(); } catch (e) {} err ? reject(err) : resolve(addr); };
|
||||
try { unsub = modal.subscribeAccount(acc => { if (acc && acc.isConnected && acc.address) finish(acc.address); }); } catch (e) {}
|
||||
const t0 = Date.now();
|
||||
(function poll() {
|
||||
if (done) return;
|
||||
const a = currentAddress();
|
||||
if (a) return finish(a);
|
||||
if (Date.now() - t0 > (timeoutMs || 180000)) return finish(null, new Error('Wallet connection timed out. Tap Connect and try again.'));
|
||||
setTimeout(poll, 400);
|
||||
})();
|
||||
});
|
||||
}
|
||||
|
||||
async function resolveProvider() {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
try { const p = modal.getWalletProvider ? await Promise.resolve(modal.getWalletProvider()) : null; if (p && p.request) return p; } catch (e) {}
|
||||
await new Promise(r => setTimeout(r, 300));
|
||||
}
|
||||
throw new Error('Could not reach your wallet. Try connecting again.');
|
||||
}
|
||||
|
||||
function eth() { if (!provider) throw new Error('Connect your wallet first.'); return provider; }
|
||||
const isInjected = () => !!(provider && window.ethereum && (provider === window.ethereum || provider.isMetaMask));
|
||||
// the account the wallet will actually sign with: for an injected wallet (MetaMask
|
||||
// extension) that is its active account, which can differ from AppKit's cached one
|
||||
async function activeAddress(fallback) {
|
||||
if (isInjected()) { try { const a = await provider.request({ method: 'eth_accounts' }); if (a && a[0]) return a[0]; } catch (e) {} }
|
||||
return fallback || currentAddress();
|
||||
}
|
||||
// Force the wallet's own account picker. Injected wallets stay connected to the
|
||||
// site, so a plain disconnect/reconnect never shows one: asking for permissions
|
||||
// again makes MetaMask open its account-selection prompt, and whatever the user
|
||||
// ticks becomes the active account. WalletConnect wallets fall back to a fresh
|
||||
// session (the picker + the wallet app's own account choice).
|
||||
async function pickAccount() {
|
||||
const c = await YPB.getConfig();
|
||||
await initAppKit(c);
|
||||
const inj = window.ethereum;
|
||||
if (inj && inj.request) {
|
||||
try {
|
||||
await inj.request({ method: 'wallet_requestPermissions', params: [{ eth_accounts: {} }] });
|
||||
const accs = await inj.request({ method: 'eth_accounts' });
|
||||
if (accs && accs[0]) { provider = inj; await ensureChain(c).catch(() => {}); return accs[0]; }
|
||||
} catch (e) {
|
||||
if (e && (e.code === 4001 || /reject|denied/i.test(String(e.message || '')))) throw new Error('You closed the account picker. Pick the account you want and try again.');
|
||||
}
|
||||
}
|
||||
return freshConnect(c);
|
||||
}
|
||||
|
||||
// A WalletConnect session can die underneath AppKit's cached "connected"
|
||||
// state: the wallet app rejects or kills it (Trust does this after its own
|
||||
// security stop), the phone sleeps, the relay drops. AppKit still reports an
|
||||
// address, so the next request fails with a "disconnected" style error.
|
||||
// Detect that, wipe the stale session, and re-open the picker for a fresh one.
|
||||
const DEAD_RE = /disconnect|not connected|no matching key|session (topic|expired|deleted|not found)|call connect|please call connect|missing or invalid|relay/i;
|
||||
const isDead = e => DEAD_RE.test(String((e && e.message) || e || ''));
|
||||
async function freshConnect(c) {
|
||||
try { YPB.status('Your wallet session dropped. Reconnect in the picker…'); } catch (e) {}
|
||||
await disconnect();
|
||||
try { await modal.open(); } catch (e) {}
|
||||
const addr = await waitForConnection(180000);
|
||||
try { if (modal && modal.close) await modal.close(); } catch (e) {}
|
||||
provider = await resolveProvider();
|
||||
await ensureChain(c).catch(() => {});
|
||||
return addr;
|
||||
}
|
||||
|
||||
async function connect() {
|
||||
const c = await YPB.getConfig();
|
||||
await initAppKit(c);
|
||||
let addr = currentAddress();
|
||||
if (!addr) {
|
||||
// give AppKit a moment to rehydrate an existing session before popping the
|
||||
// picker — otherwise an already-connected wallet still gets the modal
|
||||
for (let i = 0; i < 8 && !addr; i++) { await new Promise(r => setTimeout(r, 150)); addr = currentAddress(); }
|
||||
}
|
||||
if (!addr) { try { await modal.open(); } catch (e) {} addr = await waitForConnection(180000); }
|
||||
try { if (modal && modal.close) await modal.close(); } catch (e) {} // dismiss the picker once we're connected
|
||||
provider = await resolveProvider();
|
||||
// probe the session: a dead WalletConnect session answers with a disconnect error
|
||||
try { await provider.request({ method: 'eth_chainId' }); }
|
||||
catch (e) { if (isDead(e)) return freshConnect(c); }
|
||||
await ensureChain(c).catch(() => {}); // AppKit already connects on the right network; switch is best-effort
|
||||
return addr;
|
||||
}
|
||||
|
||||
async function ensureChain(c) {
|
||||
const want = '0x' + Number(c.chainId).toString(16);
|
||||
let cur; try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) { return; }
|
||||
if (chainNum(cur) === Number(c.chainId)) return;
|
||||
try {
|
||||
await eth().request({ method: 'wallet_switchEthereumChain', params: [{ chainId: want }] });
|
||||
} catch (e) {
|
||||
// any failure (not just 4902): try to add the chain — wallet_addEthereumChain
|
||||
// adds AND switches in one step, which is what unblocks wallets that can't
|
||||
// otherwise reach a chain they don't already have (e.g. a testnet).
|
||||
const addParams = { chainId: want, chainName: c.chainName, nativeCurrency: { name: 'POL', symbol: 'POL', decimals: 18 }, rpcUrls: [c.rpc] };
|
||||
if (c.explorer && /^https?:\/\//i.test(c.explorer)) addParams.blockExplorerUrls = [c.explorer];
|
||||
try { await eth().request({ method: 'wallet_addEthereumChain', params: [addParams] }); } catch (e2) {}
|
||||
}
|
||||
}
|
||||
|
||||
// SIWE: challenge -> personal_sign -> verify (server sets the session cookie)
|
||||
async function signIn(opts) {
|
||||
const addr = (opts && opts.pick) ? await pickAccount() : await activeAddress(await connect());
|
||||
const ch = await (await fetch('/api/auth/challenge', { method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address: addr }) })).json();
|
||||
if (ch.error) throw new Error(ch.error);
|
||||
// hex-encode the message (Trust and others require hex for personal_sign)
|
||||
const hexMsg = '0x' + Array.from(new TextEncoder().encode(ch.message)).map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
const sig = await eth().request({ method: 'personal_sign', params: [hexMsg, addr] });
|
||||
const r = await (await fetch('/api/auth/verify', { method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address: addr, signature: sig, asPosition: !!(opts && opts.asPosition) }) })).json();
|
||||
if (r.error) throw new Error(r.error);
|
||||
return r;
|
||||
}
|
||||
|
||||
async function sendTx(to, data, valueHex) {
|
||||
const c = await YPB.getConfig();
|
||||
const addr = await connect();
|
||||
const wantNum = Number(c.chainId);
|
||||
let cur; try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) {}
|
||||
if (!isNaN(chainNum(cur)) && chainNum(cur) !== wantNum) {
|
||||
await ensureChain(c);
|
||||
try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) {}
|
||||
if (!isNaN(chainNum(cur)) && chainNum(cur) !== wantNum)
|
||||
throw new Error('Your wallet is on the wrong network. Switch it to ' + (c.chainName || 'Polygon') + ', then try again.');
|
||||
}
|
||||
const tx = { from: await activeAddress(addr), to, data };
|
||||
if (valueHex) tx.value = valueHex;
|
||||
try { const g = await (await fetch('/api/gas')).json(); if (g && g.maxPriorityFeePerGas && g.maxFeePerGas) { tx.maxPriorityFeePerGas = g.maxPriorityFeePerGas; tx.maxFeePerGas = g.maxFeePerGas; } } catch (e) {}
|
||||
try { return await eth().request({ method: 'eth_sendTransaction', params: [tx] }); }
|
||||
catch (e) {
|
||||
if (!isDead(e)) throw e;
|
||||
tx.from = await freshConnect(c);
|
||||
return eth().request({ method: 'eth_sendTransaction', params: [tx] });
|
||||
}
|
||||
}
|
||||
async function waitTx(hash) {
|
||||
for (let i = 0; i < 120; i++) {
|
||||
try { const r = await (await fetch('/api/tx/' + hash)).json(); if (r.found) return r; } catch (e) { /* app switch on a phone: keep polling */ }
|
||||
await new Promise(res => setTimeout(res, 2500));
|
||||
}
|
||||
throw new Error('Still waiting for the transaction. Check it on the explorer; your Boost shows once it confirms.');
|
||||
}
|
||||
async function balance(addr) {
|
||||
await connect();
|
||||
return BigInt(await eth().request({ method: 'eth_getBalance', params: [addr || currentAddress(), 'latest'] }));
|
||||
}
|
||||
|
||||
async function disconnect() {
|
||||
// AppKit's disconnect can hang on the WalletConnect relay (esp. mobile) —
|
||||
// never block on it, so the UI can't get stuck "disconnecting".
|
||||
try { if (modal && modal.disconnect) await Promise.race([modal.disconnect(), new Promise(r => setTimeout(r, 1200))]); } catch (e) {}
|
||||
provider = null;
|
||||
try { Object.keys(localStorage).forEach(k => { if (/wc@2|walletconnect|w3m|wcm|reown|wagmi|appkit/i.test(k)) localStorage.removeItem(k); }); } catch (e) {}
|
||||
}
|
||||
|
||||
function walletName() { try { const w = modal && modal.getWalletInfo && modal.getWalletInfo(); return (w && w.name) || ''; } catch (e) { return ''; } }
|
||||
return { connect, signIn, sendTx, waitTx, balance, disconnect, address: currentAddress, activeAddress, pickAccount, walletName };
|
||||
})();
|
||||
@@ -0,0 +1,182 @@
|
||||
/* YourProgramBuilder: a seed catalog (the approved mockup, 2026-11-17). Green-white paper with a light grain, forest ink, leaf green,
|
||||
tangerine for the one call to action per screen, butter for the Spotlight. Young Serif display, Atkinson Hyperlegible body,
|
||||
Martian Mono for counts. No other network site uses these colors or fonts. */
|
||||
:root{
|
||||
--paper:#F6FAF1;--bed:#E9F2E2;--ink:#12291F;--sub:#4A6457;--leaf:#22844A;--leafInk:#1B6E3C;--tang:#F2620F;--tangInk:#C24A08;--sky:#8CCBF5;--butter:#FFE6A0;--packet:#FFFFFF;--line:#D3E3CB;--onTang:#FFFFFF;
|
||||
--bad:#B3261E;--grain:url("/art/paper-grain.jpg");--sprig:#22844A;
|
||||
--display:"Young Serif",Georgia,"Times New Roman",serif;--body:"Atkinson Hyperlegible",system-ui,-apple-system,"Segoe UI",sans-serif;--mono:"Martian Mono",ui-monospace,Menlo,Consolas,monospace;
|
||||
color-scheme:light;
|
||||
}
|
||||
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--paper:#0E1C15;--bed:#13261C;--ink:#E9F3E6;--sub:#A3BDAE;--leaf:#5CC583;--leafInk:#7FD8A0;--tang:#FF8440;--tangInk:#FF9A5E;--sky:#3F7FAE;--butter:#3B3420;--packet:#18301F;--line:#284634;--onTang:#1A0D04;--bad:#FF8A80;--grain:none;--sprig:#5CC583;color-scheme:dark}}
|
||||
:root[data-theme="dark"]{--paper:#0E1C15;--bed:#13261C;--ink:#E9F3E6;--sub:#A3BDAE;--leaf:#5CC583;--leafInk:#7FD8A0;--tang:#FF8440;--tangInk:#FF9A5E;--sky:#3F7FAE;--butter:#3B3420;--packet:#18301F;--line:#284634;--onTang:#1A0D04;--bad:#FF8A80;--grain:none;--sprig:#5CC583;color-scheme:dark}
|
||||
*{box-sizing:border-box}
|
||||
html{scroll-padding-top:16px}
|
||||
body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.55 var(--body);padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px))}
|
||||
body::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;background-image:var(--grain);background-size:620px;opacity:.28;mix-blend-mode:multiply}
|
||||
img{max-width:100%}
|
||||
a{color:var(--leafInk)}
|
||||
[hidden]{display:none!important}
|
||||
.wrap{max-width:1180px;margin:0 auto}
|
||||
.skip{position:absolute;left:-999px;top:0}.skip:focus{left:16px;z-index:50;background:var(--packet);padding:8px 12px;border:2px solid var(--ink);border-radius:8px}
|
||||
h1,h2,h3{font-family:var(--display);font-weight:400;line-height:1.1;margin:0;text-wrap:balance}
|
||||
h1{font-size:clamp(34px,5vw,56px)}
|
||||
h1 em{font-style:normal;color:var(--tangInk)}
|
||||
h2{font-size:clamp(24px,3.2vw,30px)}
|
||||
p{margin:0 0 10px}
|
||||
.muted{color:var(--sub)}
|
||||
.kicker{font:600 12px/1 var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--leafInk)}
|
||||
.mono{font-family:var(--mono);font-variant-numeric:tabular-nums}
|
||||
.ic{width:1em;height:1em;flex:none;display:block}
|
||||
|
||||
/* header */
|
||||
header.top{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px 14px;padding-block:14px;border-bottom:2px solid var(--ink)}
|
||||
.brand{display:flex;align-items:center;gap:10px;font:24px/1 var(--display);color:var(--ink);text-decoration:none;min-width:0}
|
||||
.brand svg{flex:none}
|
||||
nav.links{display:flex;flex-wrap:wrap;gap:6px 18px;font-weight:700;font-size:15px}
|
||||
nav.links a{color:var(--ink);text-decoration:none;padding-block:4px;border-bottom:2px solid transparent}
|
||||
nav.links a[aria-current]{border-color:var(--tang)}
|
||||
.signin{font-weight:700;font-size:14px;color:var(--ink);background:transparent;border:2px solid var(--ink);border-radius:999px;padding:8px 14px;cursor:pointer;text-decoration:none;white-space:nowrap}
|
||||
.stage-bar{background:var(--butter);color:var(--ink);border:2px solid var(--ink);border-radius:10px;padding:8px 12px;margin-top:10px;font-weight:700;font-size:14px;text-align:center}
|
||||
|
||||
/* buttons */
|
||||
.btn{font:700 16px/1 var(--body);border-radius:999px;padding:14px 20px;border:2px solid var(--ink);cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;gap:8px;background:var(--packet);color:var(--ink)}
|
||||
.btn.primary{background:var(--tang);color:var(--onTang);border-color:var(--tang)}
|
||||
.btn.ink{background:var(--ink);color:var(--paper);border-color:var(--ink)}
|
||||
.btn.sm{font-size:14px;padding:9px 14px}
|
||||
.btn .ic{width:20px;height:20px}
|
||||
.btn[disabled]{opacity:.55;cursor:not-allowed}
|
||||
.btn:focus-visible,.signin:focus-visible,.save:focus-visible,.chip:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,a:focus-visible,button:focus-visible{outline:3px solid var(--sky);outline-offset:2px}
|
||||
.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
|
||||
|
||||
/* hero plate: the art is a printed plate, it keeps its light paper in both themes */
|
||||
.plate{position:relative;margin-top:22px;border:2px solid var(--ink);border-radius:18px;overflow:hidden;min-height:440px;display:flex;align-items:center;background:#F6FAF1}
|
||||
.plate>img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;object-position:right center}
|
||||
.plate::before{content:"";position:absolute;inset:0;background:linear-gradient(90deg,rgba(246,250,241,.94) 0%,rgba(246,250,241,0) 48%);z-index:1}
|
||||
.plate .copy{position:relative;z-index:2;max-width:560px;padding:34px clamp(18px,4vw,44px);min-width:0;color:#12291F}
|
||||
.plate .kicker{color:#1B6E3C}
|
||||
.plate h1{margin:12px 0 14px}
|
||||
.plate h1 em{color:#C24A08}
|
||||
.lede{max-width:52ch;color:#35503F;margin:0 0 20px;font-size:17px}
|
||||
.plate .btn.primary{background:#F2620F;color:#fff;border-color:#F2620F}
|
||||
.plate .btn.ghost{background:#fff;color:#12291F;border-color:#12291F}
|
||||
.ctas{display:flex;flex-wrap:wrap;gap:12px}
|
||||
|
||||
.under{display:grid;grid-template-columns:1.25fr 1fr;gap:28px;padding-block:22px;align-items:start}
|
||||
.under>*{min-width:0}
|
||||
.steps{display:grid;grid-template-columns:repeat(3,1fr);border:2px solid var(--ink);border-radius:14px;overflow:hidden;background:var(--packet)}
|
||||
.step{padding:16px 14px;border-right:2px dashed var(--line);display:flex;flex-direction:column;gap:4px;min-width:0}
|
||||
.step:last-child{border-right:0}
|
||||
.step .ic{width:44px;height:44px;color:var(--leaf);margin-bottom:6px}
|
||||
.step b{display:block;font:20px/1.1 var(--display);font-weight:400}
|
||||
.step span{font-size:14px;color:var(--sub)}
|
||||
.step i{font:600 11px/1 var(--mono);font-style:normal;color:var(--leafInk);letter-spacing:.08em}
|
||||
.spot{position:relative;overflow:hidden;background:var(--butter);border:2px solid var(--ink);border-radius:16px;padding:20px;box-shadow:6px 6px 0 var(--ink)}
|
||||
.spot>*{position:relative;z-index:1}
|
||||
.spot .sprig{position:absolute;z-index:0;right:-8px;bottom:-10px;width:120px;height:auto;color:var(--ink);opacity:.22}
|
||||
.spot .kicker{display:flex;align-items:center;gap:8px}
|
||||
.spot .kicker .ic{width:22px;height:22px;color:var(--tangInk)}
|
||||
.spot h2{font-size:26px;margin:6px 0 8px}
|
||||
.price{font:600 34px/1 var(--mono)}
|
||||
.price small{font:400 14px var(--body);color:var(--sub)}
|
||||
.spot ul{margin:12px 0 14px;padding-left:18px;font-size:15px;max-width:44ch}
|
||||
.spot li{margin:4px 0}
|
||||
.split{font:400 12px/1.5 var(--mono);color:var(--sub);border-top:1px dashed var(--ink);padding-top:10px}
|
||||
.sprig path{vector-effect:non-scaling-stroke;stroke-width:1.4}
|
||||
|
||||
/* the bed of packets */
|
||||
.bedhead{display:flex;flex-wrap:wrap;align-items:flex-end;justify-content:space-between;gap:10px;margin-top:8px}
|
||||
.bedhead .t{display:flex;align-items:flex-end;gap:6px}
|
||||
.bedhead .sprig{width:46px;height:72px;color:var(--sprig);margin-bottom:-4px}
|
||||
.filters{display:flex;flex-wrap:wrap;gap:8px}
|
||||
.chip{font:700 13px/1 var(--body);border:2px solid var(--line);border-radius:999px;padding:7px 12px;background:var(--packet);color:var(--ink);cursor:pointer}
|
||||
.chip[aria-pressed="true"],.chip.on{border-color:var(--leaf);color:var(--leafInk)}
|
||||
.bed{background:var(--bed);border-radius:18px;padding:18px;margin-block:14px 26px;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}
|
||||
.bed.spotrow{background:transparent;padding:0;margin-block:10px 8px}
|
||||
.bed .empty{grid-column:1/-1;text-align:center;color:var(--sub);padding:28px 10px}
|
||||
.pk{background:var(--packet);border:2px solid var(--ink);border-radius:6px 6px 14px 14px;display:flex;flex-direction:column;min-width:0}
|
||||
.pk .fold{height:14px;border-bottom:2px solid var(--ink);background:repeating-linear-gradient(90deg,var(--leaf) 0 10px,transparent 10px 16px)}
|
||||
.pk.spotlit .fold{background:repeating-linear-gradient(90deg,var(--tang) 0 10px,transparent 10px 16px)}
|
||||
.pk .body{padding:14px;display:flex;flex-direction:column;gap:8px;flex:1}
|
||||
.pk .no{display:flex;align-items:center;justify-content:space-between;gap:8px;font:600 11px/1 var(--mono);letter-spacing:.06em;color:var(--sub);padding-bottom:8px;border-bottom:1.5px dashed var(--line)}
|
||||
.pk .no .ic{width:26px;height:26px;color:var(--leaf)}
|
||||
.pk.spotlit .no .ic{color:var(--tangInk)}
|
||||
.pk h3{font-size:21px;line-height:1.15}
|
||||
.pk h3 a{color:var(--ink);text-decoration:none}
|
||||
.pk h3 a:hover{text-decoration:underline}
|
||||
.meta{display:flex;flex-wrap:wrap;gap:6px}
|
||||
.tag{font:600 11px/1 var(--mono);letter-spacing:.04em;padding:5px 7px;border-radius:5px;border:1.5px solid var(--line);color:var(--sub);text-transform:uppercase}
|
||||
.tag.ok{border-color:var(--leaf);color:var(--leafInk)}
|
||||
.tag.sp{border-color:var(--tang);color:var(--tangInk)}
|
||||
.tag.warn{border-color:var(--tang);color:var(--tangInk)}
|
||||
.tag.bad{border-color:var(--bad);color:var(--bad)}
|
||||
.pk p{margin:0;font-size:14px;color:var(--sub);overflow-wrap:anywhere}
|
||||
.meter{margin-top:auto}
|
||||
.meter .lbl{display:flex;justify-content:space-between;font:600 12px/1 var(--mono);font-variant-numeric:tabular-nums;margin-bottom:6px}
|
||||
.bar{height:10px;border-radius:99px;background:var(--bed);border:1.5px solid var(--ink);overflow:hidden}
|
||||
.bar>span{display:block;height:100%;background:var(--leaf)}
|
||||
.bar.sp>span{background:var(--tang)}
|
||||
.pk .row{justify-content:space-between}
|
||||
.save{font:700 14px/1 var(--body);background:var(--ink);color:var(--paper);border:0;border-radius:999px;padding:9px 14px 9px 10px;cursor:pointer;display:inline-flex;align-items:center;gap:6px;text-decoration:none}
|
||||
.save .ic{width:20px;height:20px}
|
||||
.save.done{background:var(--leaf);color:#fff}
|
||||
.by{font-size:13px;color:var(--sub)}
|
||||
|
||||
/* panels, forms, tables */
|
||||
.panel{background:var(--packet);border:2px solid var(--ink);border-radius:14px;padding:20px;min-width:0}
|
||||
.panel+.panel{margin-top:18px}
|
||||
.grid2{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr);gap:22px;align-items:start}
|
||||
.stack{display:grid;gap:12px}
|
||||
label.f{display:grid;gap:5px;font-weight:700;font-size:15px}
|
||||
label.f small{font-weight:400;color:var(--sub);font-size:13px}
|
||||
input[type=text],input[type=url],input[type=number],select,textarea{width:100%;font:16px/1.4 var(--body);color:var(--ink);background:var(--paper);border:2px solid var(--line);border-radius:10px;padding:10px 12px;min-width:0}
|
||||
textarea{min-height:84px;resize:vertical}
|
||||
input:focus,select:focus,textarea:focus{border-color:var(--leaf)}
|
||||
.radios{display:flex;flex-wrap:wrap;gap:8px 16px;font-weight:400}
|
||||
.radios label{display:flex;gap:6px;align-items:center}
|
||||
.note{border-radius:10px;padding:10px 12px;border:2px solid var(--line);background:var(--paper);font-size:15px;margin:12px 0 0}
|
||||
.note.ok{border-color:var(--leaf)}
|
||||
.note.err{border-color:var(--bad);color:var(--bad)}
|
||||
.note.warn{border-color:var(--tang)}
|
||||
.tbl{overflow-x:auto;border:2px solid var(--line);border-radius:10px;margin-top:10px}
|
||||
table{border-collapse:collapse;width:100%;font-size:14px}
|
||||
th,td{text-align:left;padding:8px 10px;border-bottom:1px solid var(--line);vertical-align:top}
|
||||
th{background:var(--bed);font-weight:700}
|
||||
td.n{text-align:right;font-family:var(--mono);font-variant-numeric:tabular-nums;white-space:nowrap}
|
||||
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px;margin-top:12px}
|
||||
.stat{background:var(--bed);border-radius:10px;padding:10px 12px}
|
||||
.stat b{display:block;font:600 22px/1.2 var(--mono)}
|
||||
.stat span{font-size:13px;color:var(--sub)}
|
||||
.sharebox{display:flex;gap:8px;align-items:center;background:var(--bed);border-radius:10px;padding:8px 8px 8px 12px;min-width:0}
|
||||
.sharebox span{font:500 13px var(--mono);overflow-wrap:anywhere;min-width:0;flex:1}
|
||||
.tabs{display:flex;flex-wrap:wrap;gap:8px;margin:18px 0 6px}
|
||||
.prose{max-width:72ch}
|
||||
.prose h2{margin:26px 0 10px}
|
||||
.prose li{margin:5px 0}
|
||||
.page{padding-block:30px 56px}
|
||||
.page h1{font-size:clamp(32px,5vw,48px);margin-bottom:12px}
|
||||
.ph-slot{margin:22px 0}
|
||||
|
||||
/* footer */
|
||||
footer.foot{border-top:2px solid var(--ink);margin-top:30px;padding-block:16px 26px;font-size:14px;color:var(--sub)}
|
||||
footer.foot p{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px 14px;margin:0 0 8px}
|
||||
footer.foot a{color:var(--ink);font-weight:700;text-decoration:none;white-space:nowrap}
|
||||
footer.foot a:hover{text-decoration:underline}
|
||||
footer.foot b{color:var(--ink)}
|
||||
footer.foot .here{font-weight:700;color:var(--leafInk)}
|
||||
|
||||
/* toasts of real events */
|
||||
.toasts{position:fixed;left:16px;bottom:16px;z-index:40;display:grid;gap:8px;max-width:min(340px,calc(100vw - 100px))}
|
||||
.toast{display:block;background:var(--packet);color:var(--ink);border:2px solid var(--ink);border-radius:12px;padding:10px 12px;font-size:14px;text-decoration:none;box-shadow:4px 4px 0 var(--ink);opacity:0;transform:translateY(10px);transition:opacity .3s,transform .3s}
|
||||
.toast.in{opacity:1;transform:none}
|
||||
.toast span{color:var(--sub)}
|
||||
|
||||
@media (max-width:900px){.under,.grid2{grid-template-columns:1fr}.bed{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
||||
@media (max-width:700px){
|
||||
.plate{display:block;min-height:0}
|
||||
.plate>img{position:static;display:block;aspect-ratio:16/9;height:auto;max-width:100%}
|
||||
.plate::before{display:none}
|
||||
.plate .copy{padding:20px 18px 24px}
|
||||
}
|
||||
@media (max-width:560px){.bed{grid-template-columns:1fr}.steps{grid-template-columns:1fr}.step{border-right:0;border-bottom:2px dashed var(--line)}.step:last-child{border-bottom:0}nav.links{gap:4px 12px;font-size:14px}}
|
||||
@media (prefers-reduced-motion:no-preference){.bar>span{transition:width .6s ease}}
|
||||
@media (prefers-reduced-motion:reduce){.toast{transition:none}}
|
||||
@@ -0,0 +1,46 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>The contract | YourProgramBuilder</title>
|
||||
<meta name="description" content="YPBShop on Polygon: what it can and cannot do, the split, the owner powers and the 48-hour price timelock.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/contract">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="The contract | YourProgramBuilder"><meta property="og:description" content="YPBShop on Polygon: what it can and cannot do, the split, the owner powers and the 48-hour price timelock."><meta property="og:url" content="https://yourprogrambuilder.com/contract">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<div class="page prose">
|
||||
<div class="kicker">Proof</div>
|
||||
<h1>The contract</h1>
|
||||
<div id="cBox" class="panel"><p>Loading the contract facts...</p></div>
|
||||
<h2>What the contract can do</h2>
|
||||
<ul>
|
||||
<li>Take a one-time Spotlight payment in POL at the live Chainlink POL/USD price, and refund any overpayment in the same transaction.</li>
|
||||
<li>Pay levels 1 to 5 of the buyer's sponsor line (<span data-cfg="sponsor">20%</span>, then <span data-cfg="levels">5% / 5% / 5% / 5%</span>) and the company the rest, in the same transaction.</li>
|
||||
<li>Keep a payment that could not be delivered for its owner to claim. Only that wallet can claim it.</li>
|
||||
</ul>
|
||||
<h2>What it cannot do</h2>
|
||||
<ul>
|
||||
<li>No owner withdraw, no sweep, no upgrade, no proxy. The split is fixed when the contract is deployed and has no setter.</li>
|
||||
<li>A SKU price change is proposed on chain and waits 48 hours before anyone can apply it. Only switching a SKU off is immediate.</li>
|
||||
<li>Pausing stops new Spotlights only; claims stay open.</li>
|
||||
</ul>
|
||||
<p class="muted">Every order is signed by the site's keeper key, which names the buyer's sponsor line from the network hub. The keeper cannot move money: it can only sign orders that the buyer pays.</p>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/pages.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,34 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Earnings disclaimer | YourProgramBuilder</title>
|
||||
<meta name="description" content="YourProgramBuilder is a directory of programs, not an income opportunity.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/disclaimer">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Earnings disclaimer | YourProgramBuilder"><meta property="og:description" content="YourProgramBuilder is a directory of programs, not an income opportunity."><meta property="og:url" content="https://yourprogrambuilder.com/disclaimer">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap">
|
||||
<article class="page prose">
|
||||
|
||||
<h1>Earnings disclaimer</h1><p class="muted">Last updated November 17, 2026.</p>
|
||||
<p>YourProgramBuilder is a directory of programs, not an income opportunity. Nothing on this site promises income, earnings or any result.</p>
|
||||
<p>The programs in the Seed Bed are outside programs planted by members. Whatever they say about earnings is their claim, not ours. Most people who join any program earn little or nothing. Do your own research and never spend money you cannot afford to lose.</p>
|
||||
<p>When someone in your downline buys a Spotlight, the YPBShop contract pays a share to the sponsor line in the same transaction. How much depends entirely on whether anyone in your downline buys, which nobody can predict. A Spotlight buys views, not income.</p>
|
||||
<p>Any figures on this site are examples or live records of what already happened on chain (the <a href="/ledger">ledger</a>), never a forecast.</p>
|
||||
</article>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,30 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>FAQ | YourProgramBuilder</title>
|
||||
<meta name="description" content="Answers to the common questions about the YourProgramBuilder Seed Bed.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/guides/faq">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="FAQ | YourProgramBuilder"><meta property="og:description" content="Answers to the common questions about the YourProgramBuilder Seed Bed."><meta property="og:url" content="https://yourprogrambuilder.com/guides/faq">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
<script type="application/ld+json">{"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "Is YourProgramBuilder free?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Signing in, planting one program and saving IDs are free. A Spotlight is an optional one-time purchase."}}, {"@type": "Question", "name": "How many programs can I plant?", "acceptedAnswer": {"@type": "Answer", "text": "One packet per member at a time. Remove yours to plant a different one. Saving IDs in other packets has no limit."}}, {"@type": "Question", "name": "Why is my packet not showing?", "acceptedAnswer": {"@type": "Answer", "text": "Its link check is yellow (waiting for a person) or red (the link did not load). Check it on My packets. Edits are checked again."}}, {"@type": "Question", "name": "What happens at 25 saves?", "acceptedAnswer": {"@type": "Answer", "text": "The packet goes to Marty's review for the Crypto Team Build Network builder. Approved, it is added there and to DownlineHydra's wild heads with every saved ID. Reaching the number does not guarantee approval."}}, {"@type": "Question", "name": "Whose link does a visitor see?", "acceptedAnswer": {"@type": "Answer", "text": "A visitor through a member sees that member's link first. A signed-in member sees the nearest saved ID up their sponsor line, then the planter's."}}, {"@type": "Question", "name": "Can I plant a program that is already in the builder?", "acceptedAnswer": {"@type": "Answer", "text": "No. Save your ID for it on DownlineHydra's wild heads instead."}}, {"@type": "Question", "name": "Do I need a Spotlight to earn?", "acceptedAnswer": {"@type": "Answer", "text": "No. Spotlight shares go to the buyer's sponsor line, and anyone in it with a network sign-in and a linked wallet is paid. Nothing is promised."}}, {"@type": "Question", "name": "Which wallet do I use?", "acceptedAnswer": {"@type": "Answer", "text": "SafePal or any other crypto wallet on Polygon."}}, {"@type": "Question", "name": "I was a member of the old YourProgramBuilder. What happened to my account?", "acceptedAnswer": {"@type": "Answer", "text": "Old members were matched to the network by email and keep their sponsor. Old links open your new member page. Programs you added come back as dormant packets you confirm on My packets. Old balances were not carried over."}}, {"@type": "Question", "name": "How do I get help?", "acceptedAnswer": {"@type": "Answer", "text": "Network support at instantadpay.com/support handles every network site."}}]}</script>
|
||||
</head>
|
||||
<body data-nav="/guides">
|
||||
<main id="main" class="wrap">
|
||||
<article class="page prose">
|
||||
<div class="kicker"><a href="/guides">Guides</a></div><h1>FAQ</h1><h2>Is YourProgramBuilder free?</h2><p>Yes. Signing in, planting one program and saving IDs are free. A Spotlight is an optional one-time purchase.</p><h2>How many programs can I plant?</h2><p>One packet per member at a time. Remove yours to plant a different one. Saving IDs in other packets has no limit.</p><h2>Why is my packet not showing?</h2><p>Its link check is yellow (waiting for a person) or red (the link did not load). Check it on My packets. Edits are checked again.</p><h2>What happens at 25 saves?</h2><p>The packet goes to Marty's review for the Crypto Team Build Network builder. Approved, it is added there and to DownlineHydra's wild heads with every saved ID. Reaching the number does not guarantee approval.</p><h2>Whose link does a visitor see?</h2><p>A visitor through a member sees that member's link first. A signed-in member sees the nearest saved ID up their sponsor line, then the planter's.</p><h2>Can I plant a program that is already in the builder?</h2><p>No. Save your ID for it on DownlineHydra's wild heads instead.</p><h2>Do I need a Spotlight to earn?</h2><p>No. Spotlight shares go to the buyer's sponsor line, and anyone in it with a network sign-in and a linked wallet is paid. Nothing is promised.</p><h2>Which wallet do I use?</h2><p>SafePal or any other crypto wallet on Polygon.</p><h2>I was a member of the old YourProgramBuilder. What happened to my account?</h2><p>Old members were matched to the network by email and keep their sponsor. Old links open your new member page. Programs you added come back as dormant packets you confirm on My packets. Old balances were not carried over.</p><h2>How do I get help?</h2><p>Network support at instantadpay.com/support handles every network site.</p>
|
||||
</article>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,38 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Getting the most from your free account | YourProgramBuilder</title>
|
||||
<meta name="description" content="Save your IDs, share your member page and plant one program, all free.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/guides/free-account">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Getting the most from your free account | YourProgramBuilder"><meta property="og:description" content="Save your IDs, share your member page and plant one program, all free."><meta property="og:url" content="https://yourprogrambuilder.com/guides/free-account">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/guides">
|
||||
<main id="main" class="wrap">
|
||||
<article class="page prose">
|
||||
|
||||
<div class="kicker"><a href="/guides">Guides</a></div><h1>Getting the most from your free account</h1>
|
||||
<ol>
|
||||
<li><b>Sign in with your network account.</b> One account works across every network site, with the same username and sponsor.</li>
|
||||
<li><b>Save your ID in the programs you have joined.</b> Open a packet, tap Save my ID, type your ID or paste your referral link. Your saved IDs also count toward the packet's review.</li>
|
||||
<li><b>Share your member page.</b> yourprogrambuilder.com/your-username lists the programs you saved, each opening with your link. The <a href="/promote">promo kit</a> has banners and lines with your link filled in.</li>
|
||||
<li><b>Plant one program.</b> If a program you use is not in the Seed Bed or the CTB builder yet, plant it.</li>
|
||||
<li><b>Link a wallet on InstantAdPay.</b> Sponsor shares from Spotlights go to members with a linked wallet; without one, your share passes up.</li>
|
||||
</ol>
|
||||
<p class="muted">Nothing here needs a purchase. Nothing is promised.</p>
|
||||
</article>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,39 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>How the Seed Bed works | YourProgramBuilder</title>
|
||||
<meta name="description" content="Plant a program, save referral IDs, and how a program moves into the Crypto Team Build Network builder.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/guides/how-it-works">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="How the Seed Bed works | YourProgramBuilder"><meta property="og:description" content="Plant a program, save referral IDs, and how a program moves into the Crypto Team Build Network builder."><meta property="og:url" content="https://yourprogrambuilder.com/guides/how-it-works">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/guides">
|
||||
<main id="main" class="wrap">
|
||||
<article class="page prose">
|
||||
|
||||
<div class="kicker"><a href="/guides">Guides</a></div><h1>How the Seed Bed works</h1>
|
||||
<p>YourProgramBuilder is where new programs enter the network. Members plant them, the network saves referral IDs in them, and the ones that grow are reviewed for the Crypto Team Build Network builder.</p>
|
||||
<h2>1. Plant</h2>
|
||||
<p>A network member plants a program: its name, their referral link with {id} where the ID goes, their own ID, a sentence on what it is, whether it is free or paid to join, and the contract address if it is a crypto program. Planting is free, one packet per member at a time. The link is checked before the packet shows and again every day: green shows straight away, yellow waits for a person to look, red is refused.</p>
|
||||
<h2>2. Sprout</h2>
|
||||
<p>Any member can save their referral ID in any packet. A visitor who comes through a member (their page at yourprogrambuilder.com/their-username) sees that member's link first. A signed-in member sees the link of the nearest person above them in their network sponsor line who saved an ID, and the planter's link when nobody did.</p>
|
||||
<h2>3. Transplant</h2>
|
||||
<p>Each packet has a sprout meter: saved IDs from distinct confirmed network members, out of <span data-cfg="need">25</span>. At <span data-cfg="need">25</span> it goes to Marty's review queue and keeps sprouting while it waits. Approved, it is added to the Crypto Team Build Network builder, and so to DownlineHydra's wild heads, with every saved ID carried over. Reaching the number does not guarantee approval.</p>
|
||||
<h2>Spotlights</h2>
|
||||
<p>A one-time Spotlight (<span data-cfg="spotUsd">$10</span> for <span data-cfg="spotViews">1,000</span> guaranteed views) puts a packet at the top of the Seed Bed until its views are delivered. It is optional: planting and saving IDs are free. <a href="/spotlight">More about Spotlights</a>.</p>
|
||||
</article>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,42 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Is YourProgramBuilder legit? | YourProgramBuilder</title>
|
||||
<meta name="description" content="The contract, the ledger and the split, and what the Seed Bed does and does not check.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/guides/is-it-legit">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Is YourProgramBuilder legit? | YourProgramBuilder"><meta property="og:description" content="The contract, the ledger and the split, and what the Seed Bed does and does not check."><meta property="og:url" content="https://yourprogrambuilder.com/guides/is-it-legit">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/guides">
|
||||
<main id="main" class="wrap">
|
||||
<article class="page prose">
|
||||
|
||||
<div class="kicker"><a href="/guides">Guides</a></div><h1>Is YourProgramBuilder legit?</h1>
|
||||
<p>Two separate questions: can you trust the site, and can you trust the programs in it.</p>
|
||||
<h2>The programs in the Seed Bed</h2>
|
||||
<p>They are outside programs planted by members. The site checks that each link loads, is not a shortener or a private address, and does not promise income in its description, and it rechecks every day. It does not check the business behind a program. A packet is its planter's description, not a recommendation: read each program's terms, and if a program has a contract address, look it up before you send anything.</p>
|
||||
<h2>The Spotlight money</h2>
|
||||
<ul>
|
||||
<li>Every Spotlight is paid to the YPBShop contract on Polygon. Its address and source are on the <a href="/contract">contract page</a> once it is deployed.</li>
|
||||
<li>The contract splits each payment in the same transaction: <span data-cfg="sponsor">20%</span> to the buyer's sponsor, <span data-cfg="lvlEach">5%</span> each to levels 2 to 5, <span data-cfg="company">60%</span> to the company. The split is fixed and has no setter.</li>
|
||||
<li>No owner withdraw, no sweep, no upgrade. Price changes wait 48 hours on chain.</li>
|
||||
<li>No earlier buyer is ever paid from a later buyer: the shares go to the buyer's own sponsor line on a product that is delivered (views).</li>
|
||||
<li>Every payment shows on the <a href="/ledger">live ledger</a> with its transaction.</li>
|
||||
</ul>
|
||||
<p>Nothing is promised. See the <a href="/disclaimer">earnings disclaimer</a>.</p>
|
||||
</article>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,38 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Planting a program that grows | YourProgramBuilder</title>
|
||||
<meta name="description" content="How to write a packet that passes the link check and gets saved IDs.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/guides/planting">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Planting a program that grows | YourProgramBuilder"><meta property="og:description" content="How to write a packet that passes the link check and gets saved IDs."><meta property="og:url" content="https://yourprogrambuilder.com/guides/planting">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/guides">
|
||||
<main id="main" class="wrap">
|
||||
<article class="page prose">
|
||||
|
||||
<div class="kicker"><a href="/guides">Guides</a></div><h1>Planting a program that grows</h1>
|
||||
<h2>Get the link right</h2>
|
||||
<p>Copy your referral link from the program, then replace your ID in it with {id}. For example, if your link is https://program.example/?ref=jane, plant https://program.example/?ref={id} and type jane as your own ID. Use the program's real address, never a shortener, and https where the program has it.</p>
|
||||
<h2>Say what it is, plainly</h2>
|
||||
<p>One or two sentences: what the program does and what a member gets. No income claims, no "guaranteed", no links in the description. Packets with flagged words wait for a person to look.</p>
|
||||
<h2>Be honest about the cost</h2>
|
||||
<p>Pick free or paid, and for paid say what it costs to join. If it runs on a contract, add the address so members can look it up.</p>
|
||||
<h2>Help it sprout</h2>
|
||||
<p>Tell the people you work with to save their IDs in it. Every visitor who comes through them sees their link first, so saving an ID is worth it for them too. A Spotlight is optional.</p>
|
||||
</article>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,31 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Guides | YourProgramBuilder</title>
|
||||
<meta name="description" content="Guides to the YourProgramBuilder Seed Bed: how it works, is it legit, your free account, planting and the FAQ.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/guides">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Guides | YourProgramBuilder"><meta property="og:description" content="Guides to the YourProgramBuilder Seed Bed: how it works, is it legit, your free account, planting and the FAQ."><meta property="og:url" content="https://yourprogrambuilder.com/guides">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/guides">
|
||||
<main id="main" class="wrap">
|
||||
<article class="page prose">
|
||||
|
||||
<div class="kicker">Guides</div><h1>YourProgramBuilder guides</h1>
|
||||
<p>Short guides to the Seed Bed, checked against how the site really works.</p><ul><li><a href="/guides/how-it-works">How the Seed Bed works</a></li><li><a href="/guides/is-it-legit">Is YourProgramBuilder legit?</a></li><li><a href="/guides/free-account">Getting the most from your free account</a></li><li><a href="/guides/planting">Planting a program that grows</a></li><li><a href="/guides/faq">FAQ</a></li></ul>
|
||||
</article>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,68 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>YourProgramBuilder: the Seed Bed</title>
|
||||
<meta name="description" content="Plant your program in the Seed Bed and members across the network save their referral ID in it. The ones that grow go to review for the Crypto Team Build Network builder.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="YourProgramBuilder: the Seed Bed"><meta property="og:description" content="Plant your program in the Seed Bed and members across the network save their referral ID in it. The ones that grow go to review for the Crypto Team Build Network builder."><meta property="og:url" content="https://yourprogrambuilder.com/">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<section class="plate" id="top" data-art="illustration" aria-labelledby="heroTitle">
|
||||
<img id="heroImg" src="/art/hero-botanical-illustration.webp" srcset="/art/hero-botanical-illustration-900.webp 900w, /art/hero-botanical-illustration.webp 1600w" sizes="(max-width:700px) 100vw, 1180px" width="1600" height="900" alt="Botanical drawing of a seed sprouting, growing into a plant with a tangerine bud, and moving into its own pot" fetchpriority="high">
|
||||
<div class="copy">
|
||||
<div class="kicker">Open to every program</div>
|
||||
<h1 id="heroTitle">Bring your program. <em>The network grows it.</em></h1>
|
||||
<p class="lede">Plant your program in the Seed Bed and members across the network can save their referral ID in it. When <span data-cfg="need">25</span> members have saved an ID, it goes to review for the Crypto Team Build Network builder, and every saved ID moves with it.</p>
|
||||
<div class="ctas"><a class="btn primary" href="/my?tab=plant"><span data-icon="iconGardening"></span>Plant a program, free</a><a class="btn ghost" href="#bed">Browse the Seed Bed</a></div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="under" id="how">
|
||||
<div class="steps">
|
||||
<div class="step"><span data-icon="iconGardening"></span><i>STEP 1</i><b>Plant</b><span>Add the program and its referral link. Every link is checked before it shows, and again every day.</span></div>
|
||||
<div class="step"><span data-icon="iconSprout"></span><i>STEP 2</i><b>Sprout</b><span>Members save their ID. Visitors from a member see that member's link first.</span></div>
|
||||
<div class="step"><span data-icon="iconSeed"></span><i>STEP 3</i><b>Transplant</b><span>At <span data-cfg="need">25</span> saves Marty reviews it for the builder. Listed in the builder, it shows in DownlineHydra too.</span></div>
|
||||
</div>
|
||||
<aside class="spot" aria-labelledby="spotTitle">
|
||||
<span data-icon="sprig02"></span>
|
||||
<div class="kicker"><span data-icon="iconEvolution"></span>One-time, paid in POL</div>
|
||||
<h2 id="spotTitle">Spotlight a packet</h2>
|
||||
<div class="price"><span data-cfg="spotUsd">$10</span> <small>for <span data-cfg="spotViews">1,000</span> guaranteed views</small></div>
|
||||
<ul>
|
||||
<li>Top row of the Seed Bed until the views are delivered</li>
|
||||
<li>The Spotlight strip on packet and member pages</li>
|
||||
<li>Every verified view counted, shown live on your packet</li>
|
||||
</ul>
|
||||
<div class="split">Split on chain at purchase: <span data-cfg="sponsor">20%</span> to your sponsor, <span data-cfg="lvlEach">5%</span> each to levels 2 to 5, <span data-cfg="company">60%</span> to the company. No subscription. See the <a href="/contract">contract</a> and the <a href="/ledger">ledger</a>.</div>
|
||||
<p style="margin:12px 0 0"><a class="btn sm ink" href="/spotlight">About Spotlights</a></p>
|
||||
</aside>
|
||||
</section>
|
||||
<section id="spots" hidden aria-labelledby="spotsTitle"><div class="bedhead"><div class="t"><h2 id="spotsTitle">In the Spotlight</h2></div></div><div class="bed spotrow"></div></section>
|
||||
<section id="bed" aria-labelledby="bedTitle">
|
||||
<div class="bedhead">
|
||||
<div class="t"><span data-icon="sprig10"></span><h2 id="bedTitle">The Seed Bed</h2></div>
|
||||
<div class="filters" role="group" aria-label="Filter packets">
|
||||
<button class="chip" type="button" data-f="all" aria-pressed="true">All</button><button class="chip" type="button" data-f="sprouting" aria-pressed="false">Sprouting</button><button class="chip" type="button" data-f="review" aria-pressed="false">Ready for review</button><button class="chip" type="button" data-f="free" aria-pressed="false">Free to join</button><button class="chip" type="button" data-f="crypto" aria-pressed="false">Crypto</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bed" id="bedList"><p class="empty">Loading the Seed Bed...</p></div>
|
||||
<p class="muted" style="font-size:14px">Programs in the Seed Bed are planted by members. They are outside programs: read each one's own terms before you join. A packet is the planter's description, not a recommendation.</p>
|
||||
</section>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/front.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,35 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Live ledger | YourProgramBuilder</title>
|
||||
<meta name="description" content="Every Spotlight paid to the YPBShop contract, with its split and its delivery, read from the chain.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/ledger">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Live ledger | YourProgramBuilder"><meta property="og:description" content="Every Spotlight paid to the YPBShop contract, with its split and its delivery, read from the chain."><meta property="og:url" content="https://yourprogrambuilder.com/ledger">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<div class="page">
|
||||
<div class="kicker">Proof</div>
|
||||
<h1>Live ledger</h1>
|
||||
<p class="muted prose">Every Spotlight, read from the Polygon chain: who was paid at each level, what went to the company, and how many of its views were delivered. Nothing here is typed in by hand.</p>
|
||||
<div class="stats" id="ledgerStats"></div>
|
||||
<section id="ledgerBox"><div class="tbl"><table><thead><tr><th>When</th><th>Buyer</th><th>Packet</th><th>Paid</th><th>Split</th><th>Delivery</th></tr></thead><tbody id="rows"><tr><td colspan="6" class="muted">Loading...</td></tr></tbody></table></div></section>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/pages.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>A member's programs | YourProgramBuilder</title>
|
||||
<meta name="description" content="The programs a network member saved their referral ID in, in the YourProgramBuilder Seed Bed. Their links come first for you.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="A member's programs | YourProgramBuilder"><meta property="og:description" content="The programs a network member saved their referral ID in, in the YourProgramBuilder Seed Bed. Their links come first for you."><meta property="og:url" content="https://yourprogrambuilder.com/">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<div class="page">
|
||||
<div class="kicker">Member page</div>
|
||||
<h1 id="mTitle">A member's programs</h1>
|
||||
<p class="muted prose" id="mLede">Every program here opens with this member's own referral link. Join the network free and save your own IDs, so the people you bring see yours.</p>
|
||||
<p class="row"><a class="btn primary" id="mJoin" href="https://instantadpay.com/">Join the network free</a><a class="btn" href="/">See the whole Seed Bed</a></p>
|
||||
<div class="bed" id="mList"><p class="empty">Loading...</p></div>
|
||||
<section id="spots" hidden><div class="bedhead"><div class="t"><h2>In the Spotlight</h2></div></div><div class="bed spotrow"></div></section>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/member.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,82 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>My packets | YourProgramBuilder</title>
|
||||
<meta name="description" content="Plant a program, manage your packet, your saved IDs and your Spotlights.">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="My packets | YourProgramBuilder"><meta property="og:description" content="Plant a program, manage your packet, your saved IDs and your Spotlights."><meta property="og:url" content="https://yourprogrambuilder.com/my">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/my">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<div class="page">
|
||||
<h1>My packets</h1>
|
||||
<section id="signin" class="panel" hidden>
|
||||
<h2>Sign in</h2>
|
||||
<p class="muted">Use your network account (one account across the network), or sign with your wallet: a free signature that cannot move funds.</p>
|
||||
<div class="row" style="margin-top:14px"><a class="btn ink" href="/sso/start?mode=go&to=/my">Sign in with my network account</a><button class="btn" id="walletBtn" type="button">Sign in with my wallet</button></div>
|
||||
<p class="muted" style="font-size:14px;margin:12px 0 0">Wallet: SafePal or any other crypto wallet on Polygon. Not a member yet? <a id="joinLink" href="https://instantadpay.com/?return=yourprogrambuilder&to=%2Fmy">Join free</a>.</p>
|
||||
</section>
|
||||
<div id="dash" hidden>
|
||||
<p class="muted" id="who"></p>
|
||||
<div class="stats" id="myStats"></div>
|
||||
<div class="tabs" role="tablist" aria-label="My packets">
|
||||
<button class="chip" type="button" role="tab" data-tab="packets" aria-pressed="true">My packet</button><button class="chip" type="button" role="tab" data-tab="plant" aria-pressed="false">Plant a program</button><button class="chip" type="button" role="tab" data-tab="saved" aria-pressed="false">My saved IDs</button><button class="chip" type="button" role="tab" data-tab="spot" aria-pressed="false">Spotlights and earnings</button>
|
||||
</div>
|
||||
<section class="panel" data-pane="packets">
|
||||
<h2>My packet</h2>
|
||||
<div id="dormant" hidden class="note warn"></div>
|
||||
<div id="myPackets"><p class="muted">Nothing planted yet. <a href="/my?tab=plant">Plant a program</a>.</p></div>
|
||||
<div id="pageBox" hidden style="margin-top:14px"><p style="margin:0 0 6px;font-weight:700">Your member page (your links first)</p><div class="sharebox"><span id="pageUrl"></span><button class="btn sm" type="button" id="copyPage">Copy</button></div></div>
|
||||
</section>
|
||||
<section class="panel" data-pane="plant" hidden>
|
||||
<h2 id="plantTitle">Plant a program</h2>
|
||||
<p class="muted" style="font-size:15px">Free for network members: <span data-cfg="quota">1</span> packet at a time. Programs already in the Crypto Team Build Network builder are not planted again (save your ID for those on DownlineHydra).</p>
|
||||
<form class="stack" id="plantForm" autocomplete="off" style="margin-top:10px">
|
||||
<input type="hidden" id="editId"><input type="hidden" id="dormantId">
|
||||
<label class="f">Your referral link, with {id} where your ID goes <small>for example https://program.example/?ref={id}</small><input type="url" id="url" placeholder="https://" required></label>
|
||||
<label class="f">Your own referral ID <small>it fills {id} in your link, so your packet works from the first visit</small><input type="text" id="myId" maxlength="64" required></label>
|
||||
<div id="aiBox" hidden class="note"><div class="row" style="justify-content:space-between"><span>No words yet? Let the writer read the program's page</span><button type="button" class="btn sm" id="aiWrite">Write it from my link</button></div><div id="aiList"></div></div>
|
||||
<label class="f">Program name <small>2 to 40 characters</small><input type="text" id="name" maxlength="40" required></label>
|
||||
<label class="f">What it is <small>one or two sentences, 10 to 200 characters, no links</small><textarea id="desc" maxlength="200" required></textarea></label>
|
||||
<fieldset class="f" style="border:0;padding:0;margin:0"><legend style="font-weight:700">Cost to join</legend><div class="radios"><label><input type="radio" name="cost" value="free" checked> Free to join</label><label><input type="radio" name="cost" value="paid"> Costs money to join</label></div></fieldset>
|
||||
<label class="f" id="costRow" hidden>What it costs <small>for example "$10 one-time" or "from 25 POL"</small><input type="text" id="costText" maxlength="40"></label>
|
||||
<label class="f">Contract address <small>optional, only if the program runs on a blockchain contract</small><input type="text" id="contract" maxlength="42" placeholder="0x..."></label>
|
||||
<label class="f">Category<select id="cat"></select></label>
|
||||
<p class="muted" style="font-size:14px;margin:0">Every link is checked before it shows and again every day. Green shows straight away; yellow waits for a person to look; red is refused. Do not promise income in your description.</p>
|
||||
<div class="row"><button class="btn primary" type="submit" id="plantBtn">Plant it</button><button class="btn sm" type="button" id="cancelEdit" hidden>Cancel the edit</button></div>
|
||||
</form>
|
||||
<p id="status" class="note" hidden></p>
|
||||
</section>
|
||||
<section class="panel" data-pane="saved" hidden>
|
||||
<h2>My saved IDs</h2>
|
||||
<div class="tbl"><table><thead><tr><th>Program</th><th>My ID</th><th>Saves</th><th>Clicks to my link</th><th>Stage</th></tr></thead><tbody id="savedRows"><tr><td colspan="5" class="muted">Open any packet in the <a href="/#bed">Seed Bed</a> and tap Save my ID.</td></tr></tbody></table></div>
|
||||
</section>
|
||||
<section class="panel" data-pane="spot" hidden>
|
||||
<h2>Spotlights and earnings</h2>
|
||||
<p class="muted" style="font-size:15px">When someone in your downline buys a Spotlight, the contract pays your level in the same transaction. You never need to buy one to be paid: a network sign-in and a linked wallet are enough.</p>
|
||||
<div class="stats" id="earnStats"></div>
|
||||
<div class="tbl"><table><thead><tr><th>When</th><th>Spotlight</th><th>Views</th><th>Status</th></tr></thead><tbody id="spotRows"><tr><td colspan="4" class="muted">No Spotlights bought yet.</td></tr></tbody></table></div>
|
||||
<div class="tbl"><table><thead><tr><th>When</th><th>Level</th><th>Amount</th><th>From</th></tr></thead><tbody id="earnRows"><tr><td colspan="4" class="muted">Nothing yet.</td></tr></tbody></table></div>
|
||||
</section>
|
||||
<div class="row" style="margin-top:22px"><button class="btn sm" id="logout" type="button">Sign out</button><button class="btn sm" id="logoutAll" type="button">Sign out everywhere</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/wallet.js?v=20261117a"></script>
|
||||
<script src="/assets/my.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,63 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>A packet in the Seed Bed | YourProgramBuilder</title>
|
||||
<meta name="description" content="A program planted in the YourProgramBuilder Seed Bed: save your referral ID and see how close it is to the Crypto Team Build Network builder.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="A packet in the Seed Bed | YourProgramBuilder"><meta property="og:description" content="A program planted in the YourProgramBuilder Seed Bed: save your referral ID and see how close it is to the Crypto Team Build Network builder."><meta property="og:url" content="https://yourprogrambuilder.com/">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<div class="page">
|
||||
<p class="muted" style="margin:0 0 8px"><a href="/#bed">The Seed Bed</a></p>
|
||||
<div class="grid2">
|
||||
<div id="pk"><article class="pk"><div class="fold"></div><div class="body"><p>Loading the packet...</p></div></article></div>
|
||||
<aside class="stack">
|
||||
<section class="panel" id="save">
|
||||
<h2 style="font-size:24px">Save my ID</h2>
|
||||
<p class="muted" style="font-size:15px">Type your referral ID for this program, or paste your whole referral link for it. Anyone who comes through you sees your link first.</p>
|
||||
<div id="saveSignin" hidden><p><a class="btn ink sm" href="/sso/start?mode=go&to=/my">Sign in with the network</a></p><p class="muted" style="font-size:14px">Not a member yet? <a id="joinLink" href="https://instantadpay.com/">Join the network free</a>, then come back.</p></div>
|
||||
<form id="saveForm" class="stack" hidden autocomplete="off">
|
||||
<label class="f">Your referral ID <small id="idHint"></small><input type="text" id="refId" maxlength="300" required></label>
|
||||
<label class="row" style="gap:8px;font-size:14px;font-weight:400"><input type="checkbox" id="track" checked> Track my clicks with LinkSpin when it is switched on</label>
|
||||
<div class="row"><button class="btn primary sm" type="submit" id="saveBtn">Save my ID</button><button class="btn sm" type="button" id="removeBtn" hidden>Remove my ID</button></div>
|
||||
</form>
|
||||
<p id="status" class="note" hidden></p>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<h2 style="font-size:22px">Whose link you get</h2>
|
||||
<p class="muted" style="font-size:15px" id="linkWho">The nearest person in your sponsor line who saved an ID, then the planter's.</p>
|
||||
<p><a class="btn sm" id="visitBtn" target="_blank" rel="noopener sponsored nofollow" href="#">Visit the program</a></p>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<h2 style="font-size:20px">Something wrong with this packet?</h2>
|
||||
<form id="reportForm" class="stack" autocomplete="off">
|
||||
<label class="f">What is wrong<select id="reason"><option value="broken">The link is broken</option><option value="scam">It looks like a scam</option><option value="wrong">The description is wrong</option><option value="other">Something else</option></select></label>
|
||||
<label class="f">Note <small>optional</small><input type="text" id="reportNote" maxlength="200"></label>
|
||||
<button class="btn sm" type="submit">Report it</button>
|
||||
</form>
|
||||
<p id="reportStatus" class="note" hidden></p>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
<section class="panel" id="savers" hidden style="margin-top:18px"><h2 style="font-size:22px">Recently saved by</h2><p id="saverList" class="muted"></p></section>
|
||||
<section id="spots" hidden style="margin-top:22px"><div class="bedhead"><div class="t"><h2>In the Spotlight</h2></div></div><div class="bed spotrow"></div></section>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/packet.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,44 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Privacy | YourProgramBuilder</title>
|
||||
<meta name="description" content="What YourProgramBuilder stores and why.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/privacy">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Privacy | YourProgramBuilder"><meta property="og:description" content="What YourProgramBuilder stores and why."><meta property="og:url" content="https://yourprogrambuilder.com/privacy">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap">
|
||||
<article class="page prose">
|
||||
|
||||
<h1>Privacy</h1><p class="muted">Last updated November 17, 2026.</p>
|
||||
<p>YourProgramBuilder is run by TrustClickz.</p>
|
||||
<h2>What we store</h2>
|
||||
<ul>
|
||||
<li>Your wallet address and network username (from the network hub, the one record of your account across the network). This site never stores your email.</li>
|
||||
<li>The packets you plant and the referral IDs you save.</li>
|
||||
<li>Verified visit records: a one-way hash of your connection and browser, kept 15 days, to count views and clicks fairly. Spotlight view records are kept 120 days as the delivery record.</li>
|
||||
<li>Spotlight purchases, which are public on the Polygon blockchain.</li>
|
||||
</ul>
|
||||
<h2>Who sees it</h2>
|
||||
<p>Your username, your packets and the programs you saved an ID in are public on your member page. Your saved IDs are used to build the referral links visitors see. When a packet is approved, its saved IDs are shared with the Crypto Team Build Network builder and DownlineHydra. We do not sell your data.</p>
|
||||
<h2>Cookies</h2>
|
||||
<p>A sign-in cookie, and a cookie that remembers which member sent you (for 30 days), so their link comes first.</p>
|
||||
<h2>Your choices</h2>
|
||||
<p>Remove a saved ID or your packet any time on <a href="/my">My packets</a>. To erase your network account, open <a href="https://instantadpay.com/support?from=yourprogrambuilder">network support</a>.</p>
|
||||
</article>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,38 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Promote YourProgramBuilder | YourProgramBuilder</title>
|
||||
<meta name="description" content="Banners, swipe copy and your own tracked link to bring people to the Seed Bed.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/promote">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Promote YourProgramBuilder | YourProgramBuilder"><meta property="og:description" content="Banners, swipe copy and your own tracked link to bring people to the Seed Bed."><meta property="og:url" content="https://yourprogrambuilder.com/promote">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<div class="page">
|
||||
<div class="kicker">Promo kit</div>
|
||||
<h1>Promote the Seed Bed</h1>
|
||||
<p class="muted prose">Your link opens your member page, where every program shows your own referral link first. Sign in to fill your username into every banner and line below.</p>
|
||||
<div class="sharebox" style="margin:14px 0"><span id="myLink">https://yourprogrambuilder.com/</span><button class="btn sm" type="button" id="copyLink">Copy</button></div>
|
||||
<section class="panel"><h2>Swipe lines</h2><div id="lines"></div></section>
|
||||
<section class="panel"><h2>Email</h2><div id="email"></div></section>
|
||||
<section class="panel"><h2>Banners</h2><div id="creatives" class="stack"></div></section>
|
||||
<p class="muted" id="kitNote"></p>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/pages.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,55 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Spotlight a packet | YourProgramBuilder</title>
|
||||
<meta name="description" content="A one-time Spotlight: guaranteed verified views for one packet at the top of the Seed Bed, paid in POL and split on chain.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/spotlight">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Spotlight a packet | YourProgramBuilder"><meta property="og:description" content="A one-time Spotlight: guaranteed verified views for one packet at the top of the Seed Bed, paid in POL and split on chain."><meta property="og:url" content="https://yourprogrambuilder.com/spotlight">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/spotlight">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<div class="page">
|
||||
<div class="grid2">
|
||||
<div class="prose">
|
||||
<div class="kicker">One-time, paid in POL</div>
|
||||
<h1>Spotlight a packet</h1>
|
||||
<p><span data-cfg="spotUsd">$10</span> buys <span data-cfg="spotViews">1,000</span> guaranteed verified views for one packet: the top row of the Seed Bed and the Spotlight strip on packet and member pages, until every view is delivered. A program owner can spotlight their own packet, and any member can spotlight a packet they want to grow. It is never a subscription.</p>
|
||||
<h2>Where the money goes</h2>
|
||||
<p>The YPBShop contract on Polygon splits each Spotlight in the same transaction: <span data-cfg="sponsor">20%</span> to the buyer's sponsor, <span data-cfg="lvlEach">5%</span> each to levels 2 to 5 of the buyer's sponsor line, and <span data-cfg="company">60%</span> to the company. Only network members with a linked wallet are paid; anyone without one is skipped and the share passes up. A level with nobody in it goes to the company. The split is fixed in the contract and can never change, and the contract has no owner withdraw.</p>
|
||||
<h2>What counts as a view</h2>
|
||||
<p>A view counts when the Spotlight place was on screen for 6 seconds or more in a real browser, once per visitor per packet per 24 hours, never the planter's own. Views not delivered on the site within <span data-cfg="deliverDays">30</span> days are finished in the network.</p>
|
||||
<p class="muted">Paid in POL with SafePal or any other crypto wallet. Blockchain payments are final. A Spotlight buys views, not income.</p>
|
||||
</div>
|
||||
<section class="panel" id="buyBox">
|
||||
<h2>Buy a Spotlight</h2>
|
||||
<p id="notYet" class="note warn" hidden>Spotlights are not on sale yet: the contract is not deployed. Plant and save IDs for free in the meantime.</p>
|
||||
<form class="stack" id="buyForm" autocomplete="off">
|
||||
<label class="f">Packet <small>any packet in the Seed Bed</small><select id="pkPick"></select></label>
|
||||
<label class="f">How many <small>each adds <span data-cfg="spotViews">1,000</span> views</small><input type="number" id="qty" min="1" max="10" value="1"></label>
|
||||
<p id="quote" class="muted"></p>
|
||||
<button class="btn primary" type="submit" id="buyBtn" disabled>Buy the Spotlight</button>
|
||||
</form>
|
||||
<p id="status" class="note" hidden></p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/wallet.js?v=20261117a"></script>
|
||||
<script src="/assets/buy.js?v=20261117a"></script>
|
||||
<script src="/assets/spotlight.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,50 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Terms | YourProgramBuilder</title>
|
||||
<meta name="description" content="The terms for using YourProgramBuilder.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/terms">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Terms | YourProgramBuilder"><meta property="og:description" content="The terms for using YourProgramBuilder."><meta property="og:url" content="https://yourprogrambuilder.com/terms">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap">
|
||||
<article class="page prose">
|
||||
|
||||
<h1>Terms</h1><p class="muted">Last updated November 17, 2026.</p>
|
||||
<p>YourProgramBuilder (yourprogrambuilder.com) is run by TrustClickz. By using the site you agree to these terms.</p>
|
||||
<h2>What the site is</h2>
|
||||
<p>A directory where network members plant outside programs and save their own referral IDs in them. YourProgramBuilder does not run, own or check the business of the programs in the Seed Bed. A packet is its planter's description, not a recommendation, and not financial advice. Read each program's own terms before you join it.</p>
|
||||
<h2>Accounts</h2>
|
||||
<p>You sign in with your network account (InstantAdPay or LinkSpin, through the network sign-in) or with your wallet. You are responsible for your account and your wallet. One person, one network account.</p>
|
||||
<h2>Planting and saving IDs</h2>
|
||||
<ul>
|
||||
<li>Plant only programs you have joined, with your own referral link. No adult content, gambling, illegal products, malware, misleading claims or promises of income.</li>
|
||||
<li>Every link is checked before it shows and again every day. We may hold, hide or remove any packet or saved ID at any time, for example after a failed check or member reports.</li>
|
||||
<li>Reaching the review threshold sends a packet to review; it does not guarantee that it is added to the Crypto Team Build Network builder.</li>
|
||||
<li>When a packet is approved, its name, link, description and the saved IDs of network members are copied to the Crypto Team Build Network builder and DownlineHydra.</li>
|
||||
</ul>
|
||||
<h2>Spotlights</h2>
|
||||
<p>A Spotlight is a one-time purchase of guaranteed verified views for one packet, paid in POL on Polygon to the YPBShop contract. It is never a subscription. The contract splits each payment in the same transaction as described on the <a href="/contract">contract page</a>. Blockchain payments are final and cannot be reversed. If a packet is removed for breaking these terms, views not yet delivered are not delivered or refunded. A Spotlight buys views, not income.</p>
|
||||
<h2>No promises</h2>
|
||||
<p>Nothing on the site promises income or any result. See the <a href="/disclaimer">earnings disclaimer</a>.</p>
|
||||
<h2>Liability</h2>
|
||||
<p>The site is provided as it is. To the extent the law allows, TrustClickz is not liable for losses from programs listed in the Seed Bed, from wallet or network problems, or from the site being unavailable.</p>
|
||||
<h2>Contact</h2>
|
||||
<p>Network support: <a href="https://instantadpay.com/support?from=yourprogrambuilder">instantadpay.com/support</a>.</p>
|
||||
</article>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,34 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Transplanted | YourProgramBuilder</title>
|
||||
<meta name="description" content="Programs that grew in the Seed Bed and were approved for the Crypto Team Build Network builder, with every saved ID carried over.">
|
||||
<link rel="canonical" href="https://yourprogrambuilder.com/transplanted">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="YourProgramBuilder">
|
||||
<meta property="og:title" content="Transplanted | YourProgramBuilder"><meta property="og:description" content="Programs that grew in the Seed Bed and were approved for the Crypto Team Build Network builder, with every saved ID carried over."><meta property="og:url" content="https://yourprogrambuilder.com/transplanted">
|
||||
<meta property="og:image" content="https://yourprogrambuilder.com/art/og-share.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta property="og:image:alt" content="YourProgramBuilder: bring your program, the network grows it">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://yourprogrambuilder.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#12291F">
|
||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Young+Serif&family=Atkinson+Hyperlegible:wght@400;700&family=Martian+Mono:wght@400;600&display=swap">
|
||||
<link rel="stylesheet" href="/assets/ypb.css?v=20261117a">
|
||||
</head>
|
||||
<body data-nav="/transplanted">
|
||||
<main id="main" class="wrap">
|
||||
|
||||
<div class="page">
|
||||
<div class="kicker">Grown in the Seed Bed</div>
|
||||
<h1>Transplanted</h1>
|
||||
<p class="muted prose">These programs reached <span data-cfg="need">25</span> saved IDs, went to review, and were approved for the Crypto Team Build Network builder. In the builder they also show on DownlineHydra's wild heads, with every saved ID carried over. <span id="inReview"></span></p>
|
||||
<div class="bed" id="tList"><p class="empty">Loading...</p></div>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/assets/icons.js?v=20261117a"></script>
|
||||
<script src="/assets/common.js?v=20261117a"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/pages.js?v=20261117a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,280 @@
|
||||
// YourProgramBuilder end-to-end test on a local anvil chain (no fork, nothing leaves this machine, no real POL, no real people).
|
||||
// Deploys the real YPBShop (../contracts/out) with a mock Chainlink feed at $0.25, boots the app against it with a stand-in hub, and
|
||||
// walks the whole product through the app's own HTTP API:
|
||||
// pages (no dashes, no street address); sign-in by wallet, membership + usernames from the hub; planting rules (needs {id}, the
|
||||
// CTB builder and network sites refused, quota, twin, a yellow packet held for the queue); saved IDs (an ID, a pasted whole link,
|
||||
// a bad ID, the planter, unsigned, not a member); the sponsor-first link (anonymous -> planter, a member page / ?r= -> that member,
|
||||
// a signed-in member -> nearest saved ID up their hub line); the sprout meter reaching REVIEW_SAVES -> Marty's review queue ->
|
||||
// approve -> the export carries every saved ID in the builder's {affiliateid} form; reports hold a packet, admin shows it again;
|
||||
// verified visits; a Spotlight bought on chain: level 1 + level 2 to the wei with compression over a no-wallet and a blocked
|
||||
// member, the 3 empty levels to the company (75% in all), the overpay refunded; the watcher, the ledger, the contract page,
|
||||
// Spotlight delivery counted only in the Spotlight places; old links; dormant old programs confirmed by their owner; the chatbot.
|
||||
// node qa/e2e.mjs (needs anvil ~/.foundry/bin and `forge build` output in ../contracts/out)
|
||||
import { spawn } from 'node:child_process';
|
||||
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';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { ethers } = require('ethers');
|
||||
|
||||
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
|
||||
const ANVIL = process.env.ANVIL || path.join(os.homedir(), '.foundry', 'bin', process.platform === 'win32' ? 'anvil.exe' : 'anvil');
|
||||
const ART = path.resolve(APP, '..', 'contracts', 'out');
|
||||
const APORT = 8583, PORT = 3361, HPORT = PORT + 1;
|
||||
const RPC = 'http://127.0.0.1:' + APORT, BASE = 'http://127.0.0.1:' + PORT, ADMIN = 'e2e-admin-token-123', HUB_SECRET = 'e'.repeat(40);
|
||||
const K = ['0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',
|
||||
'0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a', '0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6',
|
||||
'0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a', '0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba',
|
||||
'0x92db14e403b83dfe3df233f83dfa3a0d7096f21ca9b0d6d6b8d88b2b4ec1564e', '0x4bbbf85ce3377467afe5d46f804f221813b2bb87f24d81f60f1fcdbf7cbf4356',
|
||||
'0xdbda1821b80551c9d65939329250298aa3472ba22feea921c0cf5d620ea67b97'];
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
let pass = 0, fail = 0; const procs = [];
|
||||
const ok = (c, what, extra) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra, (k, v) => typeof v === 'bigint' ? v.toString() : v).slice(0, 700) : '')); } };
|
||||
process.on('exit', () => { for (const p of procs) try { p.kill(); } catch (e) {} });
|
||||
|
||||
// stand-in hub: resolve by wallet / ref / id
|
||||
const people = new Map();
|
||||
http.createServer(async (q, r) => {
|
||||
let b = ''; for await (const c of q) b += c; const j = JSON.parse(b || '{}'); r.setHeader('Content-Type', 'application/json');
|
||||
if (q.url !== '/v1/resolve') return r.end('{"ok":true}');
|
||||
const all = [...people.entries()];
|
||||
const w = j.wallet ? String(j.wallet).toLowerCase() : j.id ? (all.find(([, p]) => p.id === j.id) || [])[0] : j.ref ? (all.find(([a, p]) => a === String(j.ref).toLowerCase() || p.username === String(j.ref).toLowerCase()) || [])[0] : null;
|
||||
const p = w && people.get(w); const sp = p && p.sponsor && people.get(p.sponsor);
|
||||
r.end(JSON.stringify({ person: p ? { id: p.id, username: p.username, wallet: p.noWallet ? null : w, blocked: !!p.blocked, sponsor: sp ? { id: sp.id, username: sp.username } : null } : null }));
|
||||
}).listen(HPORT, '127.0.0.1').unref();
|
||||
|
||||
let ipN = 10;
|
||||
function client(ua, ipAddr) {
|
||||
const jar = {}; const xff = ipAddr || '198.51.100.' + (ipN++);
|
||||
const req = async (method, p, body, headers) => {
|
||||
const h = Object.assign({ 'User-Agent': ua, 'X-Forwarded-For': xff, Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, headers || {});
|
||||
if (body !== undefined) h['Content-Type'] = 'application/json';
|
||||
const r = await fetch(BASE + p, { method, headers: h, body: body !== undefined ? JSON.stringify(body) : undefined, redirect: 'manual' });
|
||||
for (const sc of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv] = sc.split(';'); const i = kv.indexOf('='); const v = kv.slice(i + 1); if (v === '' || /Max-Age=0/.test(sc)) delete jar[kv.slice(0, i)]; else jar[kv.slice(0, i)] = v; }
|
||||
let j = null; try { j = await r.json(); } catch (e) {}
|
||||
return { status: r.status, j: j || {}, loc: r.headers.get('location') };
|
||||
};
|
||||
return { ua, jar, xff, get: (p, h) => req('GET', p, undefined, h), post: (p, b, h) => req('POST', p, b || {}, h) };
|
||||
}
|
||||
async function signIn(c, w) {
|
||||
const ch = await c.post('/api/auth/challenge', { address: w.address });
|
||||
return c.post('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.j.message) });
|
||||
}
|
||||
const admin = (p, b) => fetch(BASE + p, { method: b ? 'POST' : 'GET', headers: { 'x-admin-token': ADMIN, 'Content-Type': 'application/json' }, body: b ? JSON.stringify(b) : undefined }).then(r => r.json());
|
||||
async function verifiedVisit(c, page, q) {
|
||||
const w = await c.get('/api/wire?page=' + page + (q || '')); if (!w.j.ticket) return { w, v: null };
|
||||
await sleep(2100); const v = await c.post('/api/visit/seen', { ticket: w.j.ticket, visibleMs: 2200 }); return { w, v: v.j };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (!fs.existsSync(ANVIL)) throw new Error('anvil not found at ' + ANVIL);
|
||||
const an = spawn(ANVIL, ['--port', String(APORT), '--silent', '--chain-id', '31337'], { stdio: 'ignore' }); procs.push(an);
|
||||
const provider = new ethers.JsonRpcProvider(RPC, 31337, { staticNetwork: true });
|
||||
for (let i = 0; i < 60; i++) { try { await provider.getBlockNumber(); break; } catch (e) { await sleep(200); } }
|
||||
const deployer = new ethers.NonceManager(new ethers.Wallet(K[0], provider)), keeper = new ethers.Wallet(K[1]);
|
||||
const [S, O, M1, M2, M3, B, N] = [K[2], K[3], K[4], K[5], K[6], K[7], K[8]].map(k => new ethers.Wallet(k, provider));
|
||||
const company = ethers.Wallet.createRandom().address; const lc = w => w.address.toLowerCase();
|
||||
people.set(lc(S), { id: 'h_' + '5'.repeat(16), username: 'sponsors' });
|
||||
people.set(lc(O), { id: 'h_' + '0'.repeat(16), username: 'planter', sponsor: lc(S) });
|
||||
people.set(lc(M1), { id: 'h_' + '1'.repeat(16), username: 'memberone', sponsor: lc(S) });
|
||||
people.set(lc(M2), { id: 'h_' + '2'.repeat(16), username: 'membertwo', sponsor: lc(M1) });
|
||||
people.set(lc(M3), { id: 'h_' + '3'.repeat(16), username: 'memberthree', sponsor: lc(M2) });
|
||||
const BL = ethers.Wallet.createRandom().address.toLowerCase();
|
||||
people.set(BL, { id: 'h_' + 'd'.repeat(16), username: 'blockedone', sponsor: lc(O), blocked: true });
|
||||
people.set('x-no-wallet', { id: 'h_' + 'c'.repeat(16), username: 'nowallet', sponsor: BL, noWallet: true });
|
||||
people.set(lc(B), { id: 'h_' + 'b'.repeat(16), username: 'buyerb', sponsor: 'x-no-wallet' });
|
||||
// N is not a network member (unknown to the hub)
|
||||
|
||||
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
|
||||
const feedA = art('MockV3Aggregator'), shopA = art('YPBShop');
|
||||
const feed = await new ethers.ContractFactory(feedA.abi, feedA.bytecode.object, deployer).deploy(25000000n); await feed.waitForDeployment();
|
||||
const shopC = await new ethers.ContractFactory(shopA.abi, shopA.bytecode.object, deployer).deploy(company, keeper.address, await feed.getAddress(), [2000, 500, 500, 500, 500], 1000, 1000);
|
||||
await shopC.waitForDeployment();
|
||||
const CA = await shopC.getAddress(); console.log('YPBShop at', CA);
|
||||
|
||||
const DATA = path.join(OUT, 'e2e-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
|
||||
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, SITE_HOST: 'ypb.test.saasy.top', STAGING: '1', ADMIN_TOKEN: ADMIN, LINK_PROBE: '0', VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '50',
|
||||
REVIEW_SAVES: '3', REPORT_HOLD: '2', CHAIN_ID: '31337', CHAIN_RPC: RPC, CONTRACT_ADDRESS: CA, KEEPER_KEY: K[1], SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '300', SPOTLIGHT_VIEWS: '1000',
|
||||
HUB_URL: 'http://127.0.0.1:' + HPORT, HUB_SECRET, HUB_SITE: 'yourprogrambuilder', HUB_ENABLED: '0', HUB_SSO: 'off', NETWORK_LOOKUP_URL: '', NODE_ENV: 'test', LS_TRACK: '0', NETKB: '0', NETWORK_SITES_HUB: '0', AI_WRITER: '0', SWEEP_FIRST_MS: '600000' });
|
||||
delete env.DOCSTORE_URL; delete env.OPENROUTER_API_KEY;
|
||||
const app = spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] }); procs.push(app);
|
||||
let log = ''; app.stdout.on('data', d => { log += d; }); app.stderr.on('data', d => { log += d; });
|
||||
for (let i = 0; i < 80; i++) { try { if ((await fetch(BASE + '/health')).ok) break; } catch (e) {} await sleep(150); }
|
||||
|
||||
console.log('\n-- pages');
|
||||
for (const p of ['/', '/guides', '/guides/how-it-works', '/guides/is-it-legit', '/guides/free-account', '/guides/planting', '/guides/faq', '/my', '/spotlight', '/transplanted', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy', '/admin']) {
|
||||
const r = await fetch(BASE + p); const t = await r.text();
|
||||
ok(r.status === 200 && !/[—–]/.test(t) && !/MetaMask|Green Valley|Moody|35004|RM Circle|rmcircle/i.test(t), 'page ' + p + ' 200, no dashes, no address');
|
||||
}
|
||||
ok(/Disallow: \//.test(await (await fetch(BASE + '/robots.txt')).text()), 'staging robots.txt disallows everything');
|
||||
const nf = await fetch(BASE + '/nothing/here'); ok(nf.status === 404 && /Nothing has sprouted here/.test(await nf.text()), 'not-found page in the site look');
|
||||
const cfg = await (await fetch(BASE + '/api/config')).json();
|
||||
ok(cfg.split.live === true && cfg.split.levelBps.join() === '2000,500,500,500,500' && cfg.spotlight.live === true && cfg.spotlight.usd === 10 && cfg.spotlight.views === 1000, 'config reads the live split and SKU from the contract', { split: cfg.split, sp: cfg.spotlight });
|
||||
ok(cfg.reviewSaves === 3 && cfg.shop.live === true, 'config: review threshold and the shop is open on the local chain');
|
||||
|
||||
console.log('\n-- sign-in and membership');
|
||||
const cO = client('Mozilla/5.0 planter'), cM1 = client('Mozilla/5.0 m1'), cM2 = client('Mozilla/5.0 m2'), cM3 = client('Mozilla/5.0 m3'), cB = client('Mozilla/5.0 buyer'), cN = client('Mozilla/5.0 nonmember'), cS = client('Mozilla/5.0 sponsor');
|
||||
for (const [c, w] of [[cO, O], [cM1, M1], [cM2, M2], [cM3, M3], [cB, B], [cN, N], [cS, S]]) { const r = await signIn(c, w); ok(r.j.ok, 'wallet sign-in ' + w.address.slice(0, 8)); }
|
||||
const me = await cO.get('/api/me'); ok(me.j.netVerified === true && me.j.username === 'planter', 'membership + username from the hub', me.j);
|
||||
const meN = await cN.get('/api/me'); ok(meN.j.netVerified === false, 'a wallet the hub does not know is not a network member');
|
||||
|
||||
console.log('\n-- planting');
|
||||
const base = { name: 'Harbor Lead Mailer', desc: 'A credit-based safelist mailer, free to join.', cost: 'free', cat: '13' };
|
||||
let r = await cN.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref={id}', myId: 'nnn' }));
|
||||
ok(r.status === 403, 'not a network member: planting refused', r.j);
|
||||
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref=planter1' }));
|
||||
ok(r.status === 400 && /\{id\}/.test(r.j.error), 'a link without {id} is refused', r.j);
|
||||
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://www.adsearnltc.com/?r={id}', myId: 'p1' }));
|
||||
ok(r.status === 400 && r.j.wild === true && /DownlineHydra/.test(r.j.error), 'a program already in the CTB builder is refused (save it on DownlineHydra)', r.j);
|
||||
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://instantadpay.com/join/{id}', myId: 'p1' }));
|
||||
ok(r.status === 400 && /network site/.test(r.j.error), 'a network site is refused', r.j);
|
||||
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://bit.ly/{id}', myId: 'p1' }));
|
||||
ok(r.status === 400 && /shortener/.test(r.j.error), 'a link shortener is refused', r.j);
|
||||
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref={id}', myId: 'planter1', cost: 'paid' }));
|
||||
ok(r.status === 400 && r.j.field === 'costText', 'a paid program needs its cost', r.j);
|
||||
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref={id}', myId: 'planter1', contract: '0x123' }));
|
||||
ok(r.status === 400 && r.j.field === 'contract', 'a bad contract address is refused', r.j);
|
||||
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref={id}', myId: 'planter1' }));
|
||||
ok(r.j.ok && r.j.created && r.j.packet.check === 'green' && r.j.packet.status === 'live', 'planted: link check green, live', r.j);
|
||||
const P1 = r.j.packet.id;
|
||||
r = await cO.post('/api/my/plant', Object.assign({}, base, { name: 'Second Program', url: 'https://other.example.net/r/{id}', myId: 'x' }));
|
||||
ok(r.status === 400 && /most for one member/.test(r.j.error), 'quota: one packet per member at a time', r.j);
|
||||
r = await cM1.post('/api/my/plant', Object.assign({}, base, { name: 'Harbor again', url: 'https://harbor.example.net/?ref={id}', myId: 'm1' }));
|
||||
ok(r.status === 409 && r.j.packet === P1, 'the same program planted again points to the existing packet', r.j);
|
||||
r = await cM3.post('/api/my/plant', { name: 'Orchard Ad Credits', desc: 'Guaranteed daily profit on every credit you buy, really.', cost: 'paid', costText: '$10 one-time', contract: '0x' + 'ab'.repeat(20), url: 'https://orchard.example.org/join/{id}', myId: 'm3', cat: '0' });
|
||||
ok(r.j.ok && r.j.packet.check === 'yellow' && r.j.packet.status === 'held', 'income-claim words: planted but yellow, held for the queue', r.j);
|
||||
const P3 = r.j.packet.id;
|
||||
|
||||
console.log('\n-- the Seed Bed and saved IDs');
|
||||
let w = await cN.get('/api/wire?page=front');
|
||||
ok(w.j.bed.length === 1 && w.j.bed[0].id === P1 && w.j.bed[0].saves === 1 && w.j.bed[0].need === 3, 'the bed shows the green packet only (the planter\'s ID counts as 1)', w.j.bed);
|
||||
ok((await fetch(BASE + '/p/' + P3, { redirect: 'manual' })).status === 302, 'a held packet page is not public');
|
||||
r = await cM1.post('/api/my/save', { packetId: P1, refId: 'not ok id!' }); ok(r.status === 400, 'a bad ID is refused');
|
||||
r = await cO.post('/api/my/save', { packetId: P1, refId: 'x' }); ok(r.status === 400, 'the planter cannot save a second ID');
|
||||
r = await cN.post('/api/my/save', { packetId: P1, refId: 'nn' }); ok(r.status === 403, 'not a network member: save refused');
|
||||
r = await client('Mozilla/5.0 anon').post('/api/my/save', { packetId: P1, refId: 'nn' }); ok(r.status === 401, 'not signed in: save refused');
|
||||
r = await cM1.post('/api/my/save', { packetId: P1, refId: 'memberone99' });
|
||||
ok(r.j.ok && r.j.link === 'https://harbor.example.net/?ref=memberone99' && r.j.saves === 2 && !r.j.review, 'M1 saved an ID (2 of 3)', r.j);
|
||||
|
||||
console.log('\n-- the sponsor-first link');
|
||||
let g = await client('Mozilla/5.0 anon2').get('/go/' + P1); ok(g.status === 302 && g.loc === 'https://harbor.example.net/?ref=planter1', 'anonymous visitor: the planter\'s link', g.loc);
|
||||
const cV = client('Mozilla/5.0 visitor-of-m1');
|
||||
const mp = await cV.get('/memberone'); ok(mp.status === 200 && cV.jar['ypb.ref'] === 'memberone', 'member page sets the ref tag', mp.status);
|
||||
g = await cV.get('/go/' + P1); ok(g.loc === 'https://harbor.example.net/?ref=memberone99', 'a visitor through M1\'s page gets M1\'s link', g.loc);
|
||||
g = await client('Mozilla/5.0 anon3').get('/go/' + P1 + '?r=memberone'); ok(g.loc === 'https://harbor.example.net/?ref=memberone99', '?r=memberone on the click link gives M1\'s link', g.loc);
|
||||
g = await cM3.get('/go/' + P1); ok(g.loc === 'https://harbor.example.net/?ref=memberone99', 'M3 (line M2 -> M1) gets M1\'s link: M2 has not saved one', g.loc);
|
||||
r = await cM2.post('/api/my/save', { packetId: P1, refId: 'https://www.harbor.example.net/?ref=twoTwo' });
|
||||
ok(r.j.ok && r.j.refId === 'twoTwo' && r.j.saves === 3 && r.j.review === true, 'M2 pasted a whole link: the ID is taken from it; 3 of 3 -> review', r.j);
|
||||
g = await cM3.get('/go/' + P1); ok(g.loc === 'https://harbor.example.net/?ref=twoTwo', 'now M3 gets M2\'s link (the nearest saved ID up the line)', g.loc);
|
||||
w = await cM2.get('/api/wire?page=packet&id=' + P1);
|
||||
ok(w.j.packet.stage === 'review' && w.j.mySave.refId === 'twoTwo' && w.j.packet.recent.includes('membertwo'), 'packet page: stage review, my saved ID, recent savers', w.j.packet);
|
||||
const mw = await cV.get('/api/wire?page=member&u=memberone'); ok(mw.j.member && mw.j.member.packets.length === 1 && mw.j.member.packets[0].id === P1, 'member page lists M1\'s saved packets', mw.j.member);
|
||||
r = await cM2.post('/api/my/save', { packetId: P1, refId: '' }); ok(r.j.removed && r.j.saves === 2, 'an ID can be removed (meter back to 2)', r.j);
|
||||
r = await cM2.post('/api/my/save', { packetId: P1, refId: 'twoTwo' }); ok(r.j.saves === 3, 'saved again (3)');
|
||||
|
||||
console.log('\n-- review queue, transplant, export');
|
||||
let q = await admin('/api/admin/queue');
|
||||
ok(q.review.length === 1 && q.review[0].id === P1 && q.held.length === 1 && q.held[0].id === P3 && q.held[0].flags.includes('income claim words'), 'queue: P1 in review, P3 held with its flag', { review: q.review.map(x => x.id), held: q.held.map(x => [x.id, x.flags]) });
|
||||
r = await admin('/api/admin/packet', { id: P3, action: 'approve' }); ok(r.error && /review/.test(r.error), 'only a packet in review can be approved');
|
||||
r = await admin('/api/admin/packet', { id: P1, action: 'approve', note: 'Good fit for Mailers and Traffic' }); ok(r.ok && r.packet.stage === 'approved', 'P1 approved (transplanted)', r);
|
||||
const ex = await admin('/api/admin/export?mark=1');
|
||||
const e1 = ex.packets && ex.packets[0];
|
||||
ok(ex.packets.length === 1 && e1.url === 'https://harbor.example.net/?ref={affiliateid}' && e1.ids.length === 3 && e1.ids.some(x => x.planter && x.refId === 'planter1' && x.hubId === 'h_' + '0'.repeat(16)) && e1.ids.some(x => x.username === 'memberone' && x.refId === 'memberone99') && e1.ids.some(x => x.username === 'membertwo' && x.refId === 'twoTwo'),
|
||||
'export: the builder link with {affiliateid} and all 3 saved IDs with hub ids', e1);
|
||||
ok((await admin('/api/admin/export')).packets.length === 0 && (await admin('/api/admin/export?all=1')).packets.length === 1, 'mark=1 stamps it exported; all=1 lists it again');
|
||||
const tp = await (await fetch(BASE + '/api/transplanted')).json(); ok(tp.items.length === 1 && tp.items[0].id === P1, '/transplanted lists it');
|
||||
r = await cO.post('/api/my/packet/remove', { id: P1 }); ok(r.status === 400, 'a transplanted packet cannot be removed by its planter');
|
||||
r = await admin('/api/admin/packet', { id: P3, action: 'show' }); ok(r.ok && r.packet.status === 'live', 'Marty shows the yellow packet (approved for this exact text)');
|
||||
r = await cM3.post('/api/my/plant', { id: P3, name: 'Orchard Ad Credits', desc: 'Guaranteed daily profit on every credit you buy, now more.', cost: 'paid', costText: '$10 one-time', contract: '0x' + 'ab'.repeat(20), url: 'https://orchard.example.org/join/{id}', myId: 'm3', cat: '0' });
|
||||
ok(r.j.ok && r.j.packet.status === 'held', 'an edit of a shown yellow packet sends it back to the queue', r.j);
|
||||
await admin('/api/admin/packet', { id: P3, action: 'show' });
|
||||
|
||||
console.log('\n-- reports');
|
||||
r = await cM1.post('/api/report', { packetId: P3, reason: 'scam' }); ok(r.j.ok, 'M1 reported P3');
|
||||
r = await cM1.post('/api/report', { packetId: P3, reason: 'scam' }); ok(r.j.already, 'a second report from the same member counts once');
|
||||
r = await cM3.post('/api/report', { packetId: P3, reason: 'broken' }); ok(r.status === 400, 'a planter cannot report their own packet');
|
||||
r = await cM2.post('/api/report', { packetId: P3, reason: 'broken', note: 'page 404' }); ok(r.j.ok, 'M2 reported P3');
|
||||
q = await admin('/api/admin/queue'); ok(q.held.some(x => x.id === P3 && x.heldWhy === 'reported' && x.reports.length === 2), 'REPORT_HOLD reports hold the packet', q.held);
|
||||
r = await admin('/api/admin/packet', { id: P3, action: 'show' }); ok(r.packet.status === 'live' && (await admin('/api/admin/queue')).held.length === 0, 'Marty clears the reports and shows it again');
|
||||
|
||||
console.log('\n-- verified visits');
|
||||
const cF = client('Mozilla/5.0 fresh visitor');
|
||||
let vv = await verifiedVisit(cF, 'front'); ok(vv.v && vv.v.verified === true && vv.v.views === 2 && vv.v.spotViews === 0, 'a verified front-page visit: 2 packet views, no Spotlight yet', vv.v);
|
||||
const early = await cF.get('/api/wire?page=front'); const ev = await cF.post('/api/visit/seen', { ticket: early.j.ticket, visibleMs: 100 }); ok(ev.j.verified === false && ev.j.why === 'early', 'an early send is not verified');
|
||||
const bot = await fetch(BASE + '/api/wire?page=front', { headers: { 'User-Agent': 'curl/8' } }).then(x => x.json()); ok(!bot.ticket, 'a bot gets no ticket');
|
||||
|
||||
console.log('\n-- a Spotlight on chain, to the wei');
|
||||
r = await cB.post('/api/my/order', { qty: 1, packetId: 9999 }); ok(r.status === 400, 'a Spotlight needs a packet in the bed');
|
||||
const od = await cB.post('/api/my/order', { qty: 1, packetId: P3 });
|
||||
ok(od.j.to === CA && od.j.line === 2 && od.j.packetId === P3 && od.j.views === 1000, 'signed order for P3 with a 2-wallet line (no-wallet and blocked members skipped)', od.j);
|
||||
const rc = await (await B.sendTransaction({ to: od.j.to, data: od.j.data, value: od.j.value })).wait();
|
||||
const bal = (a, t) => provider.getBalance(a, t == null ? rc.blockNumber : t);
|
||||
const [c0, o0, s0, b0] = await Promise.all([company, O.address, S.address, B.address].map(a => bal(a, rc.blockNumber - 1)));
|
||||
const [c1, o1, s1, b1] = await Promise.all([company, O.address, S.address, B.address].map(a => bal(a)));
|
||||
const price = BigInt(od.j.wei); const l1 = price * 2000n / 10000n, l2 = price * 500n / 10000n;
|
||||
ok(o1 - o0 === l1, 'O (level 1, the nearest eligible sponsor) got exactly 20% without buying anything', (o1 - o0).toString());
|
||||
ok(s1 - s0 === l2, 'S (level 2) got exactly 5%', (s1 - s0).toString());
|
||||
ok((await provider.getBalance(BL)) === 0n, 'the blocked member got nothing');
|
||||
ok(c1 - c0 === price - l1 - l2, 'company got 60% + the 3 empty levels (75% in all)', (c1 - c0).toString());
|
||||
ok(b0 - b1 === price + rc.gasUsed * rc.gasPrice, 'the 1% overpay came back in the same transaction');
|
||||
ok((await provider.getBalance(CA)) === 0n, 'the contract holds nothing');
|
||||
const replay = await B.sendTransaction({ to: od.j.to, data: od.j.data, value: od.j.value }).then(t => t.wait()).then(() => 'mined', e => 'reverted');
|
||||
ok(replay === 'reverted', 'the same signed order cannot be used twice');
|
||||
for (let i = 0; i < 40; i++) { const L = await (await fetch(BASE + '/api/ledger')).json(); if (L.items.length && L.items[0].pays && L.items[0].pays.length > 1) break; await sleep(250); }
|
||||
const L = await (await fetch(BASE + '/api/ledger')).json(); const it = L.items[0];
|
||||
ok(L.items.length === 1 && it.packet.id === P3 && it.pays.length === 3 && it.pays.some(p => p.kind === 1 && p.name === 'planter') && it.pays.some(p => p.kind === 2 && p.name === 'sponsors') && it.delivery.views === 1000, 'ledger: the split from the receipt and the delivery', it);
|
||||
const ct = await (await fetch(BASE + '/api/contract')).json();
|
||||
ok(ct.deployed && ct.live && ct.skuDelayHours === 48 && ct.split.levelBps.join() === '2000,500,500,500,500' && ct.sku.usdCents === 1000 && ct.company === company.toLowerCase(), 'contract page reads the chain (48 h SKU delay, split, SKU, company)', ct);
|
||||
const my0 = await cO.get('/api/my'); ok(BigInt(my0.j.earned.wei) === l1 && my0.j.earned.items[0].kind === 1, 'O sees the level-1 payment on My packets', my0.j.earned);
|
||||
|
||||
console.log('\n-- Spotlight delivery (only the Spotlight places count)');
|
||||
const cG = client('Mozilla/5.0 spotlight viewer');
|
||||
vv = await verifiedVisit(cG, 'front'); ok(vv.w.j.spotlights.length === 1 && vv.w.j.spotlights[0].id === P3 && vv.v.spotViews === 1, 'the front page Spotlight row shows P3; a verified visit delivers 1 view', { s: vv.w.j.spotlights, v: vv.v });
|
||||
const again = await verifiedVisit(cG, 'front'); ok(again.v.spotViews === 0, 'the same visitor again within 24 h: no second view');
|
||||
const cQ = client('Mozilla/5.0 packet visitor');
|
||||
vv = await verifiedVisit(cQ, 'packet', '&id=' + P3); ok(vv.v.spotViews === 0, 'P3\'s own packet page is not a Spotlight place (no delivery there)', vv.v);
|
||||
vv = await verifiedVisit(cO, 'front'); ok(vv.v.spotViews === 1, 'a different member (not P3\'s planter) on the front page delivers a view');
|
||||
vv = await verifiedVisit(cM3, 'front'); ok(vv.v.spotViews === 0, 'P3\'s planter never counts their own views');
|
||||
const L2 = await (await fetch(BASE + '/api/ledger')).json(); ok(L2.items[0].delivery.delivered === 2, 'ledger delivery: 2 of 1,000', L2.items[0].delivery);
|
||||
const pk = await (await fetch(BASE + '/api/packets')).json(); ok(pk.items.length === 2, '/api/packets (the Spotlight picker) lists the bed without a ticket');
|
||||
const sf = await (await fetch(BASE + '/api/spotlight-feed')).json(); ok(sf.items.length === 1 && sf.items[0].id === P3, 'the DownlineHydra feed lists the delivering Spotlight');
|
||||
|
||||
console.log('\n-- old links and dormant old programs');
|
||||
r = await admin('/api/admin/oldrefs', { oldrefs: { oldmember: 'memberone', 'bad key!': 'x' } }); ok(r.total === 1 && r.skipped === 1, 'oldrefs loaded (a bad key skipped)', r);
|
||||
for (const [from, to] of [['/?oldmember', '/memberone'], ['/index.php?oldmember', '/memberone'], ['/splashpg.php?r=oldmember', '/memberone'], ['/lcp.php?r=oldmember', '/memberone'], ['/join.php?r=oldmember', '/memberone'], ['/login.php', '/my'], ['/faq.php', '/guides/faq'], ['/whatever.php', '/'], ['/?nobody', '/']]) {
|
||||
const x = await fetch(BASE + from, { redirect: 'manual' }); ok(x.status === 301 && x.headers.get('location') === to, 'old link ' + from + ' -> ' + to, x.headers.get('location'));
|
||||
}
|
||||
r = await admin('/api/admin/dormant', { packets: [{ oldId: '10010', oldUsername: 'oldm2', hubId: 'h_' + '2'.repeat(16), name: 'Team Build Machine', url: 'https://teambuildmachine.example.com/oldm2', added: '2022-04-21' }, { oldId: 'x', hubId: 'h_1', name: 'bad', url: 'nope' }] });
|
||||
ok(r.created === 1 && r.skipped === 1, 'dormant import: 1 created, a bad row skipped', r);
|
||||
const my2 = await cM2.get('/api/my'); const dm = my2.j.dormant && my2.j.dormant[0];
|
||||
ok(dm && dm.name === 'Team Build Machine', 'M2 (matched by hub id) sees the dormant old program', my2.j.dormant);
|
||||
ok((await cM1.get('/api/my')).j.dormant.length === 0, 'nobody else sees it');
|
||||
ok(!(await cN.get('/api/wire?page=front')).j.bed.some(x => x.name === 'Team Build Machine'), 'a dormant packet is not in the bed');
|
||||
r = await cM1.post('/api/my/plant', { dormant: dm.id, name: 'Team Build Machine', desc: 'A team builder for any program you promote.', cost: 'free', url: 'https://teambuildmachine.example.com/{id}', myId: 'm1' });
|
||||
ok(r.status === 404, 'someone else cannot confirm it');
|
||||
r = await cM2.post('/api/my/plant', { dormant: dm.id, name: 'Team Build Machine', desc: 'A team builder for any program you promote.', cost: 'free', url: 'https://teambuildmachine.example.com/{id}', myId: 'oldm2' });
|
||||
ok(r.j.ok && r.j.packet.id === dm.id && r.j.packet.status === 'live', 'M2 confirms it with a {id} link: live in the bed', r.j);
|
||||
|
||||
console.log('\n-- trust pack, chatbot, promo kit');
|
||||
const rec = await (await fetch(BASE + '/api/recent')).json(); ok(['plant', 'save', 'review', 'spotlight'].every(k => rec.items.some(x => x.kind === k)), 'toasts feed: plants, saves, review and the Spotlight', rec.items.map(x => x.kind));
|
||||
const ch = await (await fetch(BASE + '/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'How do I plant a program?' }) })).json();
|
||||
ok(ch.reply && /\{id\}/.test(ch.reply) && !/[—–]/.test(ch.reply), 'chatbot answers planting from its canned knowledge', ch);
|
||||
const ch2 = await (await fetch(BASE + '/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'What is a Spotlight?' }) })).json();
|
||||
ok(ch2.reply && /SafePal or any other crypto wallet/.test(ch2.reply) && /20%/.test(ch2.reply), 'chatbot: Spotlight answer (wallet wording, split)', ch2.reply);
|
||||
const kit = await (await fetch(BASE + '/api/promo-kit?u=memberone')).json(); ok(kit.links[0].url.endsWith('/memberone') && kit.lines.every(l => !/[—–]/.test(l)), 'promo kit: the member page link, no dashes');
|
||||
const sm = await (await fetch(BASE + '/sitemap.xml')).text(); ok(sm.includes('/p/' + P1) && sm.includes('/guides/planting'), 'sitemap lists the guides and the packets');
|
||||
|
||||
console.log('\n-- staging test switch + admin');
|
||||
r = await admin('/api/admin/test-member', { address: ethers.Wallet.createRandom().address, username: 'tester1' }); ok(r.ok && r.member.netOk && r.member.testMember, 'staging test switch marks a test network member');
|
||||
ok((await fetch(BASE + '/api/admin/status')).status === 401, 'admin needs the token');
|
||||
const st = await admin('/api/admin/status'); ok(st.packets.approved === 1 && st.packets.shown === 3 && st.shop.watching && st.oldrefs === 1, 'admin status', st.packets);
|
||||
|
||||
console.log('\n' + pass + ' passed, ' + fail + ' failed');
|
||||
if (fail) { fs.writeFileSync(path.join(OUT, 'e2e-app.log'), log); console.log('app log: qa/out/e2e-app.log'); }
|
||||
process.exit(fail ? 1 : 0);
|
||||
}
|
||||
main().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,54 @@
|
||||
// Unit checks for the pure rules: the link-check colours (linkcheck.verdict), planting validation, ID cleaning and filling.
|
||||
// node qa/unit.test.cjs
|
||||
'use strict';
|
||||
const path = require('path'); const os = require('os'); const fs = require('fs');
|
||||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'ypb-unit-'));
|
||||
const lc = require('../linkcheck');
|
||||
const sb = require('../seedbed');
|
||||
let pass = 0, fail = 0;
|
||||
const ok = (c, what, x) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (x !== undefined ? ' -> ' + JSON.stringify(x) : '')); } };
|
||||
|
||||
console.log('-- link check verdicts');
|
||||
ok(lc.verdict([], { ok: true, status: 200, host: 'a.com', moved: false }).state === 'green', '200 on the same site, no flags: green');
|
||||
ok(lc.verdict(['spam words'], { ok: true, status: 200 }).state === 'yellow', 'flags: yellow');
|
||||
ok(lc.verdict([], { ok: true, status: 200, moved: true, host: 'b.com' }).state === 'yellow', 'redirect to another site: yellow');
|
||||
ok(lc.verdict([], { ok: true, http: true }).state === 'yellow', 'plain http: yellow');
|
||||
ok(lc.verdict([], { ok: true, status: 403, wall: true }).state === 'yellow', '403 bot wall: yellow');
|
||||
ok(lc.verdict([], { ok: false, why: 'answered 404', hard: true }).state === 'red', '404 on planting: red');
|
||||
ok(lc.verdict([], { ok: false, why: 'could not be reached (timeout)' }, null).state === 'red', 'unreachable on planting: red');
|
||||
{ const v1 = lc.verdict([], { ok: false, why: 'timeout' }, { state: 'green', misses: 0 }); const v2 = lc.verdict([], { ok: false, why: 'timeout' }, v1);
|
||||
ok(v1.state === 'yellow' && v1.misses === 1 && v2.state === 'red', 'a green packet: one failed recheck yellow, the second red', [v1, v2]); }
|
||||
ok(lc.verdict([], { ok: false, why: 'answered 410', hard: true }, { state: 'green' }).state === 'red', 'a gone page on recheck: red at once');
|
||||
ok(lc.verdict([], { skipped: true }).state === 'green' && lc.verdict(['x'], { skipped: true }).state === 'yellow', 'probe off: flags only');
|
||||
ok(lc.sameSite('www.a.com'.replace(/^www\./, ''), 'a.com') && lc.sameSite('go.a.com', 'a.com') && !lc.sameSite('a.com', 'b.com'), 'same-site rule');
|
||||
ok(lc.sample('https://x.com/?r={id}') === 'https://x.com/?r=ypbcheck', 'the probe uses a sample ID');
|
||||
|
||||
console.log('-- planting validation');
|
||||
const base = { name: 'Good Program', url: 'https://good.example.net/?ref={id}', myId: 'me1', desc: 'A program that does a useful thing.', cost: 'free' };
|
||||
let v = sb.validatePlant(base); ok(v.ok && v.fields.url === 'https://good.example.net/?ref={id}' && v.fields.ownerId === 'me1' && v.flags.length === 0, 'a good packet', v);
|
||||
v = sb.validatePlant(Object.assign({}, base, { url: 'https://good.example.net/?ref={affiliateid}' })); ok(v.ok && v.fields.url.endsWith('{id}'), '{affiliateid} is accepted and normalised to {id}', v);
|
||||
v = sb.validatePlant(Object.assign({}, base, { url: 'https://{id}.good.example.net/' })); ok(v.error && /domain/.test(v.error), '{id} in the domain refused', v);
|
||||
v = sb.validatePlant(Object.assign({}, base, { desc: 'short' })); ok(v.field === 'desc', 'too short a description');
|
||||
v = sb.validatePlant(Object.assign({}, base, { cost: 'maybe' })); ok(v.field === 'cost', 'cost must be free or paid');
|
||||
v = sb.validatePlant(Object.assign({}, base, { desc: 'Earn passive income with guaranteed returns daily.' })); ok(v.ok && v.flags.includes('income claim words'), 'income words flagged', v.flags);
|
||||
v = sb.validatePlant(Object.assign({}, base, { desc: 'See www.other.com/page for more about it.' })); ok(v.ok && v.flags.includes('link in description'), 'a link in the description flagged');
|
||||
v = sb.validatePlant(Object.assign({}, base, { url: 'http://good.example.net/?ref={id}' })); ok(v.ok && v.flags.includes('not https'), 'http flagged');
|
||||
v = sb.validatePlant(Object.assign({}, base, { name: 'X' })); ok(v.field === 'name', 'name too short');
|
||||
v = sb.validatePlant(Object.assign({}, base, { myId: '' })); ok(v.field === 'myId', 'the planter ID is required');
|
||||
v = sb.validatePlant(Object.assign({}, base, { url: 'https://stackpol.com/r/{id}' })); ok(v.error && /network site/.test(v.error), 'a network site refused');
|
||||
v = sb.validatePlant(Object.assign({}, base, { url: 'https://rmcircle.team/{id}' })); ok(!!v.error, 'RM Circle refused (never in the network rows)');
|
||||
v = sb.validatePlant(Object.assign({}, base, { contract: '0x' + 'A'.repeat(40) })); ok(v.ok && v.fields.contract === '0x' + 'a'.repeat(40), 'contract address lowercased');
|
||||
ok(sb.cats().length >= 8 && !sb.cats().some(c => c.id === '12'), 'categories from the builder (empty faucets category left out)');
|
||||
|
||||
console.log('-- IDs');
|
||||
const p = { url: 'https://good.example.net/?ref={id}' };
|
||||
ok(sb.cleanId(p, ' jane ') === 'jane', 'an ID is trimmed');
|
||||
ok(sb.cleanId(p, 'https://www.good.example.net/?ref=jane99') === 'jane99', 'a pasted whole link gives the ID');
|
||||
ok(sb.cleanId(p, '') === '', 'empty = remove');
|
||||
ok(sb.cleanId(p, 'bad id!') === null, 'spaces and ! refused');
|
||||
ok(sb.fill(p, 'a b') === 'https://good.example.net/?ref=a%20b', 'fill encodes the ID');
|
||||
ok(sb.homeUrl(p) === 'https://good.example.net/', 'the plain home page');
|
||||
ok(sb.textHash({ name: 'a', url: 'b' }) !== sb.textHash({ name: 'a', url: 'c' }), 'text hash changes with the text');
|
||||
|
||||
console.log('\n' + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,168 @@
|
||||
// Link + image checks for posted banners (Downline Banners' safety.js, used by ViralAdBlitz for text-ad links only).
|
||||
// Links: https only, a real public hostname, no shorteners, and (when probed) a page that answers and allows frames.
|
||||
// Images: a real PNG/JPG/GIF at exactly 125x125 (or 250x250 retina) and at most 100 KB. An https image address is
|
||||
// fetched once, checked the same way and stored as an upload, so the splash never hotlinks someone else's server.
|
||||
const net = require('net');
|
||||
const dns = require('dns');
|
||||
const https = require('https');
|
||||
|
||||
const MAX_UPLOAD = 100 * 1024;
|
||||
const BAD_HOST = /(^|\.)(localhost|local|internal|lan|home|corp|onion|test|invalid|example)$/i;
|
||||
// shorteners and redirectors hide where a click goes; a member link must show its real destination
|
||||
const REDIRECTORS = /(^|\.)(bit\.ly|tinyurl\.com|t\.co|goo\.gl|is\.gd|cutt\.ly|ow\.ly|rebrand\.ly|shorturl\.at|rb\.gy|s\.id|t\.ly|v\.gd|bl\.ink|tiny\.cc)$/i;
|
||||
|
||||
function checkLink(raw, what) {
|
||||
what = what || 'Link';
|
||||
const s = String(raw || '').trim();
|
||||
if (!s) return { error: what + ' is empty.' };
|
||||
if (s.length > 600) return { error: what + ' is too long (600 characters max).' };
|
||||
if (/[\s<>"'`\\]/.test(s)) return { error: what + ' has spaces or characters a web address cannot have.' };
|
||||
let u; try { u = new URL(s); } catch (e) { return { error: what + ' is not a valid web address.' }; }
|
||||
if (u.protocol !== 'https:') return { error: what + ' must start with https://' };
|
||||
if (u.username || u.password) return { error: what + ' cannot contain a username or password.' };
|
||||
const h = u.hostname.toLowerCase().replace(/\.$/, '');
|
||||
if (net.isIP(h.replace(/^\[|\]$/g, ''))) return { error: what + ' must use a domain name, not an IP address.' };
|
||||
if (!h.includes('.') || BAD_HOST.test(h)) return { error: what + ' must point to a public website.' };
|
||||
if (!/^[a-z0-9.-]+$/.test(h) && !/^xn--/.test(h)) return { error: what + ' has an unusual domain name.' };
|
||||
if (REDIRECTORS.test(h)) return { error: 'Use the real destination, not a link shortener.' };
|
||||
if (u.port && !['443', ''].includes(u.port)) return { error: what + ' must use the normal https port.' };
|
||||
return { ok: true, url: u.toString() };
|
||||
}
|
||||
|
||||
function imageInfo(buf) {
|
||||
if (!buf || buf.length < 24) return null;
|
||||
if (buf.slice(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
|
||||
return { type: 'png', ext: '.png', w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
|
||||
if (buf.slice(0, 6).toString('latin1') === 'GIF87a' || buf.slice(0, 6).toString('latin1') === 'GIF89a')
|
||||
return { type: 'gif', ext: '.gif', w: buf.readUInt16LE(6), h: buf.readUInt16LE(8) };
|
||||
if (buf[0] === 0xff && buf[1] === 0xd8) {
|
||||
let i = 2;
|
||||
while (i + 9 < buf.length) {
|
||||
if (buf[i] !== 0xff) { i++; continue; }
|
||||
const m = buf[i + 1];
|
||||
if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { type: 'jpg', ext: '.jpg', h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) };
|
||||
if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { i += 2; continue; }
|
||||
i += 2 + buf.readUInt16BE(i + 2);
|
||||
}
|
||||
return { type: 'jpg', ext: '.jpg', w: 0, h: 0 };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function checkImage(buf) {
|
||||
if (!buf || !buf.length) return { error: 'No file received.' };
|
||||
if (buf.length > MAX_UPLOAD) return { error: 'That file is ' + Math.ceil(buf.length / 1024) + ' KB. The limit is 100 KB.' };
|
||||
const info = imageInfo(buf);
|
||||
if (!info) return { error: 'Use a PNG, JPG or GIF image.' };
|
||||
const ok = (info.w === 125 && info.h === 125) || (info.w === 250 && info.h === 250);
|
||||
if (!ok) return { error: 'The image is ' + info.w + 'x' + info.h + '. It must be 125x125 (or 250x250).' };
|
||||
return { ok: true, info };
|
||||
}
|
||||
|
||||
// ---- outbound requests only to public addresses (the DNS answer used for the connection is the one checked) ----
|
||||
function privateIp(ip) {
|
||||
if (net.isIPv4(ip)) {
|
||||
const [a, b] = ip.split('.').map(Number);
|
||||
return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31)
|
||||
|| (a === 192 && b === 168) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224;
|
||||
}
|
||||
const s = ip.toLowerCase();
|
||||
{ const m = /^(?:::ffff:|::ffff:0:|::|64:ff9b::)([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(s); if (m) { const hi = parseInt(m[1], 16), lo = parseInt(m[2], 16); return privateIp([hi >> 8, hi & 255, lo >> 8, lo & 255].join('.')); } } // IPv4-mapped/compatible/NAT64 in hex form (the URL parser writes ::ffff:127.0.0.1 as ::ffff:7f00:1)
|
||||
if (s.startsWith('::ffff:')) return privateIp(s.slice(7));
|
||||
return s === '::' || s === '::1' || s.startsWith('fc') || s.startsWith('fd') || /^fe[89ab][0-9a-f]:/.test(s) || s.startsWith('ff');
|
||||
}
|
||||
// Node 20's https agent asks for every address (opts.all, for happy eyeballs) and expects an array back; answering with one
|
||||
// address broke every link check (2026-11-15: no text ad could be posted). Answer in the shape asked for, private ones refused.
|
||||
function safeLookup(host, opts, cb) {
|
||||
if (typeof opts === 'function') { cb = opts; opts = {}; }
|
||||
dns.lookup(host, Object.assign({}, opts, { all: true }), (err, list) => {
|
||||
if (err) return cb(err);
|
||||
if (!list.length || list.some(a => privateIp(a.address))) return cb(new Error('private address'));
|
||||
if (opts && opts.all) return cb(null, list);
|
||||
cb(null, list[0].address, list[0].family);
|
||||
});
|
||||
}
|
||||
// GET with a size cap, a timeout and no redirects followed (a redirect is reported so the caller can decide)
|
||||
function get(url, maxBytes, timeoutMs) {
|
||||
return new Promise(resolve => {
|
||||
let done = false; const fin = v => { if (!done) { done = true; resolve(v); } };
|
||||
let req;
|
||||
try {
|
||||
req = https.get(url, { lookup: safeLookup, timeout: timeoutMs || 5000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; YPBCheck/1.0; +https://yourprogrambuilder.com)', Accept: '*/*' } }, res => {
|
||||
const out = { status: res.statusCode, headers: res.headers, location: res.headers.location || null };
|
||||
if (!maxBytes) { res.destroy(); return fin(out); }
|
||||
const ch = []; let n = 0;
|
||||
res.on('data', c => { n += c.length; if (n > maxBytes) { res.destroy(); return fin(Object.assign(out, { tooBig: true })); } ch.push(c); });
|
||||
res.on('end', () => fin(Object.assign(out, { body: Buffer.concat(ch) })));
|
||||
res.on('error', () => fin(Object.assign(out, { error: 'read' })));
|
||||
});
|
||||
req.on('timeout', () => { req.destroy(); fin({ error: 'timeout' }); });
|
||||
req.on('error', e => fin({ error: /private address/.test(e.message) ? 'private' : 'unreachable' }));
|
||||
} catch (e) { fin({ error: 'unreachable' }); }
|
||||
});
|
||||
}
|
||||
|
||||
// does this response allow being shown inside a frame on another site?
|
||||
function frameVerdict(headers) {
|
||||
const h = k => String(headers[k] || '').toLowerCase();
|
||||
if (h('x-frame-options')) return false;
|
||||
const fa = /frame-ancestors([^;]*)/.exec(h('content-security-policy'));
|
||||
return !(fa && !/\*|https:/.test(fa[1]));
|
||||
}
|
||||
// the target link must answer and allow frames (traffic exchanges and the splash preview show sites in a frame). Up to 3 redirects.
|
||||
async function probeLink(url, opts) { // opts.frames false: text ads open in a new tab, so frames are not required
|
||||
let cur = url;
|
||||
for (let hop = 0; hop < 4; hop++) {
|
||||
const r = await get(cur, 0, 6000);
|
||||
if (r.error === 'private') return { error: 'That link points to a private network address.' };
|
||||
if (r.error) return { error: 'We could not reach that link. Check it opens in your browser and try again.' };
|
||||
if (r.status >= 300 && r.status < 400 && r.location) {
|
||||
let next; try { next = new URL(r.location, cur).toString(); } catch (e) { return { error: 'That link redirects somewhere invalid.' }; }
|
||||
const c = checkLink(next, 'The page your link redirects to'); if (c.error) return c;
|
||||
cur = c.url; continue;
|
||||
}
|
||||
if (r.status >= 400) return { error: 'That link answered with an error (' + r.status + '). Use a page that loads.' };
|
||||
if (!(opts && opts.frames === false) && !frameVerdict(r.headers)) return { error: 'That site does not allow being shown in a frame, so it cannot rotate here. Use a page that allows frames (most landing pages and LinkSpin links do).' };
|
||||
return { ok: true };
|
||||
}
|
||||
return { error: 'That link redirects too many times.' };
|
||||
}
|
||||
// an https image address: fetched once, checked like an upload. -> { ok, buf, info } or { error }
|
||||
async function fetchImage(url) {
|
||||
const r = await get(url, MAX_UPLOAD, 6000);
|
||||
if (r.error === 'private') return { error: 'That image address points to a private network address.' };
|
||||
if (r.error) return { error: 'We could not download that image. Check the address or upload the file instead.' };
|
||||
if (r.tooBig) return { error: 'That image is over 100 KB.' };
|
||||
if (r.status !== 200) return { error: 'The image address answered ' + r.status + '. Use a direct link to the image file, or upload it.' };
|
||||
const c = checkImage(r.body); if (c.error) return c;
|
||||
return { ok: true, buf: r.body, info: c.info };
|
||||
}
|
||||
|
||||
// ---- ad copy rules (the AI ad writer, Marty 2026-11-17): plain, honest text ad words. -> { ok } or { error }
|
||||
// No markup, links or emails; no em dash, en dash or double hyphen; no income promises or guarantees; no shouting; and, when the
|
||||
// page text is given, every number in the copy must appear on that page (the writer never invents prices, amounts or results).
|
||||
const PROMISE_RE = [
|
||||
/\bguarantee/i, /\brisk[\s-]*free\b/i, /\bno[\s-]+risk\b/i, /\bget[\s-]+rich\b/i, /\bfinancial[\s-]+freedom\b/i, /\bquit[\s-]+your[\s-]+job\b/i,
|
||||
/\bmillionaires?\b/i, /\b(make|earn|making|earning|makes|earns)\s+(real\s+|extra\s+|big\s+|fast\s+|easy\s+|serious\s+)?(money|cash|income|profits?|\$)/i,
|
||||
/\b(passive|extra|residual|full[\s-]?time|daily|weekly|monthly|guaranteed|unlimited|recurring)\s+(income|profits?|earnings|payouts?)\b/i,
|
||||
/\$\s?\d[\d,.]*\s*\+?\s*(a|per|\/|each|every)\s*(hour|day|week|month|year)\b/i, /\bdouble\s+your\s+(money|income|investment)\b/i,
|
||||
/\b(instant|easy|fast|free)\s+(money|cash)\b/i, /\bcan'?t\s+lose\b/i
|
||||
];
|
||||
function checkAdCopy(text, pageText) {
|
||||
const s = String(text == null ? '' : text);
|
||||
if (!s.trim()) return { error: 'empty' };
|
||||
if (/[<>]|[\u0000-\u001f\u007f]/.test(s)) return { error: 'markup' };
|
||||
if (/[\u2013\u2014\u2015]|--/.test(s)) return { error: 'dash' };
|
||||
if (/https?:\/\/|www\.|\b[\w.+-]+@[\w-]+\.[\w.]+\b/i.test(s)) return { error: 'link' };
|
||||
if (/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(s)) return { error: 'emoji' };
|
||||
if (/#\w/.test(s)) return { error: 'hashtag' };
|
||||
if (/!{2,}|\?{2,}/.test(s) || (s.match(/!/g) || []).length > 1) return { error: 'shouting' };
|
||||
if (/\b[A-Z]{4,}\b(\s+\b[A-Z]{2,}\b){1,}/.test(s)) return { error: 'shouting' };
|
||||
for (const re of PROMISE_RE) if (re.test(s)) return { error: 'promise' };
|
||||
if (pageText != null) {
|
||||
const page = String(pageText).replace(/[\s,]/g, '');
|
||||
for (const n of s.match(/\d[\d,.]*/g) || []) { const d = n.replace(/[,.]+$/, '').replace(/,/g, ''); if (d && !page.includes(d)) return { error: 'number' }; }
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
module.exports = { checkAdCopy, checkLink, checkImage, imageInfo, frameVerdict, probeLink, fetchImage, privateIp, get, MAX_UPLOAD };
|
||||
@@ -0,0 +1,789 @@
|
||||
{
|
||||
"source": "CryptoTeamBuild downline builder, read-only list (yfw-builder.py list rhi cryptoteambuild cryptoteambuild.com) 2026-11-14 6:45 PM CT",
|
||||
"rules": "hidden+network = a core or growing head or another network site: never shown as a wild head (admin can change). ctbMemberLinks is the count on cryptoteambuild.com, for reference only; never shown as a DownlineHydra joined count.",
|
||||
"cats": [
|
||||
{
|
||||
"id": "6",
|
||||
"name": "Ads Earn Network",
|
||||
"short": "Ads Earn Network"
|
||||
},
|
||||
{
|
||||
"id": "7",
|
||||
"name": "Infinity Family",
|
||||
"short": "Infinity Family"
|
||||
},
|
||||
{
|
||||
"id": "8",
|
||||
"name": "Free Builders",
|
||||
"short": "Free Builders"
|
||||
},
|
||||
{
|
||||
"id": "9",
|
||||
"name": "More Ways to Earn",
|
||||
"short": "More Ways to Earn"
|
||||
},
|
||||
{
|
||||
"id": "10",
|
||||
"name": "AI and Tools",
|
||||
"short": "AI and Tools"
|
||||
},
|
||||
{
|
||||
"id": "11",
|
||||
"name": "Crypto Team Build Network",
|
||||
"short": "CTB Network"
|
||||
},
|
||||
{
|
||||
"id": "12",
|
||||
"name": "Crypto Faucets",
|
||||
"short": "Crypto Faucets"
|
||||
},
|
||||
{
|
||||
"id": "13",
|
||||
"name": "Safelist Mailers and Traffic Exchanges",
|
||||
"short": "Mailers and Traffic"
|
||||
},
|
||||
{
|
||||
"id": "0",
|
||||
"name": "Other programs",
|
||||
"short": "Other"
|
||||
}
|
||||
],
|
||||
"programs": [
|
||||
{
|
||||
"id": "ctb2",
|
||||
"builderId": 2,
|
||||
"name": "Ads Earn LTC",
|
||||
"builderTitle": "Ads Earn LTC",
|
||||
"url": "https://www.adsearnltc.com/?r={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "6",
|
||||
"order": 1,
|
||||
"ctbMemberLinks": 119,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb6",
|
||||
"builderId": 6,
|
||||
"name": "Elite Downline Club",
|
||||
"builderTitle": "Elite Downline Club",
|
||||
"url": "https://www.elitedownlineclub.com/index.php?r={affiliateid}&t=ctb",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 2,
|
||||
"ctbMemberLinks": 179,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb12",
|
||||
"builderId": 12,
|
||||
"name": "Infinity Mailer Boost",
|
||||
"builderTitle": "Infinity Mailer Boost",
|
||||
"url": "https://infinitymailerboost.com/{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "7",
|
||||
"order": 3,
|
||||
"ctbMemberLinks": 145,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb13",
|
||||
"builderId": 13,
|
||||
"name": "Infinity Traffic Boost",
|
||||
"builderTitle": "Infinity Traffic Boost",
|
||||
"url": "https://infinitytrafficboost.com/{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "7",
|
||||
"order": 4,
|
||||
"ctbMemberLinks": 183,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": true
|
||||
},
|
||||
{
|
||||
"id": "ctb14",
|
||||
"builderId": 14,
|
||||
"name": "My Lead Gen Secret",
|
||||
"builderTitle": "My Lead Gen Secret",
|
||||
"url": "https://www.myleadgensecret.com/?rid={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "9",
|
||||
"order": 5,
|
||||
"ctbMemberLinks": 71,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb15",
|
||||
"builderId": 15,
|
||||
"name": "Traffic Zipper",
|
||||
"builderTitle": "Traffic Zipper",
|
||||
"url": "https://trafficzipper.com/index2.php?af={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "13",
|
||||
"order": 6,
|
||||
"ctbMemberLinks": 100,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": true
|
||||
},
|
||||
{
|
||||
"id": "ctb16",
|
||||
"builderId": 16,
|
||||
"name": "Leased Ad Space",
|
||||
"builderTitle": "Leased Ad Space",
|
||||
"url": "https://leasedadspace.com/?aid={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "7",
|
||||
"order": 7,
|
||||
"ctbMemberLinks": 136,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": true
|
||||
},
|
||||
{
|
||||
"id": "ctb18",
|
||||
"builderId": 18,
|
||||
"name": "Unstoppable Domains",
|
||||
"builderTitle": "Unstoppable Domains",
|
||||
"url": "https://unstoppabledomains.com/?ref={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "9",
|
||||
"order": 8,
|
||||
"ctbMemberLinks": 57,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb19",
|
||||
"builderId": 19,
|
||||
"name": "Ads Earn Network",
|
||||
"builderTitle": "Ads Earn Network",
|
||||
"url": "https://www.adsearnnetwork.com/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "6",
|
||||
"order": 9,
|
||||
"ctbMemberLinks": 147,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": true
|
||||
},
|
||||
{
|
||||
"id": "ctb20",
|
||||
"builderId": 20,
|
||||
"name": "Team Builder BTC 2.0",
|
||||
"builderTitle": "Team Builder BTC 2.0",
|
||||
"url": "https://www.teambuilderbtc.com/?r={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "6",
|
||||
"order": 10,
|
||||
"ctbMemberLinks": 95,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb21",
|
||||
"builderId": 21,
|
||||
"name": "Early Birds Downline Builder",
|
||||
"builderTitle": "Early Birds Downline Builder",
|
||||
"url": "https://www.earlybirdsdownline.com/me/{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "6",
|
||||
"order": 11,
|
||||
"ctbMemberLinks": 128,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb23",
|
||||
"builderId": 23,
|
||||
"name": "Tron Banners",
|
||||
"builderTitle": "Tron Banners",
|
||||
"url": "https://tronbanners.io/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "9",
|
||||
"order": 12,
|
||||
"ctbMemberLinks": 116,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb26",
|
||||
"builderId": 26,
|
||||
"name": "Ads Earn Tron",
|
||||
"builderTitle": "Ads Earn Tron",
|
||||
"url": "https://www.adsearntron.com/?r={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "6",
|
||||
"order": 13,
|
||||
"ctbMemberLinks": 111,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb27",
|
||||
"builderId": 27,
|
||||
"name": "Team Profit Builder",
|
||||
"builderTitle": "Team Profit Builder",
|
||||
"url": "https://teamprofitbuilder.com/splashpg.php?pid=2&r={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "9",
|
||||
"order": 14,
|
||||
"ctbMemberLinks": 107,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb28",
|
||||
"builderId": 28,
|
||||
"name": "YourProgramBuilder",
|
||||
"builderTitle": "Grow Your Downline With Your Program Builder For FREE",
|
||||
"url": "https://yourprogrambuilder.com/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 15,
|
||||
"ctbMemberLinks": 330,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "growing head YourProgramBuilder",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb29",
|
||||
"builderId": 29,
|
||||
"name": "ViralAdBlitz",
|
||||
"builderTitle": "Join Viral Ad Blitz For FREE",
|
||||
"url": "https://viraladblitz.com/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 16,
|
||||
"ctbMemberLinks": 304,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "core head ViralAdBlitz",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb30",
|
||||
"builderId": 30,
|
||||
"name": "DownlineHydra",
|
||||
"builderTitle": "Downline Hydra Join It FREE",
|
||||
"url": "https://downlinehydra.com/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 17,
|
||||
"ctbMemberLinks": 305,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "this site (DownlineHydra)",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb31",
|
||||
"builderId": 31,
|
||||
"name": "DownlineScaler",
|
||||
"builderTitle": "Grow Your Team With Downline Scaler For FREE",
|
||||
"url": "https://downlinescaler.com/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 18,
|
||||
"ctbMemberLinks": 302,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "growing head DownlineScaler",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb32",
|
||||
"builderId": 32,
|
||||
"name": "5xYourTeam",
|
||||
"builderTitle": "5x Your Team For FREE",
|
||||
"url": "https://5xyourteam.com/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 19,
|
||||
"ctbMemberLinks": 299,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "growing head 5xYourTeam",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb33",
|
||||
"builderId": 33,
|
||||
"name": "Viral Ad Source",
|
||||
"builderTitle": "Join Our Viral Text Ad Marketing System FREE",
|
||||
"url": "https://viraladsource.com?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 20,
|
||||
"ctbMemberLinks": 170,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb34",
|
||||
"builderId": 34,
|
||||
"name": "Downline Banners",
|
||||
"builderTitle": "Put Your Banners On Autopilot With This Free Platform",
|
||||
"url": "https://downlinebanners.com?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 21,
|
||||
"ctbMemberLinks": 280,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "core head Downline Banners",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb35",
|
||||
"builderId": 35,
|
||||
"name": "Network Ad Space",
|
||||
"builderTitle": "Network Ad Space - Our CTB Ad Marketplace",
|
||||
"url": "https://networkadspace.com/?id={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 22,
|
||||
"ctbMemberLinks": 288,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "network site Network Ad Space",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb36",
|
||||
"builderId": 36,
|
||||
"name": "Viral Banner Blitz",
|
||||
"builderTitle": "Grow Your For Free With Viral Banner Blitz",
|
||||
"url": "https://viralbannerblitz.com?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 23,
|
||||
"ctbMemberLinks": 272,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "core head Viral Banner Blitz",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb37",
|
||||
"builderId": 37,
|
||||
"name": "Ads Earn ETH",
|
||||
"builderTitle": "Ads Earn ETH",
|
||||
"url": "https://adsearneth.com/?id={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "6",
|
||||
"order": 24,
|
||||
"ctbMemberLinks": 61,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb39",
|
||||
"builderId": 39,
|
||||
"name": "PassiveDrip",
|
||||
"builderTitle": "Join Our Auto Faucet And Earn Every 2 Minutes At PassiveDrip.com",
|
||||
"url": "https://passivedrip.com/?ref={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 25,
|
||||
"ctbMemberLinks": 152,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb40",
|
||||
"builderId": 40,
|
||||
"name": "CTB VIP",
|
||||
"builderTitle": "The Crypto Team Build VIP Program",
|
||||
"url": "https://teambuildvip.com/lcpjoinvip.php?r={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 26,
|
||||
"ctbMemberLinks": 255,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "growing head VIP (The Crypto Team Build VIP Program)",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb41",
|
||||
"builderId": 41,
|
||||
"name": "PaidOfferTasks",
|
||||
"builderTitle": "PaidOfferTasks.com - Get Paid To Complete Surveys And Tasks",
|
||||
"url": "https://paidoffertasks.com/?ref={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 27,
|
||||
"ctbMemberLinks": 89,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb43",
|
||||
"builderId": 43,
|
||||
"name": "My Link Shortener",
|
||||
"builderTitle": "My Link Shortener",
|
||||
"url": "https://mylnks.xyz/?ref={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 28,
|
||||
"ctbMemberLinks": 76,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb46",
|
||||
"builderId": 46,
|
||||
"name": "CrankOutAI",
|
||||
"builderTitle": "CrankOutAI.com",
|
||||
"url": "https://crankoutai.com/?ref={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 29,
|
||||
"ctbMemberLinks": 81,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb47",
|
||||
"builderId": 47,
|
||||
"name": "BTC4Hits",
|
||||
"builderTitle": "BTC4Hits URL Rotator",
|
||||
"url": "https://btc4hits.com/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 30,
|
||||
"ctbMemberLinks": 237,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "network site BTC4Hits (merging into LinkSpin)",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb49",
|
||||
"builderId": 49,
|
||||
"name": "Mailer.gold",
|
||||
"builderTitle": "Mailer.gold",
|
||||
"url": "https://mailer.gold/{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "7",
|
||||
"order": 31,
|
||||
"ctbMemberLinks": 85,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": true
|
||||
},
|
||||
{
|
||||
"id": "ctb50",
|
||||
"builderId": 50,
|
||||
"name": "100 Percent Clicks",
|
||||
"builderTitle": "100 Percent Clicks Viral Advertising Mailer",
|
||||
"url": "https://100percentclicks.com/index.php?r={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "13",
|
||||
"order": 32,
|
||||
"ctbMemberLinks": 93,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb51",
|
||||
"builderId": 51,
|
||||
"name": "Traffic Leads 2 Income",
|
||||
"builderTitle": "Traffic Leads 2 Income - The Income Driven Viral Mailer",
|
||||
"url": "https://tl2icashmailer.com/?rid={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "13",
|
||||
"order": 33,
|
||||
"ctbMemberLinks": 83,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb59",
|
||||
"builderId": 59,
|
||||
"name": "Xpress Viral Mailer",
|
||||
"builderTitle": "Xpress Viral Mailer",
|
||||
"url": "https://xpressviralmailer.com/index.php?referrer={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "0",
|
||||
"order": 34,
|
||||
"ctbMemberLinks": 52,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb62",
|
||||
"builderId": 62,
|
||||
"name": "Tangled Social",
|
||||
"builderTitle": "Tangled Social (Earn Crypto Just For Using It)",
|
||||
"url": "https://{affiliateid}.tangled.com",
|
||||
"idKind": "subdomain",
|
||||
"cat": "9",
|
||||
"order": 35,
|
||||
"ctbMemberLinks": 33,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb63",
|
||||
"builderId": 63,
|
||||
"name": "Ads Earn XRP",
|
||||
"builderTitle": "Ads Earn XRP",
|
||||
"url": "https://www.adsearnxrp.com/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "6",
|
||||
"order": 36,
|
||||
"ctbMemberLinks": 24,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb66",
|
||||
"builderId": 66,
|
||||
"name": "Passive Crypto AI",
|
||||
"builderTitle": "Passive Crypto AI",
|
||||
"url": "https://passivecryptoai.com/?r={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 37,
|
||||
"ctbMemberLinks": 33,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "network rebuild Passive Crypto AI (downline-builder site)",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb67",
|
||||
"builderId": 67,
|
||||
"name": "Really Smart Art",
|
||||
"builderTitle": "Really Smart Art",
|
||||
"url": "https://www.reallysmart.art/video.aspx?u={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "10",
|
||||
"order": 38,
|
||||
"ctbMemberLinks": 29,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": true
|
||||
},
|
||||
{
|
||||
"id": "ctb69",
|
||||
"builderId": 69,
|
||||
"name": "Sparky AI (PHG Hub)",
|
||||
"builderTitle": "Automatic Duplication System With Sparky AI",
|
||||
"url": "https://phghub.ai/{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "0",
|
||||
"order": 39,
|
||||
"ctbMemberLinks": 16,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb71",
|
||||
"builderId": 71,
|
||||
"name": "Amplify AI Workshop",
|
||||
"builderTitle": "Jour Our Amplify AI Workshop Skool Community",
|
||||
"url": "https://www.skool.com/amplify-ai/about?ref={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "10",
|
||||
"order": 40,
|
||||
"ctbMemberLinks": 8,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb72",
|
||||
"builderId": 72,
|
||||
"name": "CTB Rewards Telegram App",
|
||||
"builderTitle": "Earn For Free In Our Native Telegram CTB Rewards App",
|
||||
"url": "https://ctbrewards.saasy.top/invite/{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 41,
|
||||
"ctbMemberLinks": 11,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "builder URL had a misspelled {affiliateid} placeholder, fixed here",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb73",
|
||||
"builderId": 73,
|
||||
"name": "ClickBaitPays",
|
||||
"builderTitle": "ClickBaitPays",
|
||||
"url": "https://cbp-calculator.saasy.top/?ref={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "9",
|
||||
"order": 42,
|
||||
"ctbMemberLinks": 16,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb74",
|
||||
"builderId": 74,
|
||||
"name": "RM Circle",
|
||||
"builderTitle": "Join Our RM Circle Team Build",
|
||||
"url": "https://rmcircle.team/my/{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "9",
|
||||
"order": 43,
|
||||
"ctbMemberLinks": 12,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "Marty 2026-11-14: RM Circle is a wild head (never a network core head)",
|
||||
"defaultId": "",
|
||||
"featured": true
|
||||
},
|
||||
{
|
||||
"id": "ctb75",
|
||||
"builderId": 75,
|
||||
"name": "Ads Earn SOL",
|
||||
"builderTitle": "Ads Earn SOL",
|
||||
"url": "https://www.adsearnsol.com/?{affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "6",
|
||||
"order": 44,
|
||||
"ctbMemberLinks": 3,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb76",
|
||||
"builderId": 76,
|
||||
"name": "Massifly",
|
||||
"builderTitle": "Massifly",
|
||||
"url": "https://massifly.com/?r={affiliateid}",
|
||||
"idKind": "path",
|
||||
"cat": "13",
|
||||
"order": 45,
|
||||
"ctbMemberLinks": 3,
|
||||
"hidden": false,
|
||||
"network": false,
|
||||
"note": "",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
},
|
||||
{
|
||||
"id": "ctb77",
|
||||
"builderId": 77,
|
||||
"name": "InstantAdPay",
|
||||
"builderTitle": "InstantAdPay",
|
||||
"url": "https://instantadpay.com/join/{affiliateid}?promo=CTB&src=cryptoteambuild",
|
||||
"idKind": "path",
|
||||
"cat": "11",
|
||||
"order": 46,
|
||||
"ctbMemberLinks": 4,
|
||||
"hidden": true,
|
||||
"network": true,
|
||||
"note": "core head InstantAdPay",
|
||||
"defaultId": "",
|
||||
"featured": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// The Seed Bed rules: planting, saved IDs, the sprout meter, the review stage, the sponsor-first link and the transplant export.
|
||||
// Data lives in store.js; the HTTP side is in server.js. Parts reused on purpose:
|
||||
// myheads.js (DownlineHydra, unit-tested there): the link and text checks for a member-added program
|
||||
// wild.js (DownlineHydra): a pasted whole referral link -> the ID in it (cleanId), the plain home page (homeUrl)
|
||||
//
|
||||
// Packet lifecycle
|
||||
// status: live | held (yellow or red link, or reported: Marty's queue) | removed | dormant (an old YourProgramBuilder program
|
||||
// waiting for its owner to confirm it)
|
||||
// stage: sprouting -> review (REVIEW_SAVES saves from distinct confirmed network members) -> approved (transplanted: exported
|
||||
// for the CTB builder and DownlineHydra) | rejected (stays in the Seed Bed, can sprout on; Marty may look again later)
|
||||
// A packet is shown in the bed only while it is live and its link check is green, or yellow and approved by Marty for exactly
|
||||
// the text he saw (an edit sends it back to the queue).
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const store = require('./store');
|
||||
const myheads = require('./myheads');
|
||||
const wild = require('./wild');
|
||||
const cfgMod = require('./config');
|
||||
|
||||
const C = () => cfgMod.get();
|
||||
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
|
||||
const COSTS = ['free', 'paid'];
|
||||
const lc = v => String(v || '').toLowerCase();
|
||||
|
||||
// the CTB builder snapshot DownlineHydra reads (seed/builder.seed.json, 46 programs 11-14): a program already there is not planted
|
||||
// again here (its members save their IDs on DownlineHydra's wild heads)
|
||||
let builder = null;
|
||||
function builderList() {
|
||||
if (builder) return builder;
|
||||
let d = { programs: [], cats: [] };
|
||||
try { d = JSON.parse(fs.readFileSync(path.join(__dirname, 'seed', 'builder.seed.json'), 'utf8')); } catch (e) {}
|
||||
const progs = (d.programs || []).filter(p => !p.network);
|
||||
builder = { cats: (d.cats || []).filter(c => String(c.id) !== '12'), hosts: [...new Set(progs.map(p => myheads.hostOf(p.url.replace(/\{affil[a-z]*id\}\.?/gi, ''))).filter(Boolean))] };
|
||||
return builder;
|
||||
}
|
||||
const cats = () => builderList().cats;
|
||||
|
||||
const textHash = p => crypto.createHash('sha256').update([p.name, p.url, p.desc, p.cost, p.costText, p.contract].join('\n')).digest('hex').slice(0, 16);
|
||||
|
||||
// the planting form -> { error, field } | { ok, fields, flags }
|
||||
function validatePlant(b) {
|
||||
const L = C().packet;
|
||||
const v = myheads.validate({ name: b.name, url: b.url, desc: b.desc, myId: b.myId, cat: b.cat }, { limits: { name: L.name, desc: L.desc }, wildHosts: builderList().hosts, cats: cats() });
|
||||
if (v.error) {
|
||||
if (v.wild) return { error: 'That program is already in the Crypto Team Build Network builder. Save your ID for it on DownlineHydra\'s wild heads instead.', field: 'url', wild: true };
|
||||
return v;
|
||||
}
|
||||
if (!v.head.template) return { error: 'Put {id} in the link where the referral ID goes (for example https://program.example/?ref={id}), so every member can save their own ID.', field: 'url' };
|
||||
if (v.head.desc.length < 10) return { error: 'Say in a sentence what the program is (10 to ' + L.desc + ' characters).', field: 'desc' };
|
||||
const cost = COSTS.includes(String(b.cost)) ? String(b.cost) : null;
|
||||
if (!cost) return { error: 'Say whether the program is free to join or costs money to join.', field: 'cost' };
|
||||
const costText = String(b.costText == null ? '' : b.costText).replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(/[–—]/g, '-').replace(/\s+/g, ' ').trim().slice(0, L.cost + 1);
|
||||
if (costText.length > L.cost) return { error: 'Keep the cost note to ' + L.cost + ' characters.', field: 'costText' };
|
||||
if (cost === 'paid' && costText.length < 2) return { error: 'Say what it costs to join (for example "$10 one-time" or "from 25 POL").', field: 'costText' };
|
||||
let contract = String(b.contract || '').trim();
|
||||
if (contract && !ADDR_RE.test(contract)) return { error: 'The contract address must be 0x followed by 40 letters or numbers. Leave it empty if the program has no contract.', field: 'contract' };
|
||||
contract = contract.toLowerCase();
|
||||
const flags = v.flags.slice();
|
||||
if (/\b(guaranteed|passive income|daily (profit|returns?)|\d+x your|roi)\b/i.test(v.head.name + ' ' + v.head.desc + ' ' + costText)) flags.push('income claim words');
|
||||
return { ok: true, fields: { name: v.head.name, url: v.head.url, template: true, ownerId: v.head.myId, desc: v.head.desc, cat: v.head.cat, host: v.head.host, cost, costText: cost === 'paid' ? costText : '', contract }, flags };
|
||||
}
|
||||
|
||||
// an ID a member types (or a whole referral link they paste) -> the clean ID, '' (remove), or null (not an ID for this packet)
|
||||
const asWild = p => ({ url: String(p.url).replace(/\{id\}/g, '{affiliateid}'), idKind: 'path' });
|
||||
function cleanId(p, raw) { return wild.cleanId(asWild(p), raw); }
|
||||
const fill = (p, id) => String(p.url).replace(/\{id\}/g, encodeURIComponent(String(id)));
|
||||
const homeUrl = p => wild.homeUrl(asWild(p));
|
||||
|
||||
const shown = p => !!p && p.status === 'live' && p.check && (p.check.state === 'green' || (p.check.state === 'yellow' && p.yellowOk === textHash(p)));
|
||||
const confirmed = addr => { const m = store.member(addr); return !!(m && m.netOk === true && !m.blocked); };
|
||||
// the sprout meter: saved IDs from distinct confirmed network members (the planter's own ID counts as one)
|
||||
function sprouts(p) { const seen = new Set(); for (const s of store.savesOf(p.id)) if (s.refId && confirmed(s.owner)) seen.add(s.hubId || s.owner); if (p.owner && p.ownerId && confirmed(p.owner)) seen.add((store.member(p.owner) || {}).hubId || p.owner); return seen.size; }
|
||||
// after any save: a sprouting packet that reached the threshold moves to Marty's review queue (it keeps sprouting while it waits)
|
||||
function grow(p) {
|
||||
const n = sprouts(p); p.sprouts = n;
|
||||
if ((p.stage || 'sprouting') === 'sprouting' && n >= C().reviewSaves) { p.stage = 'review'; p.reviewAt = Date.now(); store.savePacket(p); return { review: true, n }; }
|
||||
store.savePacket(p); return { review: false, n };
|
||||
}
|
||||
|
||||
// the one link a visitor sees: the nearest person in `chain` who saved an ID here, else the planter's ID, else the plain home page.
|
||||
// chain = [{ wallet, username, depth }] nearest first (a member page / ?ref= visitor: that member first at depth 0; a signed-in
|
||||
// member: their sponsor at depth 1, ...)
|
||||
function sponsorLink(p, chain) {
|
||||
const byWallet = new Map(), byName = new Map();
|
||||
for (const s of store.savesOf(p.id)) { if (!s.refId) continue; byWallet.set(s.owner, s); if (s.username) byName.set(lc(s.username), s); }
|
||||
for (const c of chain || []) {
|
||||
const s = (c.wallet && byWallet.get(lc(c.wallet))) || (c.username && byName.get(lc(c.username)));
|
||||
if (s) return { url: fill(p, s.refId), by: s.username || null, depth: c.depth, fallback: null, save: s.id };
|
||||
}
|
||||
if (p.ownerId) return { url: fill(p, p.ownerId), by: p.ownerName || null, depth: null, fallback: 'planter', save: null };
|
||||
return { url: homeUrl(p), by: null, depth: null, fallback: 'none', save: null };
|
||||
}
|
||||
|
||||
// a packet as the public pages show it (never a wallet, never anyone's saved ID except through the click relay)
|
||||
function card(p, extra) {
|
||||
const n = p.sprouts != null ? p.sprouts : sprouts(p);
|
||||
return Object.assign({ id: p.id, no: String(p.id).padStart(3, '0'), name: p.name, desc: p.desc, host: p.host, cost: p.cost, costText: p.costText || '', contract: p.contract || null,
|
||||
cat: p.cat, sownAt: p.createdAt, planter: p.ownerName || null, saves: n, need: C().reviewSaves, stage: p.stage || 'sprouting', check: p.check ? p.check.state : null,
|
||||
checkedAt: p.check ? p.check.at : null, clicks: p.vclicks || 0, href: '/p/' + p.id }, extra || {});
|
||||
}
|
||||
|
||||
// approved packets for the Crypto Team Build Network builder / DownlineHydra's wild heads, every saved ID carried over.
|
||||
// The link is given in the builder's own form ({affiliateid}). Saved IDs of blocked or unconfirmed people are left out.
|
||||
function exportPacket(p) {
|
||||
const ids = [];
|
||||
for (const s of store.savesOf(p.id)) { if (!s.refId || !confirmed(s.owner)) continue; const m = store.member(s.owner) || {}; ids.push({ username: m.username || s.username || null, hubId: m.hubId || s.hubId || null, refId: s.refId, savedAt: s.at }); }
|
||||
const pm = p.owner ? store.member(p.owner) || {} : {};
|
||||
if (p.ownerId && !ids.some(x => x.hubId && x.hubId === pm.hubId)) ids.unshift({ username: pm.username || p.ownerName || null, hubId: pm.hubId || null, refId: p.ownerId, savedAt: p.createdAt, planter: true });
|
||||
return { ypbId: p.id, name: p.name, url: asWild(p).url, idKind: 'path', desc: p.desc, cat: p.cat, host: p.host, cost: p.cost, costText: p.costText || '', contract: p.contract || null,
|
||||
planter: { username: pm.username || p.ownerName || null, hubId: pm.hubId || null }, approvedAt: p.decidedAt || null, note: p.decidedNote || '', ids };
|
||||
}
|
||||
|
||||
module.exports = { validatePlant, cleanId, fill, homeUrl, shown, sprouts, grow, sponsorLink, card, exportPacket, textHash, cats, builderList, confirmed, COSTS };
|
||||
@@ -0,0 +1,639 @@
|
||||
// YourProgramBuilder web app, the Seed Bed (yourprogrambuilder.com rebuild, Marty 2026-11-17). Plain Node http server, no framework
|
||||
// (the InstantAdPay / Downline Banners / VBB / ViralAdBlitz / ViralAdSource pattern).
|
||||
// "Bring your program. The network grows it." A network member (network sign-in through the hub, membership checked with the hub)
|
||||
// plants a program free; members save their referral ID in its packet; at REVIEW_SAVES saves it goes to Marty's review queue and,
|
||||
// approved, is exported for the Crypto Team Build Network builder / DownlineHydra wild heads with every saved ID (seedbed.js).
|
||||
// Paid part: a one-time Spotlight for a packet on YPBShop (shop.js, NOT deployed; staging has no contract).
|
||||
// Pages: / (the Seed Bed), /p/<id> (a packet), /<username> (a member's packets, their links first), /my, /spotlight, /transplanted,
|
||||
// /ledger, /contract, /promote, /guides/*, /terms, /disclaimer, /privacy, /admin.
|
||||
'use strict';
|
||||
const http = require('http');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const { verifyMessage, getAddress } = require('ethers');
|
||||
const cfgMod = require('./config');
|
||||
|
||||
const C = cfgMod.get();
|
||||
fs.mkdirSync(C.dataDir, { recursive: true });
|
||||
const docstore = require('./docstore'); docstore.install(C.dataDir);
|
||||
const store = require('./store');
|
||||
const wire = require('./wire');
|
||||
const seedbed = require('./seedbed');
|
||||
const linkcheck = require('./linkcheck');
|
||||
const networksso = require('./networksso');
|
||||
const shop = require('./shop');
|
||||
const promokit = require('./promokit');
|
||||
const hubreport = require('./hubreport');
|
||||
const hubpeople = require('./hubpeople');
|
||||
const hubevents = require('./hubevents');
|
||||
const hubline = require('./hubline');
|
||||
const proof = require('./proof');
|
||||
const netsites = require('./netsites');
|
||||
const netdeals = require('./netdeals');
|
||||
const lstrack = require('./lstrack');
|
||||
const chatbot = require('./chatbot');
|
||||
const adwriter = require('./hubadwriter');
|
||||
|
||||
const PUB = path.join(__dirname, 'public');
|
||||
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
|
||||
const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/;
|
||||
const PAGE_RE = /^\/([A-Za-z0-9_.-]{2,40})\/?$/;
|
||||
const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|preview|monitor|wget|curl|python|httpclient|scrapy|semrush|ahrefs|headless|lighthouse|pingdom|go-http|java\/|okhttp|axios|node-fetch|phantom|selenium|puppeteer|playwright/i;
|
||||
const SECRET = (() => {
|
||||
if (process.env.SESSION_SECRET) return process.env.SESSION_SECRET;
|
||||
const f = path.join(C.dataDir, '.secret');
|
||||
try { return fs.readFileSync(f, 'utf8').trim(); } catch (e) {}
|
||||
const s = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, s, { mode: 0o600 }); } catch (e) {} return s;
|
||||
})();
|
||||
const hash = s => crypto.createHmac('sha256', SECRET).update(s).digest('hex').slice(0, 24);
|
||||
wire.setSecret(SECRET);
|
||||
const TEST_SWITCH = C.staging && !/(^|\.)yourprogrambuilder\.com$/i.test(C.site); // never on the real domain
|
||||
|
||||
// ---- http helpers ----
|
||||
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp',
|
||||
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
|
||||
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://linkspin.app https://polhunter.com; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
|
||||
+ "img-src 'self' data: blob: https:; connect-src 'self' https://linkspin.app https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org "
|
||||
+ "https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; "
|
||||
+ "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: 'self'";
|
||||
function headers(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); }
|
||||
function json(res, code, obj, extra) { res.writeHead(code, headers(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); res.end(JSON.stringify(obj)); }
|
||||
function sendFile(res, file, extra, code) {
|
||||
fs.readFile(file, (err, data) => {
|
||||
if (err) { res.writeHead(404, headers({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
res.writeHead(code || 200, headers(Object.assign({ 'Content-Type': MIME[ext] || 'application/octet-stream', 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' }, extra)));
|
||||
res.end(data);
|
||||
});
|
||||
}
|
||||
function readRaw(req, max) {
|
||||
return new Promise((resolve, reject) => { const ch = []; let n = 0;
|
||||
req.on('data', c => { n += c.length; if (n > max * 8) { req.destroy(); return; } if (n <= max) ch.push(c); });
|
||||
req.on('end', () => n > max ? reject(new Error('too big')) : resolve(Buffer.concat(ch))); req.on('error', reject); });
|
||||
}
|
||||
async function readBody(req) { const b = await readRaw(req, 32 * 1024); try { return b.length ? JSON.parse(b.toString('utf8')) : {}; } catch (e) { return {}; } }
|
||||
function cookies(req) { const o = {}; for (const p of (req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { o[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } return o; }
|
||||
function cookie(name, val, maxAgeSec, httpOnly) { return name + '=' + encodeURIComponent(val) + '; Path=/; SameSite=Lax; Max-Age=' + maxAgeSec + (httpOnly ? '; HttpOnly' : '') + (C.isProd ? '; Secure' : ''); }
|
||||
function ip(req) {
|
||||
if (process.env.CF_PROXIED === '1' && req.headers['cf-connecting-ip']) return String(req.headers['cf-connecting-ip']).trim();
|
||||
const xff = String(req.headers['x-forwarded-for'] || '').split(',').map(s => s.trim()).filter(Boolean);
|
||||
return (xff.length ? xff[xff.length - 1] : String(req.socket.remoteAddress || '')).replace(/^::ffff:/, '');
|
||||
}
|
||||
const isBot = req => !req.headers['user-agent'] || BOT_UA.test(req.headers['user-agent']);
|
||||
const visitorKey = req => hash('vk|' + ip(req) + '|' + (req.headers['user-agent'] || ''));
|
||||
const ipKey = req => hash('ip|' + ip(req));
|
||||
const buckets = new Map();
|
||||
function limited(req, name, max, windowMs) {
|
||||
const k = name + ':' + ip(req); const now = Date.now(); let b = buckets.get(k);
|
||||
if (!b || now - b.t > windowMs) { b = { t: now, n: 0 }; buckets.set(k, b); }
|
||||
if (buckets.size > 100000) buckets.clear();
|
||||
return ++b.n > max;
|
||||
}
|
||||
const isAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const g = String(req.headers['x-admin-token'] || '');
|
||||
return t.length >= 8 && g.length === t.length && crypto.timingSafeEqual(Buffer.from(g), Buffer.from(t)); };
|
||||
|
||||
// ---- network membership through the hub (InstantAdPay's lookup only while the hub is unreachable) ----
|
||||
const netCache = new Map();
|
||||
async function netMember(q) {
|
||||
const h = q.u ? await hubpeople.byRef(q.u) : await hubpeople.byWallet(q.a);
|
||||
if (h.ok) { const a = hubpeople.wallet(h.person); return a ? { address: a, username: h.person.username ? String(h.person.username) : null, hubId: h.person.id || null, via: 'hub' } : null; }
|
||||
if (!C.networkLookupUrl) return null;
|
||||
const k = q.u ? 'u:' + q.u.toLowerCase() : 'a:' + q.a.toLowerCase();
|
||||
const hit = netCache.get(k); if (hit && Date.now() - hit.at < 3600000) return hit.m;
|
||||
let m = null;
|
||||
try { const ac = new AbortController(); setTimeout(() => ac.abort(), 4000).unref();
|
||||
const qs = q.u ? 'u=' + encodeURIComponent(q.u) : 'a=' + encodeURIComponent(q.a);
|
||||
const j = await (await fetch(C.networkLookupUrl + '?' + qs, { signal: ac.signal })).json();
|
||||
if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username), via: 'iap' }; } catch (e) { return null; }
|
||||
netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear();
|
||||
return m;
|
||||
}
|
||||
const netVerified = m => !!m && m.netOk === true && !m.blocked;
|
||||
async function verifyNet(addr) {
|
||||
const m = store.member(addr); if (!m) return;
|
||||
if (netVerified(m) && m.hubId && m.netAt && Date.now() - m.netAt < 6 * 3600000) return;
|
||||
const h = await hubpeople.byWallet(addr);
|
||||
if (h.ok && h.person) {
|
||||
const patch = { netOk: !h.person.blocked, blocked: !!h.person.blocked, netAt: Date.now(), netBy: 'hub', hubId: h.person.id || null };
|
||||
const n = h.person.username ? String(h.person.username) : null;
|
||||
if (n && NAME_RE.test(n)) { const other = store.memberByName(n); if (!other || other.address === m.address) patch.username = n; }
|
||||
store.upsertMember(addr, patch); return;
|
||||
}
|
||||
if (h.ok && !h.person) { if (!m.testMember) store.upsertMember(addr, { netOk: false, netAt: Date.now(), netBy: 'hub' }); return; }
|
||||
// hub down: InstantAdPay's lookup, or how the member signed in
|
||||
if (netVerified(m)) return;
|
||||
const n = await netMember({ a: addr }).catch(() => null);
|
||||
if ((n && n.address === m.address) || m.via === 'iap' || m.via === 'linkspin' || m.via === 'hub') store.upsertMember(addr, { netOk: true, netAt: Date.now(), netBy: 'fallback', username: m.username || (n && n.username) || null });
|
||||
}
|
||||
const session = req => store.session(cookies(req)['ypb.sid']);
|
||||
|
||||
networksso.init({ self: C.siteId, peer: 'iap', peerBase: () => C.iapBase, from: { iap: () => C.iapBase, linkspin: () => C.lsBase },
|
||||
isProd: C.isProd, dataDir: C.dataDir, defaultPath: '/my',
|
||||
member: async req => { const s = session(req); return s ? { address: s.address } : null; },
|
||||
accept: async (email, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
||||
signIn: async (email, req, v) => {
|
||||
const patch = { via: v.iss };
|
||||
if (v.name && NAME_RE.test(v.name)) { const other = store.memberByName(v.name); if (!other || other.address === v.wallet) patch.username = v.name; }
|
||||
store.upsertMember(v.wallet, patch);
|
||||
await verifyNet(v.wallet).catch(() => {});
|
||||
return cookie('ypb.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true);
|
||||
},
|
||||
landing: to => to, signinPath: to => to });
|
||||
hubevents.init({ dataDir: C.dataDir, site: 'yourprogrambuilder', end: who => store.endSessions(x => who.match(x) || who.match(store.member(x.address)), who.before) });
|
||||
|
||||
// ---- old site links (the YourFreeWorld site): /?<old username>, /index.php?<old>, /splashpg.php?r=<old>, /lcp.php?r=<old>,
|
||||
// /join.php?r=<old> -> that person's member page here (oldrefs.json from the reconcile, matched by email to the hub, loaded by
|
||||
// POST /api/admin/oldrefs). The old member pages map to their new places; any other *.php -> / ----
|
||||
let oldRefs = { at: 0, map: {} };
|
||||
function oldRefMap() {
|
||||
if (Date.now() - oldRefs.at < 60000) return oldRefs.map;
|
||||
let m = {}; try { m = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'oldrefs.json'), 'utf8')) || {}; } catch (e) {}
|
||||
oldRefs = { at: Date.now(), map: m }; return m;
|
||||
}
|
||||
const OLD_PAGES = { '/login.php': '/my', '/loginform.php': '/my', '/stats.php': '/my', '/addprograms.php': '/my?tab=plant', '/updateprograms.php': '/my', '/programs.php': '/', '/programs1.php': '/',
|
||||
'/faq.php': '/guides/faq', '/terms.php': '/terms', '/privacy.php': '/privacy', '/upgradepro.php': '/spotlight', '/advertise.php': '/spotlight', '/marketingtools.php': '/promote', '/contactus2.php': '/guides/faq' };
|
||||
function oldLink(u) {
|
||||
const p = u.pathname; const bare = u.search.slice(1).split('&')[0];
|
||||
if (p === '/' || p === '/index.php') { if (!/^[A-Za-z0-9_.-]{2,40}$/.test(bare)) return p === '/' ? null : '/'; }
|
||||
else if (!/\.php$/i.test(p)) return null;
|
||||
const lp = p.toLowerCase();
|
||||
const named = ['/splashpg.php', '/lcp.php', '/join.php'].includes(lp);
|
||||
const old = named ? String(u.searchParams.get('r') || u.searchParams.get('ref') || (/^[A-Za-z0-9_.-]{2,40}$/.test(bare) ? bare : '')) : (lp === '/' || lp === '/index.php') ? bare : '';
|
||||
const net = /^[A-Za-z0-9_.-]{2,40}$/.test(old) ? oldRefMap()[old.toLowerCase()] : null;
|
||||
if (net) return '/' + encodeURIComponent(net);
|
||||
return OLD_PAGES[lp] || '/';
|
||||
}
|
||||
|
||||
const PAGES = { '/': 'index.html', '/my': 'my.html', '/spotlight': 'spotlight.html', '/transplanted': 'transplanted.html', '/ledger': 'ledger.html', '/contract': 'contract.html',
|
||||
'/admin': 'admin.html', '/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html',
|
||||
'/guides': 'guides.html', '/guides/how-it-works': 'guide-how.html', '/guides/is-it-legit': 'guide-legit.html', '/guides/free-account': 'guide-free.html', '/guides/planting': 'guide-planting.html', '/guides/faq': 'guide-faq.html' };
|
||||
const RESERVED = new Set(['api', 'assets', 'art', 'go', 'r', 'p', 'sso', 'health', 'promote', 'sitemap.xml', 'robots.txt', 'favicon.ico', 'index.php', 'my', 'spotlight', 'transplanted',
|
||||
'ledger', 'contract', 'admin', 'terms', 'disclaimer', 'privacy', 'guides', 'faq', 'how', 'plant', 'bed', 'seedbed', 'support']);
|
||||
const challenges = new Map();
|
||||
const tickets = new Map();
|
||||
const srcHost = raw => { try { const x = new URL(String(raw || '')); if (!/^https?:$/.test(x.protocol)) return ''; const h = x.hostname.toLowerCase().replace(/^www\./, ''); return h === C.site || h.endsWith('.' + C.site) || !h.includes('.') ? '' : h.slice(0, 80); } catch (e) { return ''; } };
|
||||
const refOf = req => { const r = String(cookies(req)['ypb.ref'] || ''); return NAME_RE.test(r) ? r : null; };
|
||||
const refCookie = name => cookie('ypb.ref', name, C.viaDays * 86400, false);
|
||||
|
||||
function issueTicket(req, page, shown, src) {
|
||||
if (isBot(req) || req.headers['sec-fetch-site'] === 'cross-site' || limited(req, 'ticket', 240, 3600000)) return null;
|
||||
const s = session(req); const t = crypto.randomBytes(12).toString('hex');
|
||||
tickets.set(t, { vk: visitorKey(req), iph: ipKey(req), at: Date.now(), page, shown, src: srcHost(src), viewer: s ? s.address : null });
|
||||
if (tickets.size > 50000) { const cut = Date.now() - 1800000; for (const [k, v] of tickets) if (v.at < cut) tickets.delete(k); }
|
||||
return t;
|
||||
}
|
||||
const withReturn = url => { try { const x = new URL(url); if (!/^(www\.)?(instantadpay\.com|linkspin\.app)$/.test(x.hostname) && x.origin !== new URL(C.iapBase).origin) return url; x.searchParams.set('return', C.siteId); x.searchParams.set('to', '/my'); return x.toString(); } catch (e) { return url; } };
|
||||
const joinUrl = ref => withReturn(ref ? C.joinUrl.split('{ref}').join(encodeURIComponent(ref)) : C.joinUrl.replace(/\/join\/\{ref\}.*$/, '/').replace(/[?&]ref=\{ref\}/, '').split('{ref}').join(''));
|
||||
function cleanText(s, max) { return String(s == null ? '' : s).replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(/[–—]/g, '-').replace(/\s+/g, ' ').trim().slice(0, max + 1); }
|
||||
// LinkSpin network ad zones (the ViralAdSource hook): LS_ZONES='{"footWide":"ls-..","footPhone":"ls-..","ledger":"ls-..","notFound":"ls-.."}', made on
|
||||
// Marty's LinkSpin account through LinkSpin's admin zone route at go-live. Unset (staging): no zones shown.
|
||||
const lsZones = () => { try { const z = JSON.parse(process.env.LS_ZONES || '{}'); const o = {}; for (const k of ['footWide', 'footPhone', 'ledger', 'notFound']) if (/^ls-[a-z0-9]{4,12}$/.test(String(z[k] || ''))) o[k] = z[k]; return o; } catch (e) { return {}; } };
|
||||
const uname = a => { const m = store.member(a); return m && m.username ? m.username : null; };
|
||||
const todayStats = () => { const t = store.today(); return { saves: t.saves || 0, planted: t.planted || 0, vclicks: t.vclicks || 0, packets: store.packets().filter(seedbed.shown).length }; };
|
||||
function myEarned(me) {
|
||||
let wei = 0n; const items = [];
|
||||
for (const x of wire.purchases()) for (const q of x.pays || []) if (q.to === me && q.kind > 0) { try { wei += BigInt(q.wei); } catch (e) {} items.push({ tx: String(x.key).split(':')[0], at: (x.blockAt ? x.blockAt * 1000 : x.at), kind: q.kind, depth: q.depth, wei: q.wei, failed: !!q.failed, buyerName: uname(x.buyer) }); }
|
||||
return { wei: wei.toString(), items: items.sort((a, b) => (b.at || 0) - (a.at || 0)).slice(0, 50) };
|
||||
}
|
||||
|
||||
// the chain a link is chosen along: a ?r= / member-page / ref-cookie visitor starts at that member (depth 0) and goes up their line;
|
||||
// a signed-in member starts at their sponsor (depth 1). The hub is the source of the line (cached 5 minutes, hubline.js).
|
||||
async function chainFor(req, override) {
|
||||
const s = session(req); const ref = override || refOf(req);
|
||||
if (ref && (!s || (uname(s.address) || '').toLowerCase() !== ref.toLowerCase())) {
|
||||
const lo = await hubline.lineOf({ ref: ref.toLowerCase() }, 6).catch(() => ({ ok: false, line: [] }));
|
||||
const local = store.memberByName(ref);
|
||||
const head = { wallet: (lo.person && hubpeople.wallet(lo.person)) || (local && local.address) || null, username: ref, depth: 0 };
|
||||
return [head].concat((lo.line || []).filter(x => !x.blocked).map(x => ({ wallet: x.wallet, username: x.username, depth: x.depth })));
|
||||
}
|
||||
if (s) { const lo = await hubline.lineOf({ wallet: s.address }, 6).catch(() => ({ ok: false, line: [] })); return (lo.line || []).filter(x => !x.blocked).map(x => ({ wallet: x.wallet, username: x.username, depth: x.depth })); }
|
||||
return [];
|
||||
}
|
||||
// a fresh check of a packet's link (plant, edit, recheck, admin). Probe off (LINK_PROBE=0, local tests): text flags only.
|
||||
async function checkPacket(p, flags) {
|
||||
const pr = C.linkProbe ? await linkcheck.probe(p.url).catch(() => ({ ok: false, why: 'check failed' })) : { skipped: true };
|
||||
const v = linkcheck.verdict(flags || p.flags || [], pr, p.check);
|
||||
p.check = Object.assign({ at: Date.now() }, v); p.flags = flags || p.flags || [];
|
||||
if (p.status === 'live' || p.status === 'held') p.status = v.state === 'green' || (v.state === 'yellow' && p.yellowOk === seedbed.textHash(p)) ? 'live' : 'held';
|
||||
if (p.reportsOpen >= C.reportHold && !p.reportsCleared) p.status = 'held';
|
||||
store.savePacket(p); return v;
|
||||
}
|
||||
// the daily recheck of every live and held packet (one at a time, small batches)
|
||||
async function recheckSweep(max) {
|
||||
const due = Date.now() - C.recheckHours * 3600000; let n = 0;
|
||||
for (const p of store.packets()) {
|
||||
if (n >= (max || 20)) break;
|
||||
if (!['live', 'held'].includes(p.status) || p.manualHold || (p.check && p.check.at > due)) continue;
|
||||
n++; await checkPacket(p).catch(() => {});
|
||||
}
|
||||
return n;
|
||||
}
|
||||
function packetPublic(p, me) {
|
||||
const sp = wire.spotProgress(p.id);
|
||||
return seedbed.card(p, { spotlight: sp && sp.active ? { views: sp.views, delivered: sp.delivered } : null, mine: me ? !!store.saveOf(p.id, me) : false, own: me ? p.owner === me : false });
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const u = new URL(req.url, 'http://x'); const p = u.pathname;
|
||||
{ const host = String(req.headers.host || '').toLowerCase().split(':')[0];
|
||||
if (C.isProd && host !== C.site && host.endsWith('.' + C.site)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } }
|
||||
try {
|
||||
if (req.method === 'GET' && await networksso.page(req, res, u)) return;
|
||||
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
|
||||
if ((p === '/api/promo-kit' || p === '/promote') && promokit.handle(req, res, u, sendFile)) return;
|
||||
if ((p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) && await chatbot.handle(req, res, p, u, { json, readBody, isAdmin })) return;
|
||||
|
||||
if (req.method === 'GET' || req.method === 'HEAD') {
|
||||
if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files' });
|
||||
{ const to = oldLink(u); if (to) { res.writeHead(301, { Location: to, 'Cache-Control': 'no-store' }); return res.end(); } }
|
||||
if (PAGES[p]) {
|
||||
const ex = {}; const ref = u.searchParams.get('ref');
|
||||
if (ref && NAME_RE.test(ref)) ex['Set-Cookie'] = refCookie(ref);
|
||||
if (p === '/my' || p === '/admin') ex['X-Frame-Options'] = 'DENY';
|
||||
return sendFile(res, path.join(PUB, PAGES[p]), ex);
|
||||
}
|
||||
if (p === '/how' || p === '/faq' || p === '/plant') { res.writeHead(301, { Location: { '/how': '/guides/how-it-works', '/faq': '/guides/faq', '/plant': '/my?tab=plant' }[p] }); return res.end(); }
|
||||
const pk = /^\/p\/(\d{1,9})\/?$/.exec(p);
|
||||
if (pk) { const x = store.packet(pk[1]); if (!x || !seedbed.shown(x)) { res.writeHead(302, { Location: '/' }); return res.end(); }
|
||||
const r = u.searchParams.get('r'); return sendFile(res, path.join(PUB, 'packet.html'), r && NAME_RE.test(r) ? { 'Set-Cookie': refCookie(r) } : {}); }
|
||||
if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); }
|
||||
if (p === '/sitemap.xml') {
|
||||
const day = new Date().toISOString().slice(0, 10);
|
||||
const urls = ['/', '/guides', '/guides/how-it-works', '/guides/is-it-legit', '/guides/free-account', '/guides/planting', '/guides/faq', '/spotlight', '/transplanted', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy']
|
||||
.concat(store.packets().filter(seedbed.shown).map(x => '/p/' + x.id)).map(x => '<url><loc>https://' + C.site + x + '</loc><lastmod>' + day + '</lastmod></url>').join('');
|
||||
res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }));
|
||||
return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>');
|
||||
}
|
||||
if (p === '/robots.txt') { res.writeHead(200, headers({ 'Content-Type': 'text/plain; charset=utf-8' })); return res.end(C.staging ? 'User-agent: *\nDisallow: /\n' : 'User-agent: *\nAllow: /\nDisallow: /my\nDisallow: /admin\nDisallow: /api/\nDisallow: /go/\nDisallow: /sso/\n\nSitemap: https://' + C.site + '/sitemap.xml\n'); }
|
||||
if (p.startsWith('/assets/') || p.startsWith('/art/') || p === '/favicon.ico') {
|
||||
const f = path.normalize(path.join(PUB, p === '/favicon.ico' ? '/art/icon-192.png' : p)); if (!f.startsWith(PUB + path.sep)) { res.writeHead(400); return res.end(); }
|
||||
return sendFile(res, f);
|
||||
}
|
||||
// click relay: /go/<packet>?v=<verified token>&p=<placement>&r=<member> -> the sponsor-first referral link (LinkSpin tracked when on)
|
||||
const gm = /^\/go\/(\d{1,9})$/.exec(p);
|
||||
if (gm) {
|
||||
const x = store.packet(gm[1]); if (!x || !seedbed.shown(x)) { res.writeHead(302, { Location: '/' }); return res.end(); }
|
||||
const r = u.searchParams.get('r'); const chain = await chainFor(req, r && NAME_RE.test(r) ? r : null);
|
||||
const lk = seedbed.sponsorLink(x, chain); const sv = lk.save ? store.state().saves.find(s => s.id === lk.save) : null;
|
||||
if (!isBot(req) && !limited(req, 'click', 600, 3600000)) { const vk = visitorKey(req); const ss = session(req); wire.click(x, vk, wire.vtokenOk(vk, u.searchParams.get('v')), ss ? ss.address : null, String(u.searchParams.get('p') || '').slice(0, 20), lk.save); }
|
||||
const dest = (sv && lstrack.dest(sv, x)) || lk.url;
|
||||
if (!dest) { res.writeHead(302, { Location: '/p/' + x.id }); return res.end(); }
|
||||
res.writeHead(302, { Location: dest, 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end();
|
||||
}
|
||||
// a member's page: yourprogrambuilder.com/<network username> -> their saved packets, their links first (sets the ref tag)
|
||||
const pm = PAGE_RE.exec(p);
|
||||
if (pm && !RESERVED.has(pm[1].toLowerCase()) && !/\.php$/i.test(pm[1])) {
|
||||
const name = pm[1]; const m = store.memberByName(name);
|
||||
const h = m ? { ok: true, person: m } : await hubpeople.byRef(name.toLowerCase()).catch(() => ({ ok: false }));
|
||||
if (h.ok && h.person) return sendFile(res, path.join(PUB, 'member.html'), { 'Set-Cookie': refCookie(m ? m.username : String(h.person.username || name)) });
|
||||
}
|
||||
}
|
||||
|
||||
// -- public API
|
||||
if (p === '/api/config' && req.method === 'GET') {
|
||||
const live = await shop.liveRules(C.spotlight.sku).catch(() => null);
|
||||
return json(res, 200, { site: C.site, siteName: C.siteName, staging: C.staging, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId,
|
||||
reviewSaves: C.reviewSaves, plantQuota: C.plantQuota, packet: C.packet, cats: seedbed.cats(), recheckHours: C.recheckHours,
|
||||
spotlight: Object.assign({}, C.spotlight, live && live.sku ? { usd: live.sku.usdCents / 100, views: live.sku.views, live: true } : {}),
|
||||
split: live ? { levelBps: live.levelBps, live: true } : Object.assign({ planned: true }, C.split),
|
||||
sso: networksso.enabled() || networksso.hubOn(), shop: { live: shop.watching() && shop.signerOn(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, joinUrl: joinUrl(''),
|
||||
dh: C.dhBase, zones: lsZones(), aiWriter: await adwriter.status().then(w => (w.on ? { daily: w.daily } : null)) });
|
||||
}
|
||||
// everything a page shows, with its visit ticket. page=front|packet|member|other, id=<packet>, u=<member>
|
||||
if (p === '/api/wire' && req.method === 'GET') {
|
||||
const kind = ['front', 'packet', 'member'].includes(u.searchParams.get('page')) ? u.searchParams.get('page') : 'other';
|
||||
const s = session(req); const me = s ? s.address : null;
|
||||
const out = { today: todayStats(), week: wire.weekStats(), need: C.reviewSaves }; const shown = []; const used = new Set();
|
||||
if (kind === 'front') {
|
||||
const live = store.packets().filter(seedbed.shown);
|
||||
out.bed = live.map(x => packetPublic(x, me)).sort((a, b) => b.saves - a.saves || b.sownAt - a.sownAt);
|
||||
out.bed.forEach(x => shown.push({ id: x.id, slot: 'bed' }));
|
||||
}
|
||||
if (kind === 'packet') {
|
||||
const x = store.packet(Number(u.searchParams.get('id'))); if (!x || !seedbed.shown(x)) return json(res, 404, { error: 'That packet is not in the Seed Bed right now.' });
|
||||
const lk = seedbed.sponsorLink(x, await chainFor(req, null));
|
||||
out.packet = Object.assign(packetPublic(x, me), { linkBy: lk.by, linkFallback: lk.fallback, home: seedbed.homeUrl(x), recent: store.savesOf(x.id).filter(v => v.refId && seedbed.confirmed(v.owner)).sort((a, b) => b.at - a.at).slice(0, 12).map(v => uname(v.owner) || v.username).filter(Boolean) });
|
||||
if (me) { const mine = store.saveOf(x.id, me); out.mySave = mine ? { refId: mine.refId, track: mine.track !== false, ls: lstrack.state(mine, x) } : null; }
|
||||
shown.push({ id: x.id, slot: 'packet' }); used.add(x.id);
|
||||
}
|
||||
if (kind === 'member') {
|
||||
const name = String(u.searchParams.get('u') || ''); const m = NAME_RE.test(name) ? store.memberByName(name) : null;
|
||||
const h = m ? null : NAME_RE.test(name) ? await hubpeople.byRef(name.toLowerCase()).catch(() => ({ ok: false })) : { ok: false };
|
||||
if (!m && !(h && h.ok && h.person)) return json(res, 404, { error: 'No network member by that name.' });
|
||||
const list = m ? store.savesBy(m.address).filter(v => v.refId).map(v => store.packet(v.packetId)).filter(seedbed.shown) : [];
|
||||
const planted = m ? store.packetsOf(m.address).filter(seedbed.shown) : [];
|
||||
const ids = new Set(); const all = planted.concat(list).filter(x => (ids.has(x.id) ? false : ids.add(x.id)));
|
||||
out.member = { username: m ? m.username : String(h.person.username || name), packets: all.map(x => Object.assign(packetPublic(x, me), { planted: !!(m && x.owner === m.address) })) };
|
||||
all.forEach(x => { shown.push({ id: x.id, slot: 'member' }); used.add(x.id); });
|
||||
out.joinUrl = joinUrl(out.member.username);
|
||||
}
|
||||
// the Spotlight places (top row of the bed; the strip on packet and member pages)
|
||||
const spots = wire.pickSpots(C.spotlight.row, kind === 'front' ? null : used, seedbed.shown);
|
||||
out.spotlights = spots.map(x => packetPublic(x, me)); spots.forEach(x => shown.push({ id: x.id, slot: 'spot' }));
|
||||
const hunt = u.searchParams.get('hunt') === '1' || srcHost(u.searchParams.get('src')) === 'polhunter.com';
|
||||
out.ticket = hunt ? null : issueTicket(req, kind, shown, u.searchParams.get('src'));
|
||||
if (hunt) { out.hunt = true; store.bump('huntVisits'); }
|
||||
out.seconds = C.visitSeconds;
|
||||
return json(res, 200, out);
|
||||
}
|
||||
if (p === '/api/visit/seen' && req.method === 'POST') {
|
||||
const b = await readBody(req); const t = tickets.get(String(b.ticket || ''));
|
||||
if (!t || isBot(req) || t.vk !== visitorKey(req)) return json(res, 200, { verified: false, why: 'ticket' });
|
||||
const age = Date.now() - t.at;
|
||||
if (age < C.visitSeconds * 1000 - 300 || Number(b.visibleMs) < C.visitSeconds * 1000 - 300) return json(res, 200, { verified: false, why: 'early' });
|
||||
tickets.delete(String(b.ticket));
|
||||
if (age > 1800000) return json(res, 200, { verified: false, why: 'ticket' });
|
||||
const r = wire.verify(t);
|
||||
return json(res, 200, Object.assign(r, r.verified ? { vt: wire.vtoken(t.vk) } : {}));
|
||||
}
|
||||
// the packets in the bed, no visit ticket (pickers that do not show the packets, e.g. the Spotlight page: views are never counted here)
|
||||
if (p === '/api/packets' && req.method === 'GET') return json(res, 200, { items: store.packets().filter(seedbed.shown).map(x => ({ id: x.id, no: String(x.id).padStart(3, '0'), name: x.name })) }, { 'Cache-Control': 'public, max-age=30' });
|
||||
if (p === '/api/transplanted' && req.method === 'GET') {
|
||||
const list = store.packets().filter(x => x.stage === 'approved' && x.status !== 'removed').sort((a, b) => (b.decidedAt || 0) - (a.decidedAt || 0)).slice(0, 100);
|
||||
const review = store.packets().filter(x => x.stage === 'review' && seedbed.shown(x)).length;
|
||||
return json(res, 200, { items: list.map(x => seedbed.card(x, { approvedAt: x.decidedAt || null })), inReview: review }, { 'Cache-Control': 'public, max-age=30' });
|
||||
}
|
||||
// DownlineHydra's "New in the network" slot (hook, not wired on DownlineHydra yet): the packets with a Spotlight still delivering
|
||||
if (p === '/api/spotlight-feed' && req.method === 'GET') {
|
||||
const items = wire.pickSpots(6, null, seedbed.shown).map(x => ({ id: x.id, name: x.name, desc: x.desc, host: x.host, url: 'https://' + C.site + '/p/' + x.id }));
|
||||
return json(res, 200, { site: C.site, items }, { 'Cache-Control': 'public, max-age=60', 'Access-Control-Allow-Origin': '*' });
|
||||
}
|
||||
if (p === '/api/ledger' && req.method === 'GET') return json(res, 200, proof.ledger(u.searchParams.get('n')), { 'Cache-Control': 'public, max-age=10' });
|
||||
if (p === '/api/contract' && req.method === 'GET') { if (limited(req, 'contract', 600, 3600000)) return json(res, 429, { error: 'Too many requests' }); return json(res, 200, await proof.contract(), { 'Cache-Control': 'public, max-age=60' }); }
|
||||
if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res);
|
||||
if (p === '/api/network-deals' && req.method === 'GET') return netdeals.handle(req, res, 'yourprogrambuilder');
|
||||
if (p === '/api/recent' && req.method === 'GET') {
|
||||
const cut = Date.now() - 30 * 60000;
|
||||
const planted = store.packets().filter(x => x.createdAt > cut && seedbed.shown(x)).slice(-6).map(x => ({ kind: 'plant', key: 'p' + x.id, at: x.createdAt, name: x.ownerName || null, packet: x.name, id: x.id }));
|
||||
const saves = store.saves().filter(s => s.at > cut && s.refId).slice(-6).map(s => { const x = store.packet(s.packetId); return x && seedbed.shown(x) ? { kind: 'save', key: 's' + s.id + s.at, at: s.at, name: uname(s.owner), packet: x.name, id: x.id } : null; }).filter(Boolean);
|
||||
const grown = store.packets().filter(x => x.reviewAt && x.reviewAt > cut && seedbed.shown(x)).map(x => ({ kind: 'review', key: 'g' + x.id, at: x.reviewAt, packet: x.name, id: x.id }));
|
||||
const spots = proof.ledger(10).items.filter(x => x.at && x.at > cut).map(x => ({ kind: 'spotlight', key: 'b' + x.tx + x.orderId, at: x.at, name: x.buyerName, packet: x.packet ? x.packet.name : null }));
|
||||
return json(res, 200, { items: planted.concat(saves, grown, spots).sort((a, b) => b.at - a.at) }, { 'Cache-Control': 'public, max-age=10' });
|
||||
}
|
||||
if (p === '/api/quote' && req.method === 'GET') {
|
||||
if (!shop.watching()) return json(res, 503, { error: 'Spotlights are not on sale yet.' });
|
||||
if (limited(req, 'quote', 600, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
|
||||
const qty = Number(u.searchParams.get('qty') || 1);
|
||||
if (!Number.isInteger(qty) || qty < 1 || qty > C.spotlight.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.spotlight.maxQty + ' Spotlights.' });
|
||||
try { return json(res, 200, Object.assign({ usd: C.spotlight.usd * qty, views: C.spotlight.views * qty }, await shop.quote(C.spotlight.sku, qty))); } catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
|
||||
}
|
||||
if (p === '/api/gas' && req.method === 'GET') { try { return json(res, 200, shop.watching() ? await shop.fees() : {}); } catch (e) { return json(res, 200, {}); } }
|
||||
if (/^\/api\/tx\/0x[0-9a-fA-F]{64}$/.test(p) && req.method === 'GET') {
|
||||
if (!shop.watching() || limited(req, 'tx', 1200, 3600000)) return json(res, 200, { found: false });
|
||||
try { return json(res, 200, await shop.receipt(p.slice(8))); } catch (e) { return json(res, 200, { found: false }); }
|
||||
}
|
||||
|
||||
// wallet sign-in
|
||||
if (p === '/api/auth/challenge' && req.method === 'POST') {
|
||||
if (limited(req, 'auth', 30, 600000)) return json(res, 429, { error: 'Too many sign-in attempts. Wait a few minutes.' });
|
||||
const b = await readBody(req); if (!ADDR_RE.test(b.address || '')) return json(res, 400, { error: 'Bad address' });
|
||||
const a = b.address.toLowerCase(); const nonce = crypto.randomBytes(16).toString('hex');
|
||||
const message = C.site + ' wants you to sign in with your wallet:\n' + getAddress(a) + '\n\nYourProgramBuilder sign-in. This signature is free and cannot move funds or approve anything.\n\nChain ID: ' + C.chainId + '\nNonce: ' + nonce + '\nIssued At: ' + new Date().toISOString();
|
||||
challenges.set(a, { message, exp: Date.now() + 600000 }); if (challenges.size > 20000) challenges.clear();
|
||||
return json(res, 200, { message });
|
||||
}
|
||||
if (p === '/api/auth/verify' && req.method === 'POST') {
|
||||
const b = await readBody(req); const a = String(b.address || '').toLowerCase(); const ch = challenges.get(a);
|
||||
if (!ch || ch.exp < Date.now()) return json(res, 400, { error: 'Sign-in request expired. Tap sign in again.' });
|
||||
let rec; try { rec = verifyMessage(ch.message, String(b.signature || '')).toLowerCase(); } catch (e) { return json(res, 400, { error: 'Invalid signature.' }); }
|
||||
if (rec !== a) return json(res, 400, { error: 'Your wallet signed with a different account (' + rec.slice(0, 6) + '...' + rec.slice(-4) + '). Switch accounts and try again.' });
|
||||
challenges.delete(a);
|
||||
store.upsertMember(a, store.member(a) ? {} : { via: 'wallet' });
|
||||
await verifyNet(a).catch(() => {});
|
||||
return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('ypb.sid', store.mintSession(a), store.SESSION_TTL / 1000, true) });
|
||||
}
|
||||
if (p === '/api/auth/logout' && req.method === 'POST') {
|
||||
const s = session(req); if (s) store.dropSession(s.token);
|
||||
return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('ypb.sid', '', 0, true), networksso.offCookie()] });
|
||||
}
|
||||
if (p === '/api/auth/logout-everywhere' && req.method === 'POST') {
|
||||
const s = session(req); let hub = { ok: false };
|
||||
if (s) { hub = await networksso.signOutEverywhere(s); store.endSessions(x => x.address === s.address, Date.now() + 1000); }
|
||||
return json(res, 200, { ok: true, everywhere: !!hub.ok }, { 'Set-Cookie': [cookie('ypb.sid', '', 0, true), networksso.offCookie()] });
|
||||
}
|
||||
if (p === '/api/hub/events' && req.method === 'POST') {
|
||||
let raw = ''; try { raw = (await readRaw(req, 256 * 1024)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
|
||||
const r = await hubevents.receive(req.headers, raw); return json(res, r.status, r.body);
|
||||
}
|
||||
if (p === '/api/me' && req.method === 'GET') {
|
||||
const s = session(req); if (!s) return json(res, 200, { signedIn: false });
|
||||
const m = store.member(s.address);
|
||||
return json(res, 200, { signedIn: true, address: s.address, username: m ? m.username : null, netVerified: netVerified(m), test: !!(m && m.testMember) });
|
||||
}
|
||||
// the report button (signed-in network members): REPORT_HOLD distinct reports send the packet back to Marty's queue
|
||||
if (p === '/api/report' && req.method === 'POST') {
|
||||
const s = session(req); if (!s) return json(res, 401, { error: 'Sign in with your network account to report a packet.' });
|
||||
if (limited(req, 'report', 20, 3600000)) return json(res, 429, { error: 'Too many reports this hour.' });
|
||||
const m = store.member(s.address); if (!netVerified(m)) return json(res, 403, { error: 'Reports are for network members.' });
|
||||
const b = await readBody(req); const x = store.packet(Number(b.packetId)); if (!x || x.status === 'removed') return json(res, 404, { error: 'Not found' });
|
||||
const reason = ['broken', 'scam', 'wrong', 'other'].includes(b.reason) ? b.reason : 'other';
|
||||
if (x.owner === s.address) return json(res, 400, { error: 'This is your own packet. Edit it on My packets instead.' });
|
||||
if (store.reports().some(r => r.packetId === x.id && r.by === s.address && !r.closed)) return json(res, 200, { ok: true, already: true });
|
||||
store.addReport({ packetId: x.id, by: s.address, reason, note: cleanText(b.note, 200) });
|
||||
x.reportsOpen = store.reports().filter(r => r.packetId === x.id && !r.closed).length;
|
||||
if (x.reportsOpen >= C.reportHold && x.status === 'live') { x.status = 'held'; x.heldWhy = 'reported'; x.reportsCleared = false; }
|
||||
store.savePacket(x); return json(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
// -- member API
|
||||
if (p.startsWith('/api/my')) {
|
||||
const s = session(req); if (!s) return json(res, 401, { error: 'Sign in first.' });
|
||||
const me = s.address; if (!store.member(me)) store.upsertMember(me, { via: 'wallet' });
|
||||
if (p === '/api/my' && req.method === 'GET') {
|
||||
await verifyNet(me).catch(() => {}); const m = store.member(me);
|
||||
const mine = store.packetsOf(me).filter(x => x.status !== 'dormant').map(x => Object.assign(seedbed.card(x), { status: x.status, check: x.check || null, heldWhy: x.heldWhy || null, url: x.url, ownerId: x.ownerId, views: x.views || 0, clicks: x.vclicks || 0,
|
||||
reportsOpen: x.reportsOpen || 0, spotlight: wire.spotProgress(x.id), decidedNote: x.stage === 'rejected' ? x.decidedNote || null : null }));
|
||||
const dormant = m.hubId ? store.packets().filter(x => x.status === 'dormant' && x.old && x.old.hubId === m.hubId).map(x => ({ id: x.id, name: x.name, url: x.old.url, added: x.old.added })) : [];
|
||||
const saved = store.savesBy(me).filter(v => v.refId).map(v => { const x = store.packet(v.packetId); return x ? { packetId: x.id, name: x.name, refId: v.refId, link: seedbed.fill(x, v.refId), shown: seedbed.shown(x), stage: x.stage || 'sprouting', saves: x.sprouts || 0, clicks: v.clicks || 0, track: v.track !== false, ls: lstrack.state(v, x) } : null; }).filter(Boolean);
|
||||
let lsClicks = null; if (lstrack.on() && m.username) lsClicks = await lstrack.clicks(m.username).catch(() => null);
|
||||
return json(res, 200, { address: me, username: m.username, netVerified: netVerified(m), test: !!m.testMember, hubId: m.hubId || null, quota: C.plantQuota, packets: mine, dormant, saved, lsClicks,
|
||||
spotlights: wire.purchases().filter(b => b.buyer === me).sort((x, y) => (y.at || 0) - (x.at || 0)).map(wire.spotView), earned: myEarned(me), joinUrl: joinUrl(''), page: m.username ? 'https://' + C.site + '/' + m.username : null });
|
||||
}
|
||||
if (p === '/api/my/plant' && req.method === 'POST') {
|
||||
if (limited(req, 'plant', 20, 3600000)) return json(res, 429, { error: 'Too many changes this hour.' });
|
||||
await verifyNet(me).catch(() => {}); const m = store.member(me);
|
||||
if (!netVerified(m)) return json(res, 403, { error: 'Planting is free for network members. Join InstantAdPay or LinkSpin free, then sign in here with that account.', join: joinUrl('') });
|
||||
const b = await readBody(req);
|
||||
const v = seedbed.validatePlant(b); if (v.error) return json(res, 400, v);
|
||||
const cur = b.id ? store.packet(Number(b.id)) : null;
|
||||
if (b.id && (!cur || cur.owner !== me || cur.status === 'removed')) return json(res, 404, { error: 'That packet is not yours.' });
|
||||
const dorm = b.dormant ? store.packet(Number(b.dormant)) : null;
|
||||
if (b.dormant && !(dorm && dorm.status === 'dormant' && dorm.old && m.hubId && dorm.old.hubId === m.hubId)) return json(res, 404, { error: 'That old program is not yours to confirm.' });
|
||||
if (!cur && !dorm && store.packetsOf(me).filter(x => x.status !== 'dormant').length >= C.plantQuota) return json(res, 400, { error: 'You have ' + C.plantQuota + ' packet planted, the most for one member. Remove it on My packets to plant a different one.' });
|
||||
// one packet per program: the same link base (host + path before {id}) planted by someone else -> save your ID there instead
|
||||
const stem = x => String(x.url).split('{id}')[0].toLowerCase().replace(/^https?:\/\/(www\.)?/, '');
|
||||
const twin = store.packets().find(x => x !== cur && x !== dorm && !['removed', 'dormant'].includes(x.status) && x.url && stem(x) === stem(v.fields));
|
||||
if (twin) return json(res, 409, { error: 'That program is already in the Seed Bed as packet No. ' + String(twin.id).padStart(3, '0') + '. Save your ID there instead.', packet: twin.id });
|
||||
const pr = C.linkProbe ? await linkcheck.probe(v.fields.url).catch(() => ({ ok: false, why: 'check failed' })) : { skipped: true };
|
||||
const vd = linkcheck.verdict(v.flags, pr, null);
|
||||
if (vd.state === 'red') return json(res, 400, { error: 'The link check could not load your link (' + vd.why.filter(w => /^link /.test(w)).map(w => w.slice(5)).join(', ') + '). Check it opens in your browser, then try again.', check: vd });
|
||||
let x = cur || dorm;
|
||||
if (x) { const wasText = seedbed.textHash(x); Object.assign(x, v.fields, { owner: me, ownerName: m.username || null, flags: v.flags }); if (x.status === 'dormant') { x.status = 'live'; x.confirmedAt = Date.now(); x.createdAt = Date.now(); x.stage = 'sprouting'; } if (seedbed.textHash(x) !== wasText) delete x.yellowOk; }
|
||||
else { x = store.addPacket(Object.assign({ owner: me, ownerName: m.username || null, status: 'live', stage: 'sprouting', flags: v.flags, views: 0, clicks: 0, vclicks: 0 }, v.fields)); store.bump('planted'); }
|
||||
x.check = Object.assign({ at: Date.now() }, vd);
|
||||
x.status = vd.state === 'green' || (vd.state === 'yellow' && x.yellowOk === seedbed.textHash(x)) ? 'live' : 'held'; if (x.status === 'held') x.heldWhy = 'link check';
|
||||
seedbed.grow(x);
|
||||
return json(res, 200, { ok: true, packet: { id: x.id, status: x.status, check: vd.state, why: vd.why }, created: !cur && !dorm });
|
||||
}
|
||||
if (p === '/api/my/packet/remove' && req.method === 'POST') {
|
||||
const b = await readBody(req); const x = store.packet(Number(b.id)); if (!x || x.owner !== me || x.status === 'removed') return json(res, 404, { error: 'Not found' });
|
||||
if (x.stage === 'approved') return json(res, 400, { error: 'This packet was transplanted into the builder. Ask network support to change it there.' });
|
||||
x.status = 'removed'; x.removedBy = 'owner'; store.savePacket(x); return json(res, 200, { ok: true });
|
||||
}
|
||||
if (p === '/api/my/save' && req.method === 'POST') {
|
||||
if (limited(req, 'save', 120, 3600000)) return json(res, 429, { error: 'Too many saves this hour.' });
|
||||
await verifyNet(me).catch(() => {}); const m = store.member(me);
|
||||
if (!netVerified(m)) return json(res, 403, { error: 'Saving your ID is free for network members. Sign in with your network account first.', join: joinUrl('') });
|
||||
const b = await readBody(req); const x = store.packet(Number(b.packetId)); if (!x || !seedbed.shown(x)) return json(res, 404, { error: 'That packet is not in the Seed Bed right now.' });
|
||||
if (x.owner === me) return json(res, 400, { error: 'This is your packet: your ID is the planter\'s ID. Change it on My packets.' });
|
||||
const id = seedbed.cleanId(x, b.refId);
|
||||
if (id === null) return json(res, 400, { error: 'That does not look like a referral ID for this program. Type only your ID, or paste your whole referral link for it.' });
|
||||
if (id === '') { store.dropSave(x.id, me); seedbed.grow(x); return json(res, 200, { ok: true, removed: true, saves: x.sprouts }); }
|
||||
const had = store.saveOf(x.id, me);
|
||||
const sv = store.putSave(x.id, me, { refId: id, username: m.username || null, hubId: m.hubId || null, track: b.track === undefined ? (had ? had.track !== false : true) : b.track !== false });
|
||||
if (!had) store.bump('saves');
|
||||
const g = seedbed.grow(x);
|
||||
if (lstrack.on()) lstrack.ensureSave(sv).catch(() => {});
|
||||
return json(res, 200, { ok: true, refId: id, link: seedbed.fill(x, id), saves: g.n, review: g.review, need: C.reviewSaves });
|
||||
}
|
||||
if (p === '/api/my/order' && req.method === 'POST') {
|
||||
if (!shop.watching() || !shop.signerOn()) return json(res, 503, { error: 'Spotlights are not on sale yet.' });
|
||||
if (limited(req, 'order', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
|
||||
const b = await readBody(req); const qty = Number(b.qty || 1);
|
||||
if (!Number.isInteger(qty) || qty < 1 || qty > C.spotlight.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.spotlight.maxQty + ' Spotlights.' });
|
||||
const x = store.packet(Number(b.packetId)); if (!x || !seedbed.shown(x)) return json(res, 400, { error: 'Pick a packet that is in the Seed Bed.' });
|
||||
const lo = await hubline.lineOf({ wallet: me }, shop.MAX_LINE);
|
||||
if (!lo.ok) return json(res, 503, { error: 'Your sponsor line could not be checked with the network just now. Try again in a minute, so your team gets paid.' });
|
||||
// eligibility (the ViralAdSource rule, Marty 2026-11-17): a network member (hub, not blocked) with a linked wallet earns a level,
|
||||
// Spotlight or not. Dropping the ineligible here IS the compression; levels left when the line runs out go to the company
|
||||
const line = lo.line.filter(y => y.wallet && !y.blocked && y.wallet !== me).map(y => y.wallet);
|
||||
try { return json(res, 200, Object.assign({ buyer: me, usd: C.spotlight.usd * qty, views: C.spotlight.views * qty, qty, packetId: x.id }, await shop.order(me, C.spotlight.sku, qty, x.id, line))); }
|
||||
catch (e) { console.error('order failed:', String(e && e.message || e).slice(0, 200)); return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
|
||||
}
|
||||
if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); }
|
||||
// the AI writer (2026-11-17, through the hub): a name and a one-sentence description from the program's own page; nothing is saved
|
||||
if (p === '/api/my/adwriter' && req.method === 'POST') {
|
||||
if (!(await adwriter.enabled())) return json(res, 503, { error: 'The writer is switched off right now. You can still write it yourself.' });
|
||||
if (limited(req, 'adwriter', 12, 3600000)) return json(res, 429, { error: 'Too many writes from this connection this hour. Try again later, or write it yourself.' });
|
||||
const m = store.member(me); await verifyNet(me).catch(() => {});
|
||||
if (!netVerified(m)) return json(res, 403, { error: 'The writer is for network members. Sign in with your network account first.' });
|
||||
const b = await readBody(req); const url = String(b.url || '').trim().replace(/\{id\}/g, 'x').slice(0, 600);
|
||||
const r = await adwriter.write(me, url, { headline: C.packet.name, line: C.packet.desc });
|
||||
if (r.error) return json(res, r.status || 400, { error: r.error, code: r.code, left: r.left });
|
||||
return json(res, 200, { ok: true, options: r.options, url: r.url, cached: r.cached, left: r.left });
|
||||
}
|
||||
return json(res, 404, { error: 'Not found' });
|
||||
}
|
||||
|
||||
// -- admin (x-admin-token: ADMIN_TOKEN)
|
||||
if (p.startsWith('/api/admin/')) {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'no' });
|
||||
if (p === '/api/admin/status' && req.method === 'GET') {
|
||||
const S = store.state(); const P = store.packets();
|
||||
const count = f => P.filter(f).length;
|
||||
return json(res, 200, { day: store.ctDay(), week: store.ctWeek(), staging: C.staging, testSwitch: TEST_SWITCH, config: { reviewSaves: C.reviewSaves, plantQuota: C.plantQuota, spotlight: C.spotlight, split: C.split, hubJoin: C.hubJoin, payouts: C.payouts, linkProbe: C.linkProbe },
|
||||
today: store.today(), totals: S.totals, members: store.members().length,
|
||||
packets: { all: P.length, shown: count(seedbed.shown), held: count(x => x.status === 'held'), dormant: count(x => x.status === 'dormant'), review: count(x => x.stage === 'review' && x.status !== 'removed'), approved: count(x => x.stage === 'approved'), removed: count(x => x.status === 'removed') },
|
||||
saves: store.saves().filter(v => v.refId).length, reportsOpen: store.reports().filter(r => !r.closed).length,
|
||||
shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), hubEvents: hubevents.view(), sso: { hub: networksso.hubOn(), pairwise: networksso.enabled() },
|
||||
linkspin: lstrack.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length, adWriter: await adwriter.status() });
|
||||
}
|
||||
// Marty's queue: held packets (yellow / red link, reported) and packets that reached the review threshold
|
||||
if (p === '/api/admin/queue' && req.method === 'GET') {
|
||||
const row = x => Object.assign(seedbed.card(x), { status: x.status, url: x.url, ownerId: x.ownerId, owner: x.owner, check: x.check || null, flags: x.flags || [], heldWhy: x.heldWhy || null,
|
||||
reports: store.reports().filter(r => r.packetId === x.id && !r.closed).map(r => ({ id: r.id, reason: r.reason, note: r.note, by: uname(r.by) || r.by, at: r.at })), reviewAt: x.reviewAt || null, manualHold: !!x.manualHold });
|
||||
const P = store.packets();
|
||||
return json(res, 200, { held: P.filter(x => x.status === 'held').map(row), review: P.filter(x => x.stage === 'review' && x.status !== 'removed').sort((a, b) => (a.reviewAt || 0) - (b.reviewAt || 0)).map(row),
|
||||
approved: P.filter(x => x.stage === 'approved').map(row).slice(0, 100), live: P.filter(seedbed.shown).length });
|
||||
}
|
||||
if (p === '/api/admin/packet' && req.method === 'POST') {
|
||||
const b = await readBody(req); const x = store.packet(Number(b.id)); if (!x) return json(res, 404, { error: 'not found' });
|
||||
const note = cleanText(b.note, 300); const a = String(b.action || '');
|
||||
if (a === 'show') { x.yellowOk = seedbed.textHash(x); x.manualHold = false; x.reportsCleared = true; x.status = x.check && x.check.state === 'red' ? 'held' : 'live'; delete x.heldWhy; for (const r of store.reports()) if (r.packetId === x.id && !r.closed) { r.closed = Date.now(); store.saveReport(r); } x.reportsOpen = 0; }
|
||||
else if (a === 'hold') { x.status = 'held'; x.manualHold = true; x.heldWhy = note || 'held by Marty'; }
|
||||
else if (a === 'remove') { x.status = 'removed'; x.removedBy = 'admin'; x.note = note; }
|
||||
else if (a === 'restore') { x.status = 'held'; x.manualHold = false; }
|
||||
else if (a === 'recheck') { x.manualHold = false; await checkPacket(x); }
|
||||
else if (a === 'approve') { if (x.stage !== 'review') return json(res, 400, { error: 'Only a packet in review can be approved.' }); x.stage = 'approved'; x.decidedAt = Date.now(); x.decidedNote = note; }
|
||||
else if (a === 'reject') { if (x.stage !== 'review') return json(res, 400, { error: 'Only a packet in review can be rejected.' }); x.stage = 'rejected'; x.decidedAt = Date.now(); x.decidedNote = note; }
|
||||
else if (a === 'reopen') { x.stage = 'sprouting'; delete x.decidedAt; seedbed.grow(x); }
|
||||
else return json(res, 400, { error: 'action show | hold | remove | restore | recheck | approve | reject | reopen' });
|
||||
store.savePacket(x); return json(res, 200, { ok: true, packet: { id: x.id, status: x.status, stage: x.stage, check: x.check ? x.check.state : null } });
|
||||
}
|
||||
// approved packets for the CTB builder / DownlineHydra wild heads, every saved ID carried. mark=1 stamps exportedAt (the
|
||||
// add on CTB / DownlineHydra is done there: this site never writes to another site)
|
||||
if (p === '/api/admin/export' && req.method === 'GET') {
|
||||
const all = u.searchParams.get('all') === '1';
|
||||
const list = store.packets().filter(x => x.stage === 'approved' && (all || !x.exportedAt));
|
||||
if (u.searchParams.get('mark') === '1') for (const x of list) { x.exportedAt = Date.now(); store.savePacket(x); }
|
||||
return json(res, 200, { v: 1, site: C.site, exportedAt: Date.now(), format: 'ctb-builder', placeholder: '{affiliateid}', packets: list.map(seedbed.exportPacket) });
|
||||
}
|
||||
if (p === '/api/admin/recheck' && req.method === 'POST') return json(res, 200, { checked: await recheckSweep(Number((await readBody(req)).max) || 50) });
|
||||
if (p === '/api/admin/test-member' && req.method === 'POST') {
|
||||
if (!TEST_SWITCH) return json(res, 403, { error: 'The test switch exists on staging only.' });
|
||||
const b = await readBody(req); if (!ADDR_RE.test(b.address || '') || (b.username && !NAME_RE.test(b.username))) return json(res, 400, { error: 'address (+ username)' });
|
||||
const a = b.address.toLowerCase(); const other = b.username ? store.memberByName(b.username) : null;
|
||||
if (other && other.address !== a) return json(res, 409, { error: 'username taken here' });
|
||||
const mm = store.upsertMember(a, { netOk: b.on !== false, netBy: 'test', netAt: Date.now() + 365 * 86400000, testMember: b.on !== false, hubId: b.hubId || (store.member(a) || {}).hubId || 'h_test' + crypto.createHash('sha256').update(a).digest('hex').slice(0, 10), username: b.username || (store.member(a) || {}).username || null });
|
||||
return json(res, 200, { ok: true, member: mm });
|
||||
}
|
||||
if (p === '/api/admin/oldrefs' && req.method === 'POST') {
|
||||
let b; try { b = JSON.parse((await readRaw(req, 4 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); }
|
||||
if (!b || !b.oldrefs || typeof b.oldrefs !== 'object') return json(res, 400, { error: 'oldrefs object required' });
|
||||
const o = {}; for (const [k, v] of Object.entries(b.oldrefs)) if (/^[a-z0-9_.-]{2,40}$/.test(k) && NAME_RE.test(String(v))) o[k] = String(v);
|
||||
fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} };
|
||||
return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length });
|
||||
}
|
||||
// old YourProgramBuilder member programs as dormant packets (myheads.csv from the reconcile): {packets: [{oldId, oldUsername, hubId,
|
||||
// name, url, added}]}. Only people the hub knows (hubId). Nothing shows until the owner confirms it with a {id} link on My packets.
|
||||
if (p === '/api/admin/dormant' && req.method === 'POST') {
|
||||
let b; try { b = JSON.parse((await readRaw(req, 2 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); }
|
||||
const list = Array.isArray(b && b.packets) ? b.packets : null; if (!list) return json(res, 400, { error: 'packets array required' });
|
||||
let created = 0, skipped = 0;
|
||||
for (const r of list) {
|
||||
const oldId = String(r.oldId || ''); const hubId = String(r.hubId || '');
|
||||
if (!/^\d{1,9}$/.test(oldId) || !/^h_[0-9a-f]{16}$/.test(hubId) || store.packets().some(x => x.old && x.old.oldId === oldId)) { skipped++; continue; }
|
||||
const name = cleanText(r.name, C.packet.name).slice(0, C.packet.name); const url = String(r.url || '').trim().slice(0, 500);
|
||||
if (name.length < 2 || !/^https?:\/\//i.test(url)) { skipped++; continue; }
|
||||
store.addPacket({ owner: '', ownerName: null, status: 'dormant', stage: 'sprouting', name, url: '', desc: '', old: { oldId, oldUsername: String(r.oldUsername || '').slice(0, 40), hubId, url, added: String(r.added || '').slice(0, 10) } }); created++;
|
||||
}
|
||||
return json(res, 200, { ok: true, created, skipped, dry: !!b.dry });
|
||||
}
|
||||
if (p === '/api/admin/member-lookup' && req.method === 'GET') {
|
||||
const q = String(u.searchParams.get('q') || '').trim(); let a = null;
|
||||
if (ADDR_RE.test(q)) a = q.toLowerCase(); else if (NAME_RE.test(q)) { const m = store.memberByName(q); a = m ? m.address : null; }
|
||||
if (!a) return json(res, 404, { error: 'not found' });
|
||||
return json(res, 200, { address: a, record: store.member(a), packets: store.packetsOf(a).map(x => seedbed.card(x, { status: x.status })), saves: store.savesBy(a).length, earned: myEarned(a) });
|
||||
}
|
||||
return json(res, 404, { error: 'Not found' });
|
||||
}
|
||||
|
||||
if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });
|
||||
res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' }));
|
||||
return res.end('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not found | YourProgramBuilder</title><body style="background:#F6FAF1;color:#12291F;font-family:\'Atkinson Hyperlegible\',system-ui,sans-serif;text-align:center;padding:40px 16px"><p style="font-size:22px;font-weight:700">Nothing has sprouted here.</p><p><a style="color:#C24A08;font-weight:700" href="/">Back to the Seed Bed</a></p>' + (lsZones().notFound ? '<p style="font-size:11px;margin:24px 0 4px;opacity:.7">Network</p><script async src="https://linkspin.app/z.js" data-zone="' + lsZones().notFound + '"></script>' : '') + '</body>');
|
||||
} catch (e) {
|
||||
console.error('request', p, e.message);
|
||||
if (!res.headersSent) json(res, 500, { error: 'Server error' });
|
||||
}
|
||||
});
|
||||
|
||||
(async () => {
|
||||
await docstore.init({ splits: store.SPLITS });
|
||||
process.on('SIGTERM', () => { store.flush(); docstore.drain(8000).finally(() => process.exit(0)); });
|
||||
store.load();
|
||||
wire.init();
|
||||
store.prune(); wire.rebuild();
|
||||
hubreport.init({ dataDir: C.dataDir, purchases: () => wire.purchases().map(x => ({ key: x.key, buyer: x.buyer, sponsor: null, usdCents: x.usdCents, block: x.block, at: x.at })) });
|
||||
proof.init(C, { shop, wire });
|
||||
shop.setAttach(rec => { wire.attach(rec); store.bump('spotlights', Number(rec.qty) || 1); });
|
||||
shop.setHook(proof.onPurchase);
|
||||
shop.init(C);
|
||||
setInterval(() => { if (store.prune()) wire.rebuild(); }, 3600000).unref();
|
||||
chatbot.init();
|
||||
lstrack.init(C, store, seedbed);
|
||||
{ let busy = false; const tick = () => { if (busy) return; busy = true; Promise.all([lstrack.sweep(25), recheckSweep(20)]).catch(() => {}).finally(() => { busy = false; }); };
|
||||
setTimeout(tick, Number(process.env.SWEEP_FIRST_MS || 30000)).unref(); setInterval(tick, Number(process.env.SWEEP_MS || 300000)).unref(); }
|
||||
server.listen(C.port, () => console.log('YourProgramBuilder on :' + C.port + (C.staging ? ' (staging)' : '') + ', review at ' + C.reviewSaves + ' saves, store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)')));
|
||||
})().catch(e => { console.error('start failed:', e.message); process.exit(1); });
|
||||
process.on('SIGINT', () => { store.flush(); process.exit(0); });
|
||||
@@ -0,0 +1,178 @@
|
||||
// On-chain side (YPBShop, ../contracts; NOT deployed: staging runs with no CONTRACT_ADDRESS, so every job here is inert).
|
||||
// (a) orders: KEEPER_KEY (the keeper the contract trusts) signs EIP-712 Order(buyer, sku, qty, ref, line[], nonce, deadline).
|
||||
// line = the buyer's network sponsor line from the hub (wallets, nearest first, up to 20). ref = the packet id. The contract
|
||||
// pays places 1..5 of the line (20% / 5% / 5% / 5% / 5%, DEFAULT split) and the company the rest, in the same transaction.
|
||||
// Nobody needs a Spotlight to earn. Compression happens in server.js (/api/my/order): only network members with a linked
|
||||
// wallet go in the line, so a level passes up to the next eligible person; levels left when the line runs out go to the company.
|
||||
// (b) watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase logs (confirmed blocks only) and records each once per
|
||||
// txHash:logIndex. The split of each order is read from its receipt (Paid / PaymentFailed).
|
||||
// No key ever enters config or any API answer.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const { Wallet, Interface, getAddress } = require('ethers');
|
||||
const store = require('./store');
|
||||
|
||||
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
|
||||
const ZERO = '0x0000000000000000000000000000000000000000';
|
||||
const IFACE = new Interface([
|
||||
'event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 views, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, uint256 companyPaid)',
|
||||
'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 kind, uint8 depth)',
|
||||
'event PaymentFailed(uint256 indexed orderId, address indexed to, uint256 amount, uint8 kind, uint8 depth)']);
|
||||
const TOPIC = IFACE.getEvent('Purchase').topicHash;
|
||||
const T = { paid: IFACE.getEvent('Paid').topicHash, fail: IFACE.getEvent('PaymentFailed').topicHash };
|
||||
const CALLS = new Interface(['function quoteWei(uint256 sku, uint256 qty) view returns (uint256)',
|
||||
'function buy(uint256 sku, uint256 qty, uint256 ref, address[] line, uint256 nonce, uint256 deadline, bytes sig) payable returns (uint256 orderId)',
|
||||
'function levelBps() view returns (uint16[])', 'function levelCount() view returns (uint8)', 'function purchases(address) view returns (uint256)',
|
||||
'function owner() view returns (address)', 'function company() view returns (address)', 'function keeper() view returns (address)', 'function paused() view returns (bool)',
|
||||
'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)', 'function SKU_DELAY() view returns (uint256)',
|
||||
'function skus(uint256) view returns (uint64 usdCents, uint64 views, bool active)', 'function pendingSku(uint256) view returns (uint64 usdCents, uint64 views, bool active, uint64 eta)']);
|
||||
const TYPES = {
|
||||
Order: [{ name: 'buyer', type: 'address' }, { name: 'sku', type: 'uint256' }, { name: 'qty', type: 'uint256' }, { name: 'ref', type: 'uint256' }, { name: 'line', type: 'address[]' },
|
||||
{ name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint256' }]
|
||||
};
|
||||
const MAX_LINE = 20;
|
||||
const st = { polls: 0, recorded: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null };
|
||||
let C = null, keeper = null, busy = false, timer = null;
|
||||
const hooks = { onPurchase: null, attach: null };
|
||||
function setHook(fn) { hooks.onPurchase = typeof fn === 'function' ? fn : null; }
|
||||
function setAttach(fn) { hooks.attach = typeof fn === 'function' ? fn : null; }
|
||||
const keyOf = k => { k = String(k || '').trim(); if (!k) return null; try { return new Wallet(k.startsWith('0x') ? k : '0x' + k); } catch (e) { return null; } };
|
||||
|
||||
function init(cfg) {
|
||||
C = cfg; keeper = keyOf(process.env.KEEPER_KEY);
|
||||
if (process.env.KEEPER_KEY && !keeper) console.error('shop: KEEPER_KEY is not a valid private key; orders off');
|
||||
if (timer) { clearTimeout(timer); timer = null; }
|
||||
if (watching()) { console.log('shop: watching', C.contractAddress); tick(); }
|
||||
}
|
||||
const signerOn = () => !!(C && keeper && C.contractAddress);
|
||||
const watching = () => !!(C && C.contractAddress && C.chainRpc);
|
||||
const domain = () => ({ name: 'YPBShop', version: '1', chainId: C.chainId, verifyingContract: C.contractAddress });
|
||||
const nonce = () => BigInt('0x' + crypto.randomBytes(16).toString('hex'));
|
||||
function cleanLine(buyer, line) {
|
||||
const b = String(buyer).toLowerCase(); const seen = new Set([b]); const l = [];
|
||||
for (const w of line || []) { const x = String(w || '').toLowerCase(); if (!ADDR_RE.test(x) || x === ZERO || seen.has(x) || x === String(C.contractAddress).toLowerCase()) continue; seen.add(x); l.push(getAddress(x)); if (l.length >= MAX_LINE) break; }
|
||||
return l;
|
||||
}
|
||||
// the buy() call for `buyer`: a signed order carrying the sponsor line and the packet id
|
||||
async function order(buyer, sku, qty, ref, line) {
|
||||
if (!signerOn()) throw new Error('orders off');
|
||||
const b = getAddress(String(buyer).toLowerCase());
|
||||
const o = { buyer: b, sku: BigInt(sku), qty: BigInt(qty), ref: BigInt(ref || 0), line: cleanLine(b, line), nonce: nonce(), deadline: BigInt(Math.floor(Date.now() / 1000) + C.voucherSeconds) };
|
||||
const sig = await keeper.signTypedData(domain(), { Order: TYPES.Order }, o);
|
||||
const q = await quote(sku, qty);
|
||||
const data = CALLS.encodeFunctionData('buy', [o.sku, o.qty, o.ref, o.line, o.nonce, o.deadline, sig]);
|
||||
return { to: C.contractAddress, chainId: C.chainId, data, value: '0x' + BigInt(q.sendWei).toString(16), wei: q.wei, sendWei: q.sendWei, line: o.line.length };
|
||||
}
|
||||
|
||||
function apply(ev) {
|
||||
const S = store.state(); const P = S.purchases || (S.purchases = {});
|
||||
const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex;
|
||||
if (P[key]) { st.dupes++; return false; }
|
||||
const a = ev.buyer.toLowerCase(); if (!store.member(a)) store.upsertMember(a, { via: 'wallet' });
|
||||
const rec = { at: Date.now(), blockAt: ev.blockAt || null, block: ev.block, orderId: ev.orderId, buyer: a, sku: ev.sku, qty: ev.qty, ref: ev.ref, views: ev.views,
|
||||
usdCents: ev.usdCents, weiPaid: ev.weiPaid, levelsPaid: ev.levelsPaid, companyPaid: ev.companyPaid };
|
||||
if (hooks.attach) { try { hooks.attach(rec); } catch (e) {} }
|
||||
P[key] = rec; store.save(); st.recorded++;
|
||||
if (hooks.onPurchase) { try { hooks.onPurchase(rec, String(ev.txHash).toLowerCase()); } catch (e) {} }
|
||||
console.log('shop: Spotlight order', ev.orderId, 'x' + ev.qty, a, rec.packetId ? 'for packet #' + rec.packetId : '(packet ' + ev.ref + ' not found)');
|
||||
return true;
|
||||
}
|
||||
function decode(l) {
|
||||
if (!l || l.removed || String(l.address || '').toLowerCase() !== C.contractAddress.toLowerCase()) return null;
|
||||
if ((l.topics || [])[0] !== TOPIC) return null;
|
||||
const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args;
|
||||
return { txHash: l.transactionHash, logIndex: parseInt(l.logIndex, 16), block: parseInt(l.blockNumber, 16), orderId: Number(d.orderId), buyer: d.buyer, sku: Number(d.sku),
|
||||
qty: Number(d.qty), ref: d.ref.toString(), views: Number(d.views), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString(), levelsPaid: Number(d.levelsPaid), companyPaid: d.companyPaid.toString() };
|
||||
}
|
||||
// the split of one order from its receipt: kind 0 company, 1..5 sponsor levels (depth = place in the compressed line)
|
||||
async function readSplit(tx, orderId) {
|
||||
const r = await rpc('eth_getTransactionReceipt', [tx]); if (!r || !Array.isArray(r.logs)) return null;
|
||||
const pays = [];
|
||||
for (const l of r.logs) {
|
||||
if (String(l.address).toLowerCase() !== C.contractAddress.toLowerCase()) continue;
|
||||
const t0 = l.topics[0]; if (t0 !== T.paid && t0 !== T.fail) continue;
|
||||
const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; if (Number(d.orderId) !== Number(orderId)) continue;
|
||||
pays.push({ kind: Number(d.kind), depth: Number(d.depth), to: d.to.toLowerCase(), wei: d.amount.toString(), failed: t0 === T.fail || undefined });
|
||||
}
|
||||
return { pays };
|
||||
}
|
||||
|
||||
async function rpc(method, params) {
|
||||
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 10000); t.unref();
|
||||
try { const j = await (await fetch(C.chainRpc, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), signal: ac.signal })).json();
|
||||
if (j.error) throw new Error(method + ': ' + (j.error.message || JSON.stringify(j.error))); return j.result; } finally { clearTimeout(t); }
|
||||
}
|
||||
async function poll() {
|
||||
if (busy || !watching()) return; busy = true; st.polls++;
|
||||
try {
|
||||
const S = store.state(); const sh = S.shop || (S.shop = {});
|
||||
const head = parseInt(await rpc('eth_blockNumber', []), 16) - C.shopConfirmations; st.head = head;
|
||||
if (sh.lastBlock == null) { sh.lastBlock = (C.shopStartBlock || head + 1) - 1; store.save(); }
|
||||
while (sh.lastBlock < head) {
|
||||
const from = sh.lastBlock + 1, to = Math.min(head, from + 999);
|
||||
const logs = await rpc('eth_getLogs', [{ address: C.contractAddress, topics: [TOPIC], fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }]);
|
||||
for (const l of logs || []) {
|
||||
const ev = decode(l); if (!ev) { st.ignored++; continue; }
|
||||
if ((S.purchases || {})[String(ev.txHash).toLowerCase() + ':' + ev.logIndex]) { st.dupes++; continue; }
|
||||
ev.blockAt = await blockTime(ev.block);
|
||||
apply(ev);
|
||||
}
|
||||
sh.lastBlock = to; store.save();
|
||||
}
|
||||
} catch (e) { st.errors++; st.lastError = String(e.message).slice(0, 200); }
|
||||
finally { busy = false; }
|
||||
}
|
||||
const btCache = new Map();
|
||||
async function blockTime(n) {
|
||||
if (btCache.has(n)) return btCache.get(n);
|
||||
let t = null; try { const b = await rpc('eth_getBlockByNumber', ['0x' + n.toString(16), false]); t = b && b.timestamp ? parseInt(b.timestamp, 16) : null; } catch (e) {}
|
||||
if (t) { btCache.set(n, t); if (btCache.size > 5000) btCache.clear(); }
|
||||
return t;
|
||||
}
|
||||
function tick() { poll().finally(() => { if (watching()) { timer = setTimeout(tick, C.shopPollMs); timer.unref(); } }); }
|
||||
|
||||
async function call(fn, args) {
|
||||
const r = await rpc('eth_call', [{ to: C.contractAddress, data: CALLS.encodeFunctionData(fn, args || []) }, 'latest']);
|
||||
return CALLS.decodeFunctionResult(fn, r);
|
||||
}
|
||||
const qCache = new Map();
|
||||
async function quote(sku, qty) {
|
||||
const k = sku + 'x' + qty; const hit = qCache.get(k); if (hit && Date.now() - hit.at < 15000) return hit.v;
|
||||
const wei = (await call('quoteWei', [sku, qty]))[0];
|
||||
const v = { sku, qty, wei: wei.toString(), sendWei: (wei + wei / 100n).toString() };
|
||||
qCache.set(k, { at: Date.now(), v }); if (qCache.size > 200) qCache.clear();
|
||||
return v;
|
||||
}
|
||||
// the live split and SKU from the contract (cached 5 minutes); null when the chain is not set or does not answer
|
||||
let rules = null;
|
||||
async function liveRules(sku) {
|
||||
if (!watching()) return null;
|
||||
if (rules && Date.now() - rules.at < 300000) return rules.v;
|
||||
try {
|
||||
const [l, s, pend] = await Promise.all([call('levelBps').then(x => x[0]), call('skus', [sku || 1]), call('pendingSku', [sku || 1])]);
|
||||
const v = { levelBps: l.map(Number), sku: { usdCents: Number(s[0]), views: Number(s[1]), active: !!s[2] }, pending: Number(pend[3]) ? { usdCents: Number(pend[0]), views: Number(pend[1]), active: !!pend[2], eta: Number(pend[3]) } : null };
|
||||
rules = { at: Date.now(), v }; return v;
|
||||
} catch (e) { return rules ? rules.v : null; }
|
||||
}
|
||||
async function receipt(hash) {
|
||||
const r = await rpc('eth_getTransactionReceipt', [hash]);
|
||||
if (!r) return { found: false };
|
||||
return { found: true, status: r.status, blockNumber: r.blockNumber, to: r.to ? String(r.to).toLowerCase() : null, from: r.from ? String(r.from).toLowerCase() : null };
|
||||
}
|
||||
async function fees() {
|
||||
let tip = 0n, base = 0n;
|
||||
try { tip = BigInt(await rpc('eth_maxPriorityFeePerGas', [])); } catch (e) {}
|
||||
try { const blk = await rpc('eth_getBlockByNumber', ['latest', false]); base = BigInt((blk && blk.baseFeePerGas) || '0x0'); } catch (e) {}
|
||||
const MIN_TIP = C.chainId === 137 ? 30000000000n : 1000000000n;
|
||||
const priority = tip > MIN_TIP ? tip : MIN_TIP;
|
||||
return { maxPriorityFeePerGas: '0x' + priority.toString(16), maxFeePerGas: '0x' + (base * 2n + priority).toString(16) };
|
||||
}
|
||||
let lastNudge = 0;
|
||||
function nudge() { if (!watching() || Date.now() - lastNudge < 3000) return; lastNudge = Date.now(); poll().catch(() => {}); }
|
||||
|
||||
function view() {
|
||||
const list = Object.values((store.state() && store.state().purchases) || {});
|
||||
return Object.assign({ contract: C ? C.contractAddress || null : null, watching: watching(), orders: signerOn(), keeper: keeper ? keeper.address : null,
|
||||
lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, spotlights: list.reduce((t, x) => t + (Number(x.qty) || 1), 0), orderCount: list.length }, st);
|
||||
}
|
||||
module.exports = { setHook, setAttach, init, order, signerOn, watching, apply, poll, view, quote, liveRules, receipt, fees, nudge, call, rpc, readSplit, TOPIC, IFACE, TYPES, CALLS, MAX_LINE, ZERO };
|
||||
@@ -0,0 +1,149 @@
|
||||
// YourProgramBuilder data. One document (ypb.json) holds members, sessions, Spotlight purchases (the chain's Purchase events), the
|
||||
// watcher position, the ref tags of buyers and daily counters. The growing collections are row tables when the app runs on MySQL
|
||||
// (docstore splits): packets (planted programs), saved IDs, reports, verified visits, verified clicks and Spotlight views (the
|
||||
// delivery audit trail: one row per view counted). Without DOCSTORE_URL (local prototype + tests only) everything stays in the one
|
||||
// file, written atomically. Marty's rule (2026-11-13): MySQL is the standard; never launch on files.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const cfgMod = require('./config');
|
||||
const docstore = require('./docstore');
|
||||
|
||||
const DOC = 'ypb.json';
|
||||
const SPLITS = [
|
||||
{ doc: DOC, field: 'packets', table: 'ypb_packets', key: 'id', ts: 'createdAt' },
|
||||
{ doc: DOC, field: 'saves', table: 'ypb_saves', key: 'id', ts: 'at' },
|
||||
{ doc: DOC, field: 'reports', table: 'ypb_reports', key: 'id', ts: 'at' },
|
||||
{ doc: DOC, field: 'visits', table: 'ypb_visits', key: 'id', ts: 'at' },
|
||||
{ doc: DOC, field: 'clicks', table: 'ypb_clicks', key: 'id', ts: 'at' },
|
||||
{ doc: DOC, field: 'sviews', table: 'ypb_sviews', key: 'id', ts: 'at' }
|
||||
];
|
||||
const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s]));
|
||||
|
||||
let S = null, saveT = null, rowMode = false;
|
||||
const packetById = new Map(), saveById = new Map(), savesByPacket = new Map(), savesByOwner = new Map();
|
||||
const FILE = () => path.join(cfgMod.get().dataDir, DOC);
|
||||
const lc = v => String(v || '').toLowerCase();
|
||||
|
||||
function index() {
|
||||
packetById.clear(); saveById.clear(); savesByPacket.clear(); savesByOwner.clear();
|
||||
for (const p of S.packets) packetById.set(p.id, p);
|
||||
for (const s of S.saves) indexSave(s);
|
||||
}
|
||||
function indexSave(s) {
|
||||
saveById.set(s.id, s);
|
||||
let l = savesByPacket.get(s.packetId); if (!l) savesByPacket.set(s.packetId, l = []); if (!l.includes(s)) l.push(s);
|
||||
let o = savesByOwner.get(s.owner); if (!o) savesByOwner.set(s.owner, o = []); if (!o.includes(s)) o.push(s);
|
||||
}
|
||||
function unindexSave(s) {
|
||||
saveById.delete(s.id);
|
||||
const l = savesByPacket.get(s.packetId); if (l) { const i = l.indexOf(s); if (i >= 0) l.splice(i, 1); }
|
||||
const o = savesByOwner.get(s.owner); if (o) { const i = o.indexOf(s); if (i >= 0) o.splice(i, 1); }
|
||||
}
|
||||
function load() {
|
||||
try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; }
|
||||
S = Object.assign({ v: 1, seq: { packet: 0, report: 0, visit: 0, click: 0, sview: 0 }, daily: {}, totals: { visits: 0, views: 0, clicks: 0, vclicks: 0, sviews: 0 },
|
||||
members: {}, sessions: {}, purchases: {}, shop: {}, orderRef: {}, packets: [], saves: [], reports: [], visits: [], clicks: [], sviews: [] }, S || {});
|
||||
rowMode = docstore.isOn();
|
||||
if (rowMode) for (const sp of SPLITS) S[sp.field] = (docstore.rows(sp.table) || []).slice();
|
||||
index();
|
||||
const now = Date.now();
|
||||
for (const [k, s] of Object.entries(S.sessions)) if (s.expires < now) delete S.sessions[k];
|
||||
}
|
||||
function save(now) {
|
||||
if (saveT && !now) return;
|
||||
const run = () => {
|
||||
saveT = null;
|
||||
try {
|
||||
const out = rowMode ? Object.assign({}, S, Object.fromEntries(SPLITS.map(sp => [sp.field, []]))) : S;
|
||||
const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 }); fs.renameSync(tmp, FILE());
|
||||
} catch (e) { console.error('store save failed', e.message); }
|
||||
};
|
||||
if (now) { clearTimeout(saveT); run(); } else saveT = setTimeout(run, 800);
|
||||
}
|
||||
function flush() { save(true); }
|
||||
const state = () => S;
|
||||
function putRow(field, item) { if (rowMode) { const sp = TABLE[field]; docstore.rowPut(sp.table, item[sp.key], item[sp.ts], item); } save(); }
|
||||
function dropRows(field, ids) {
|
||||
if (!ids.length) return;
|
||||
const set = new Set(ids); S[field] = S[field].filter(x => !set.has(x[TABLE[field].key]));
|
||||
if (rowMode) docstore.rowDel(TABLE[field].table, ids);
|
||||
save();
|
||||
}
|
||||
function nextId(kind) { S.seq[kind] = (S.seq[kind] || 0) + 1; return S.seq[kind]; }
|
||||
|
||||
// ---- Central time (Marty: everything on US Central) ----
|
||||
const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
|
||||
function ctDay(ts) { const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value])); return p.year + '-' + p.month + '-' + p.day; }
|
||||
function ctWeek(ts) {
|
||||
const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value]));
|
||||
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0;
|
||||
return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)).toISOString().slice(0, 10);
|
||||
}
|
||||
function bump(k, n) { const day = ctDay(); const d = S.daily[day] || (S.daily[day] = {}); d[k] = (d[k] || 0) + (n || 1); save(); }
|
||||
function today() { return S.daily[ctDay()] || {}; }
|
||||
|
||||
// ---- packets (planted programs) ----
|
||||
function packet(id) { return packetById.get(Number(id)) || null; }
|
||||
function packets() { return S.packets; }
|
||||
function addPacket(p) { p.id = nextId('packet'); p.createdAt = p.createdAt || Date.now(); p.updatedAt = Date.now(); S.packets.push(p); packetById.set(p.id, p); putRow('packets', p); return p; }
|
||||
function savePacket(p) { p.updatedAt = Date.now(); putRow('packets', p); }
|
||||
function packetsOf(owner) { const o = lc(owner); return S.packets.filter(p => p.owner === o && p.status !== 'removed'); }
|
||||
|
||||
// ---- saved IDs: one per member per packet. id = <packetId>|<wallet> ----
|
||||
const saveKey = (packetId, owner) => Number(packetId) + '|' + lc(owner);
|
||||
function saveOf(packetId, owner) { return saveById.get(saveKey(packetId, owner)) || null; }
|
||||
function savesOf(packetId) { return savesByPacket.get(Number(packetId)) || []; }
|
||||
function savesBy(owner) { return savesByOwner.get(lc(owner)) || []; }
|
||||
function putSave(packetId, owner, patch) {
|
||||
const id = saveKey(packetId, owner); let s = saveById.get(id);
|
||||
if (!s) { s = { id, packetId: Number(packetId), owner: lc(owner), at: Date.now() }; S.saves.push(s); indexSave(s); }
|
||||
Object.assign(s, patch || {}); s.updatedAt = Date.now(); putRow('saves', s); return s;
|
||||
}
|
||||
function dropSave(packetId, owner) { const s = saveOf(packetId, owner); if (!s) return false; unindexSave(s); dropRows('saves', [s.id]); return true; }
|
||||
function saves() { return S.saves; }
|
||||
|
||||
// ---- reports (the report button) ----
|
||||
function addReport(r) { r.id = 'r' + nextId('report'); r.at = Date.now(); S.reports.push(r); putRow('reports', r); return r; }
|
||||
function saveReport(r) { putRow('reports', r); }
|
||||
function reports() { return S.reports; }
|
||||
|
||||
// ---- verified visits / clicks / Spotlight views ----
|
||||
function addVisit(v) { v.id = 'v' + nextId('visit'); v.at = v.at || Date.now(); S.visits.push(v); putRow('visits', v); return v; }
|
||||
function addClick(c) { c.id = 'k' + nextId('click'); c.at = c.at || Date.now(); S.clicks.push(c); putRow('clicks', c); return c; }
|
||||
function addSview(b) { b.id = 's' + nextId('sview'); b.at = b.at || Date.now(); S.sviews.push(b); putRow('sviews', b); return b; }
|
||||
const visits = () => S.visits, clicks = () => S.clicks, sviews = () => S.sviews;
|
||||
// visits + clicks: 15 days (the 24-hour checks and the weekly numbers); Spotlight views: 120 days (the delivery audit trail)
|
||||
function prune() {
|
||||
const now = Date.now(); let n = 0;
|
||||
for (const [f, days] of [['visits', 15], ['clicks', 15], ['sviews', 120]]) { const cut = now - days * 86400000; const old = S[f].filter(x => x.at < cut).map(x => x.id); dropRows(f, old); n += old.length; }
|
||||
return n;
|
||||
}
|
||||
|
||||
// ---- members (keyed by wallet: sign-in is by wallet or the network sign-in, which always carries the wallet) ----
|
||||
function member(addr) { return S.members[lc(addr)] || null; }
|
||||
function upsertMember(addr, patch) {
|
||||
const a = lc(addr);
|
||||
const m = S.members[a] || (S.members[a] = { address: a, username: null, joinedAt: Date.now(), via: null, netOk: false });
|
||||
Object.assign(m, patch || {}); m.lastSeen = Date.now(); save(); return m;
|
||||
}
|
||||
function memberByName(name) {
|
||||
const n = lc(name); if (!n) return null;
|
||||
for (const m of Object.values(S.members)) if (m.username && m.username.toLowerCase() === n) return m;
|
||||
return null;
|
||||
}
|
||||
function memberByHub(id) { if (!id) return null; for (const m of Object.values(S.members)) if (m.hubId === id) return m; return null; }
|
||||
function members() { return Object.values(S.members); }
|
||||
|
||||
// ---- sessions ----
|
||||
const SESSION_TTL = 7 * 24 * 3600000;
|
||||
function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: lc(address), expires: Date.now() + SESSION_TTL }; save(); return token; }
|
||||
function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; }
|
||||
function dropSession(token) { delete S.sessions[token]; save(); }
|
||||
function endSessions(match, before) { let n = 0; for (const [k, x] of Object.entries(S.sessions)) if (x.expires - SESSION_TTL <= before && match(x)) { delete S.sessions[k]; n++; } if (n) save(); return n; }
|
||||
|
||||
module.exports = { SPLITS, load, flush, save, state, ctDay, ctWeek, bump, today,
|
||||
packet, packets, addPacket, savePacket, packetsOf, saveOf, savesOf, savesBy, putSave, dropSave, saves, saveKey,
|
||||
addReport, saveReport, reports, addVisit, addClick, addSview, visits, clicks, sviews, prune,
|
||||
member, upsertMember, memberByName, memberByHub, members, mintSession, session, dropSession, endSessions, SESSION_TTL };
|
||||