ViralAdSource app (Marty approved 2026-11-16): free text ads that spread by reshares, each ad with its own family tree
Watershed look from the approved mockup (hero, topo pattern, icons). Network sign-in through the hub, hub membership, activity ping. Reshare links per member per ad with branch/step tracking; family-tree dashboard (branch, step, reshares, views, clicks, sign-ups, Boosts). Verified views earn ad credits for the branch's resharer (L3). L2 sign-up pipeline (hub-new, confirmed email, not self device/IP, throwaway block, daily cap, fraud score) with keeper-signed reward vouchers and a pending-rewards ledger; payouts OFF (REWARD_PAYOUTS). L1 Boosts through VASShop with signed orders naming the sponsor line and the resharer. Trust pack, chatbot, promo kit, PolHunter embed. All numbers are PROPOSALS until Marty sets them. qa/e2e.mjs 59/59 on a local anvil chain, chatbot test 108/108. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
data
|
||||
qa/out
|
||||
.git
|
||||
.env
|
||||
@@ -0,0 +1,21 @@
|
||||
# ViralAdSource app env (Coolify). Never commit real values. Numbers marked PROPOSAL in config.js have defaults; Marty sets the real ones.
|
||||
DOCSTORE_URL= # mysql://user:pass@host:3306/viraladsource REQUIRED (files are local prototype only)
|
||||
SITE_HOST=viraladsource.com # staging: vas.saasy.top
|
||||
STAGING=0 # 1 = staging banner + the admin-only test-member switch (refused on viraladsource.com anyway)
|
||||
SESSION_SECRET=
|
||||
ADMIN_TOKEN= # x-admin-token for /api/admin/*
|
||||
NETWORK_SSO_SECRET= # network-wide secret (LinkSpin partner calls)
|
||||
HUB_URL=https://hub.saasy.top
|
||||
HUB_SECRET= # this site's hub secret (HUB_SITES.viraladsource)
|
||||
HUB_SITE=viraladsource
|
||||
HUB_SSO=on # network sign-in through the hub
|
||||
HUB_ENABLED=0 # 1 = report Boosts to the hub (contract-bind / spend)
|
||||
HUB_JOIN=0 # 1 = a confirmed L2 sign-up is written to the hub (join-all). 0 = dry check only
|
||||
MAIL_URL= # mail relay for confirm links (JSON POST {from,to,subject,text}); empty = no mail
|
||||
CONTRACT_ADDRESS= # VASShop
|
||||
CHAIN_RPC=
|
||||
KEEPER_KEY= # signs orders + reward vouchers (a NEW key, never the ViralAdBlitz keeper)
|
||||
RELAY_KEY= # pays gas for claimReward relays (holds a little POL only)
|
||||
REWARD_PAYOUTS=0 # 1 = relay sign-up rewards. OFF until Marty confirms the amounts
|
||||
LS_TRACK=0 # 1 = LinkSpin tracked links for ads (needs LinkSpin's 'vas' partner entry)
|
||||
LS_PARTNER=vas
|
||||
@@ -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,58 @@
|
||||
# ViralAdSource app (viraladsource.com rebuild)
|
||||
|
||||
"Every ad has a source. Watch yours travel." Approved by Marty 2026-11-16 (mockup: Design canvas 2XuFAog3KEiuXbfEvVvTZk).
|
||||
Plain Node http server, no framework (the ViralAdBlitz / VBB / Downline Banners pattern). Contract: `../contracts` (VASShop).
|
||||
|
||||
Every number marked **PROPOSAL** (Boost $5, resharer 20%, pot 10%, sponsor levels 5 x 5%, sign-up reward $0.25 with a daily cap of 10,
|
||||
10 credits per 100 verified views, tier bonus every 25th sign-up $2.50 locked 14 days, Boost = 7 days on top) is Claude's proposal.
|
||||
Marty has not set them. Payouts of sign-up rewards are OFF (`REWARD_PAYOUTS`).
|
||||
|
||||
## What it does
|
||||
|
||||
- **Free text ad** (headline 60, two lines of 90, an https link, or the member's OWN LinkSpin spin link picked from "Use one of my spin
|
||||
links"; ownership confirmed through LinkSpin's signed partner endpoint `/api/partner/<LS_PARTNER>/links`, op `spins`). One ad per
|
||||
network member. Membership from the network hub (hubpeople.js), sign-in through the hub (networksso.js, `HUB_SSO=on`) or a wallet signature.
|
||||
- **Reshares** (tree.js): every ad has a source link `/s/<code>` (step 0). A member who reshares gets ONE unique link per ad; its parent is
|
||||
the reshare link they arrived through (the `vas.via` tag, last touch, 30 days), so `step` counts how far from the source it travelled and
|
||||
`branch` is the step-1 link it descends from. `/a/<id>` and `/<username>` open an ad at its source.
|
||||
- **Family tree** (`GET /api/my` -> `tree`): branch, step, reshares under it, verified views, verified clicks, sign-ups, Boosts, with
|
||||
totals and the furthest step. Clicks through a reshare link carry the branch: `/go/<ad>?s=<code>`; on LinkSpin links the relay adds
|
||||
`s2=<resharer>` and `s3=<code>` so LinkSpin Reports split clicks and sign-ups per branch.
|
||||
- **Verified views** (wire.js, the VBB / ViralAdBlitz rules): the server decides what a page showed; after `VISIT_SECONDS` visible the
|
||||
browser redeems its ticket; one view per visitor per ad per 24 h; never the owner's own; never a resharer's own link; `VISITS_PER_IP_DAY`.
|
||||
- **L3 ad credits**: verified views through a reshare link (step 1+) count for that resharer; every `CREDITS_VIEWS` (100) earn
|
||||
`CREDITS_PER` (10) credits. Credits are spent on the member's own ad in the "Featured with credits" places (1 credit per verified view
|
||||
there). Never paid out. "Ad credits buy advertising, not income."
|
||||
- **L2 sign-up rewards** (signup.js): `/join` through a reshare link -> confirm link (MAIL_URL relay; unset on staging = no mail, the admin
|
||||
page shows the link) -> real-time checks: share (a resharer, never the owner's own link), confirmed email, throwaway domain, **hub-new**
|
||||
(the hub has never seen the email; `HUB_JOIN=1` writes the join with sponsor = the resharer and requires `created: true`; staging = dry
|
||||
read, nobody created), not the resharer's own device (rejected) or connection (held), daily cap, fraud score (held at `FRAUD_HOLD`).
|
||||
Passed -> a row in the pending-rewards ledger with a keeper-signed EIP-712 `Reward(to, usdCents, unlockAt, nonce, deadline)` voucher.
|
||||
Tier bonuses (`REWARD_TIERS`) carry an `unlockAt`. `REWARD_PAYOUTS=1` relays `claimReward` from `RELAY_KEY`'s wallet (gas only); the
|
||||
contract pays from the pot. Admin can release / reject / recheck.
|
||||
- **L1 Boost** (shop.js): `POST /api/my/order` builds a keeper-signed `Order(buyer, sku, qty, ref, line[], resharer, nonce, deadline)`:
|
||||
line = the buyer's hub sponsor line (wallets, up to 20), resharer = the owner of the reshare link the buyer came through (never the
|
||||
buyer). The contract pays the resharer cut, the sponsor levels (pass-up over people who never bought), the pot slice and the company in
|
||||
the same transaction. The watcher records Purchase and RewardPaid events; a Boost puts the ad on top of the reshare board for 7 days per unit.
|
||||
- **Trust pack** (proof.js): `/ledger` (Boost splits + sign-up rewards, no emails), `/contract` (live from the chain, or the proposals
|
||||
before deploy), toasts (new ads, reshares, Boosts), Telegram photo card per Boost (off unless `TG_*` are set), Terms / Earnings
|
||||
Disclaimer / Privacy (TrustClickz, 615 Green Valley Drive, Moody, AL 35004), the network footer (netsites.js).
|
||||
- **Chatbot** (chatbot.js + the shared chatcore / kb / netkb), **promo kit** (`/promote`, `/api/promo-kit`, 24 creatives
|
||||
`public/art/kit/vas-{free,tree,boost}-<shape>.png`), **PolHunter embed** on the front page (hunters' visits never count).
|
||||
- **Old links** (the YourFreeWorld site): `/?<old>`, `/index.php?<old>`, `/splashpg.php?r=`, `/lcp.php?r=` -> the member's ad via
|
||||
oldrefs.json (`POST /api/admin/oldrefs`, payload D:/tmp/vas-reconcile/oldrefs-admin-payload.json, load at the domain switch); other `*.php` -> `/`.
|
||||
- **Data**: docstore.js (MySQL via `DOCSTORE_URL`): document `vas.json` + row tables `vas_ads`, `vas_shares`, `vas_visits`, `vas_clicks`,
|
||||
`vas_signups`, `vas_rewards`.
|
||||
- **Staging switch**: `STAGING=1` shows the staging bar and enables the admin-only `POST /api/admin/test-member` (marks a wallet as a
|
||||
test network member). It is refused whenever SITE_HOST is viraladsource.com.
|
||||
|
||||
## Run and test
|
||||
|
||||
```
|
||||
npm install
|
||||
node tools/pages.mjs # regenerate public/*.html (one source of copy + legal facts)
|
||||
node tools/art.mjs # icon, OG image, proof cards, kit creatives (Playwright)
|
||||
node qa/e2e.mjs # 59 checks: real VASShop on a local anvil chain + stand-in hub (needs ../contracts built)
|
||||
node qa/chatbot.test.mjs # the site assistant
|
||||
```
|
||||
Env: `.env.example`.
|
||||
@@ -0,0 +1,71 @@
|
||||
// ViralAdSource'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 (Boost, split, reward and credit numbers, all marked
|
||||
// as PROPOSALS until Marty sets them), tree.js (reshare links, branches, steps), wire.js (verified views, credits), signup.js (the L2
|
||||
// checks, payouts off), shop.js + ../contracts (VASShop), lstrack.js (spin-link picker), 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.
|
||||
'use strict';
|
||||
const core = require('./chatcore');
|
||||
const C = require('./config').get();
|
||||
|
||||
const KNOWLEDGE_DATE = '2026-11-16';
|
||||
const URL_ = 'https://' + C.site;
|
||||
const SUPPORT = 'https://instantadpay.com/support';
|
||||
const B = C.boost, SP = C.split, R = C.reward, CR = C.credits;
|
||||
const pct = bps => (bps / 100).toFixed(bps % 100 ? 1 : 0) + '%';
|
||||
const NOT_INCOME = 'Ad credits buy advertising, not income.';
|
||||
|
||||
const CANNED = [
|
||||
{ id: 'support', title: 'Talk to a person, or a problem with my account', q: ['How do I contact support?', 'My Boost did not show up', 'I need a real person'], tags: ['support', 'help', 'ticket', 'problem'],
|
||||
re: core.SUPPORT_RE, handoff: true,
|
||||
a: 'Network support handles every network site, ViralAdSource included: open ' + SUPPORT + ', say it is about ViralAdSource, and include your wallet address and the transaction link if it is about a Boost or a reward.' },
|
||||
{ id: 'about', title: 'What is ViralAdSource?', q: ['What is ViralAdSource?', 'How does ViralAdSource work?', 'What is VAS?'], tags: ['viraladsource', 'vas', 'reshare', 'overview'],
|
||||
re: /(what('s| is) (viral ?ad ?source|vas|this (site|place))|how does (viral ?ad ?source|vas|this site|it) work|explain (viral ?ad ?source|this))/i,
|
||||
a: 'ViralAdSource is where every ad has a source. Post one free text ad, then anyone can reshare it with their own reshare link, and every reshare grows a new branch. Your dashboard shows the family tree of your ad: who passed it on, how many steps it travelled, and the views, clicks and sign-ups each branch brought in. See ' + URL_ + '/#how' },
|
||||
{ id: 'reshare', title: 'How resharing works', q: ['How do I reshare an ad?', 'What is a reshare link?', 'What is a branch?'], tags: ['reshare', 'branch', 'tree', 'link'],
|
||||
re: /(reshare|re-share|branch|family tree|share link|step)/i,
|
||||
a: 'Open any ad and tap "Reshare this ad". You get your own unique reshare link for that ad (one per ad, always the same). Anyone who arrives through it and reshares too grows the branch under you. Each click and view through your link is booked to you, so the ad owner sees your branch on their tree. A share alone is never paid: only real results through your link are.' },
|
||||
{ id: 'rewards', title: 'How resharers are rewarded', q: ['Do I get paid for resharing?', 'What are the three rewards?', 'How do rewards work?'], tags: ['reward', 'paid', 'earn', 'resharer'],
|
||||
re: /(reward|get paid|earn|paid for|commission|payout)/i,
|
||||
a: 'Only results are rewarded, never a bare share. 1) A Boost bought through your branch: the contract pays you a resharer cut in POL in the same transaction (proposed ' + pct(SP.resharerBps) + '). 2) A brand-new network member who joins through your link and confirms their email: a small POL reward from the reward pot after real-time checks (proposed $' + (R.cents / 100).toFixed(2) + ', with a daily cap of ' + R.dailyCap + '). Sign-up reward payouts are switched off until the amounts are confirmed; they wait in the pending ledger. 3) Verified views through your link: ad credits for your own ad (proposed ' + CR.per + ' credits per ' + CR.views + ' views). ' + NOT_INCOME + ' Nothing is promised.' },
|
||||
{ id: 'credits', title: 'Ad credits', q: ['What are ad credits?', 'How do I use my credits?'], tags: ['credits', 'ad credits', 'views'],
|
||||
re: /\bcredits?\b/i,
|
||||
a: 'Every ' + CR.views + ' verified views through your reshare links earn ' + CR.per + ' ad credits (a proposal until confirmed). Credits are spent automatically on your own ad: it is shown in the "Featured with credits" places, and each verified view there uses 1 credit. Credits are never paid out. ' + NOT_INCOME },
|
||||
{ id: 'spin-link', title: 'Use one of my LinkSpin spin links as my ad link', q: ['Can I use my LinkSpin spin link in my ad?'], tags: ['linkspin', 'spin link', 'rotator'],
|
||||
re: /(spin ?links?|\brotator\b|linkspin link)/i,
|
||||
a: 'Yes. In the ad form on ' + URL_ + '/my tap "Use one of my spin links" and pick one of your own LinkSpin spin links. LinkSpin confirms it is yours on every save. Clicks through a reshare link carry the resharer (s2) and the reshare link (s3), so your LinkSpin Reports show which branch brought each click and sign-up.' },
|
||||
{ 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). Posting a text ad and resharing are free for network members.' },
|
||||
{ id: 'boost', title: 'What a Boost is', q: ['What is a Boost?', 'How much is a Boost?', 'Where does the Boost money go?'], tags: ['boost', 'price', 'split'],
|
||||
re: /\bboost/i,
|
||||
a: 'A Boost (proposed $' + B.usd + ', one-time, never a subscription) puts your ad at the top of the reshare board for ' + B.days + ' days, so more people see it and pass it on. Paid in POL with SafePal or any other crypto wallet. The contract splits it in the same transaction (proposed): ' + pct(SP.resharerBps) + ' to the resharer whose branch sold it, ' + pct(SP.potBps) + ' to the reward pot, ' + SP.levelBps.map(pct).join(' / ') + ' to your sponsor line (people who have bought a Boost; others are passed over), the rest to the company. Every payment is on ' + URL_ + '/ledger.' },
|
||||
{ id: 'old', title: 'Old ViralAdSource accounts', q: ['I was a ViralAdSource member before', 'Does my old link work?'], tags: ['old account', 'old link'],
|
||||
re: /(old (account|link|balance|member)|was a member|member before|before the rebuild)/i,
|
||||
a: 'Old ViralAdSource members were matched to the network by email and keep their sponsor. Sign in with your network account. Old referral links open your new member page. Old balances were not carried over.' }
|
||||
];
|
||||
const FAQ = [
|
||||
{ id: 'f-network', title: 'ViralAdSource and the other network sites', source: 'faq', tags: ['network', 'one account'],
|
||||
questions: ['Is ViralAdSource part of InstantAdPay?', 'Do I need a new account?'],
|
||||
answer: 'ViralAdSource is part of the network: one network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, DownlineHydra, 5xYourTeam, Stack POL and Earners Corner, with the same username and sponsor everywhere.' },
|
||||
{ id: 'f-checks', title: 'How a sign-up reward is verified', source: 'faq', tags: ['verified', 'checks', 'fraud'],
|
||||
questions: ['How do you check a sign-up?', 'Why was my sign-up reward held?'],
|
||||
answer: 'A sign-up reward needs all of these: the person is brand new to the whole network (checked with the network hub), they confirmed their email, it is not your own device, connection or wallet, the email is not a throwaway address, you are under the daily cap, and the fraud score is low. A sign-up that looks unusual is held for a person to look at.' }
|
||||
];
|
||||
const FACTS = () => [
|
||||
'- WHAT IT IS: ViralAdSource (' + URL_ + '): "Every ad has a source. Watch yours travel." One free text ad per network member (headline ' + C.ad.headline + ', two lines of ' + C.ad.line + ', an https link or the member\'s own LinkSpin spin link). Anyone reshares an ad with their own unique reshare link /s/<code>; each reshare is a branch; the owner\'s dashboard shows the family tree: branch, step, reshares under it, views, clicks, sign-ups.',
|
||||
'- REWARDS (results only, never a bare share; all amounts are PROPOSALS until Marty confirms): L1 Boost through a branch: resharer cut ' + pct(SP.resharerBps) + ' paid by the VASShop contract in the same transaction. L2 verified brand-new network member through a branch: $' + (R.cents / 100).toFixed(2) + ' in POL from the reward pot, cap ' + R.dailyCap + ' a day per resharer; checks: hub-new, confirmed email, not the resharer\'s device/IP/wallet, no throwaway email, daily cap, fraud score; payouts currently ' + (R.payouts ? 'ON' : 'OFF (rewards wait in the pending ledger)') + '. L3 verified views: ' + CR.per + ' ad credits per ' + CR.views + ' verified views through the resharer\'s links, spent on their own ad, never paid out.',
|
||||
'- BOOST: one-time $' + B.usd + ' (proposal) = top of the reshare board for ' + B.days + ' days per unit, 1 to ' + B.maxQty + ' per purchase. Split: resharer ' + pct(SP.resharerBps) + ', reward pot ' + pct(SP.potBps) + ', sponsor levels ' + SP.levelBps.map(pct).join('/') + ' (pass-up over people who never bought, up to ' + SP.maxDepth + ' places), company the rest. The pot can only pay sign-up rewards, never more than it holds.',
|
||||
'- VERIFIED VIEWS: page visible ' + C.visitSeconds + ' s, one view per visitor per ad per 24 h, never the owner\'s own, max ' + C.perIpDay + ' browsers per connection a day.',
|
||||
'- TRUST: ' + URL_ + '/ledger, ' + URL_ + '/contract, toasts of real events. Terms ' + URL_ + '/terms, Earnings Disclaimer ' + URL_ + '/disclaimer, Privacy ' + URL_ + '/privacy. Run by TrustClickz, 615 Green Valley Drive, Moody, AL 35004. SUPPORT: ' + SUPPORT
|
||||
].join('\n');
|
||||
|
||||
const SITE = {
|
||||
id: 'viraladsource', hubSite: 'viraladsource', netId: 'viraladsource', name: 'ViralAdSource', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE,
|
||||
dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS,
|
||||
intro: 'You are the assistant on ViralAdSource (' + URL_ + '): free text ads that spread by reshares, each ad with its own family tree, and rewards only for verified results. It is part of a network of sites that share one account.',
|
||||
quickTopics: ['How does resharing work?', 'How are resharers rewarded?', 'What are ad credits?', 'What is a Boost?']
|
||||
};
|
||||
function init() { return core.init(SITE); }
|
||||
module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE };
|
||||
@@ -0,0 +1,219 @@
|
||||
// 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.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,75 @@
|
||||
// All runtime config comes from env (Coolify sets these). Read once.
|
||||
// ViralAdSource (viraladsource.com rebuild, Marty approved 2026-11-16: "that looks good. Let's go with it."). "Every ad has a source.
|
||||
// Watch yours travel." A network member posts one free text ad; anyone reshares it with their own unique reshare link; every
|
||||
// reshare is a branch of the ad's family tree. Rewards are for verified RESULTS only, never a bare share:
|
||||
// L1 a Boost bought through a branch: the resharer's cut is paid by VASShop in the same transaction (server-signed order).
|
||||
// L2 a verified brand-new network member through a branch: a small POL reward from the contract's reward pot, after real-time
|
||||
// checks (hub-new, confirmed email, not the resharer's device/IP/wallet, no throwaway email, daily cap, fraud score).
|
||||
// PAYOUTS ARE OFF (REWARD_PAYOUTS=1 turns the relay on) until Marty confirms the amounts.
|
||||
// L3 verified views through a branch: ad credits for the resharer, spent on their own ad. Ad credits buy advertising, not income.
|
||||
// Every number below marked PROPOSAL is Claude's proposal (2026-11-16); Marty has not set them.
|
||||
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()) : '';
|
||||
let tiers = [];
|
||||
try { tiers = JSON.parse(e.REWARD_TIERS || '[]'); } catch (x) { tiers = []; }
|
||||
if (!Array.isArray(tiers) || !tiers.length) tiers = [{ every: 25, cents: 250, lockDays: 14 }]; // PROPOSAL: each 25th verified sign-up from one resharer = a $2.50 bonus, withdrawable after 14 days
|
||||
cfg = {
|
||||
port: Number(e.PORT || 3000),
|
||||
isProd: e.NODE_ENV === 'production',
|
||||
site: e.SITE_HOST || 'viraladsource.com',
|
||||
siteName: 'ViralAdSource',
|
||||
siteId: 'viraladsource', // hub site id, network sign-in audience, netsites id
|
||||
staging: e.STAGING === '1', // staging only: the admin "mark test member" switch, no ad zones
|
||||
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(),
|
||||
// ---- Boost (PROPOSAL $5). The contract's SKU holds the real price; this is display copy and must match it.
|
||||
// A Boost puts the ad at the top of the reshare board for `days` days per unit. One-time, never a subscription.
|
||||
boost: { sku: int(e.BOOST_SKU, 1, 1, 1000), usd: num(e.BOOST_USD, 5, 0.01, 1000), days: int(e.BOOST_DAYS, 7, 1, 365), maxQty: 10 },
|
||||
// VASShop split (PROPOSAL; owner-settable on the contract, read live from it when the contract is set): basis points
|
||||
split: { resharerBps: int(e.SPLIT_RESHARER_BPS, 2000, 0, 9000), potBps: int(e.SPLIT_POT_BPS, 1000, 0, 9000), levelBps: String(e.SPLIT_LEVEL_BPS || '500,500,500,500,500').split(',').map(x => int(x, 0, 0, 9000)).slice(0, 5), maxDepth: 20 },
|
||||
// ---- L2 sign-up rewards (PROPOSAL $0.25, 10 a day per resharer). Payouts OFF unless REWARD_PAYOUTS=1.
|
||||
reward: { cents: int(e.REWARD_CENTS, 25, 1, 10000), dailyCap: int(e.REWARD_DAILY_CAP, 10, 0, 1000), tiers,
|
||||
payouts: e.REWARD_PAYOUTS === '1', fraudHold: int(e.FRAUD_HOLD, 50, 1, 100), voucherDays: int(e.REWARD_VOUCHER_DAYS, 30, 1, 365),
|
||||
joinWindowHours: int(e.JOIN_WINDOW_HOURS, 72, 1, 720) },
|
||||
hubJoin: e.HUB_JOIN === '1', // a confirmed sign-up is written to the hub (join-all). OFF on staging: a dry check instead
|
||||
mail: { from: String(e.MAIL_FROM || 'ViralAdSource <noreply@viraladsource.com>'), url: String(e.MAIL_URL || '').trim() }, // MAIL_URL unset = no mail sent (staging)
|
||||
// ---- L3 ad credits (PROPOSAL: 10 credits per 100 verified views through a branch; 1 credit = 1 verified view of your own ad)
|
||||
credits: { per: int(e.CREDITS_PER, 10, 1, 1000), views: int(e.CREDITS_VIEWS, 100, 1, 100000), slots: int(e.CREDIT_SLOTS, 2, 0, 10) },
|
||||
// verified visitors (the VBB / ViralAdBlitz rules)
|
||||
visitSeconds: int(e.VISIT_SECONDS, 6, 2, 60),
|
||||
visitWindowHours: 24,
|
||||
perIpDay: int(e.VISITS_PER_IP_DAY, 3, 1, 100),
|
||||
boardSize: int(e.BOARD_SIZE, 12, 3, 50),
|
||||
viaDays: int(e.VIA_DAYS, 30, 1, 365), // how long a reshare link's tag stays on a visitor (last touch)
|
||||
maxStep: int(e.MAX_STEP, 50, 2, 500), // the deepest reshare step kept
|
||||
ad: { headline: 60, line: 90 },
|
||||
linkProbe: e.LINK_PROBE !== '0',
|
||||
explorer: String(e.EXPLORER || (Number(e.CHAIN_ID || 137) === 137 ? 'https://polygonscan.com' : '')).replace(/\/+$/, ''),
|
||||
// VASShop (../contracts). KEEPER_KEY / RELAY_KEY are read by shop.js only, never kept here.
|
||||
contractAddress: addr(e.CONTRACT_ADDRESS),
|
||||
companyWallet: addr(e.COMPANY_WALLET) || '0x7627Fc78876948AC9d95C1C9eB061E7D6d647b70', // Tangem (immutable in VASShop)
|
||||
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(/\/+$/, ''),
|
||||
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,42 @@
|
||||
services:
|
||||
viraladsource:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
PORT: 3000
|
||||
DATA_DIR: /app/data
|
||||
SITE_HOST: ${SITE_HOST:-viraladsource.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:-}
|
||||
RELAY_KEY: ${RELAY_KEY:-}
|
||||
REWARD_PAYOUTS: ${REWARD_PAYOUTS:-0}
|
||||
HUB_JOIN: ${HUB_JOIN:-0}
|
||||
MAIL_URL: ${MAIL_URL:-}
|
||||
MAIL_KEY: ${MAIL_KEY:-}
|
||||
HUB_URL: ${HUB_URL:-}
|
||||
HUB_SECRET: ${HUB_SECRET:-}
|
||||
HUB_SITE: ${HUB_SITE:-viraladsource}
|
||||
HUB_ENABLED: ${HUB_ENABLED:-0}
|
||||
HUB_SSO: ${HUB_SSO:-off}
|
||||
LS_TRACK: ${LS_TRACK:-0}
|
||||
LS_PARTNER: ${LS_PARTNER:-vas}
|
||||
TG_TOKEN: ${TG_TOKEN:-}
|
||||
TG_CHAT: ${TG_CHAT:-}
|
||||
TG_PAY_TOPIC: ${TG_PAY_TOPIC:-}
|
||||
JOIN_URL: ${JOIN_URL:-}
|
||||
volumes:
|
||||
- vas-data:/app/data # the session secret + the OpenRouter key file only; all data lives in MySQL (DOCSTORE_URL)
|
||||
expose:
|
||||
- "3000"
|
||||
volumes:
|
||||
vas-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,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,40 @@
|
||||
// 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
|
||||
const r = await hubpeople.sponsorOf(p); 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) });
|
||||
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 = 'viraladsource';
|
||||
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). ViralAdSource members are wallets here, so every VASShop Boost
|
||||
// goes to the hub by wallet:
|
||||
// the buyer's first purchase: POST /v1/contract-bind { contract: 'viraladsource', wallet, sponsorRef: <sponsor wallet>, spentCents, tx, at }
|
||||
// every later purchase: POST /v1/contract-spend { contract: 'viraladsource', 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 = 'viraladsource';
|
||||
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 || 'viraladsource').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 || 'viraladsource').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,141 @@
|
||||
// LinkSpin tracking on member text ads (Marty 2026-11-15, the DownlineHydra module generalized: LinkSpin /api/partner/<site>/links).
|
||||
// When a member saves their text ad, LinkSpin makes (or updates) a tracked link for it on that member's own LinkSpin account (every
|
||||
// hub member has one through join-all), tagged with the account's "ViralAdSource" source and the ad id as a sub-id (?s1=<ad>&placement=<ad>),
|
||||
// so LinkSpin Reports show the ad's clicks. The ad's public link (/go/<ad>) then sends to the tracked link, which lands on the member's
|
||||
// own link. Per ad the member can switch tracking off ("Track with LinkSpin", default on): then /go/<ad> sends straight to their link.
|
||||
// Fail soft: if LinkSpin does not answer (or does not know the endpoint yet), the ad works exactly as before with its plain link,
|
||||
// and the sweep tries again later. A tracked link is used only while it points at the ad's current link (an edit never sends
|
||||
// traffic to an old destination). Links with {clickid} / {placement} macros are not tracked (they are filled here on every click).
|
||||
// Account: by network username (ViralAdSource never stores emails). The call: POST LS_URL/api/partner/vab/links, X-Net-Ts + X-Net-Sig =
|
||||
// hex HMAC-SHA256('net.v1.' + ts + newline + raw body) with NETWORK_SSO_SECRET (the Downline Banners Banner Spins pattern).
|
||||
// ensureAd(ad) -> updates ad.ls { code, link, url, at } or ad.lsErr / ad.lsTry; saves through the store
|
||||
// clicks(username) -> { <ad id>: { hits, hits30, unique30 } } | null (cached 5 minutes per member)
|
||||
// dest(ad) -> the tracked link when it is current, else null
|
||||
// "Use one of my spin links" (Marty 2026-11-15): the same endpoint with { username, op: 'spins' } lists the member's own LinkSpin spin
|
||||
// links (never another account's, never the tracked links made for ads). An ad whose link is the member's own spin link (ad.spin =
|
||||
// its code) is already tracked on LinkSpin, so it never gets the tracked-link wrapper. A LinkSpin /r/<code> link is accepted as an
|
||||
// ad link ONLY when LinkSpin confirms it belongs to the signed-in member (checkSpin); the network's own fixed links stay allowed.
|
||||
// spins(username) -> { account, host, hosts, spins: [{ code, name, url, destinations, paused }] } | { error }
|
||||
// checkSpin(url, username) -> { spin: false } (not a LinkSpin spin link) | { spin: true, code } | { error }
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
|
||||
let C = null, store = null; const st = { ensured: 0, failed: 0, noAccount: 0, lastError: null, lastOkAt: 0, sweeps: 0 };
|
||||
const cache = new Map();
|
||||
const MACRO = /\{(clickid|placement)\}|%7B(clickid|placement)%7D/i;
|
||||
const SITE = String(process.env.LS_PARTNER || 'vas').trim(); // LinkSpin partner path (/api/partner/<SITE>/links). 'vas' needs LinkSpin's PARTNER_LINKS entry first
|
||||
const NET_CODES = new Set(Object.values(require('./netsites').CODES)); // the network's fixed LinkSpin links (admin account), not member spin links
|
||||
const lsHosts = new Set(['linkspin.app']); // hosts a LinkSpin /r/ link answers on, learned from every spins answer
|
||||
function init(cfg, st0) { C = cfg; store = st0; }
|
||||
// learn LinkSpin's link hosts (public; sent even when no account matches) so a foreign spin link is spotted after a restart too
|
||||
let hostsAt = 0;
|
||||
async function warmHosts() {
|
||||
if (!base() || String(process.env.NETWORK_SSO_SECRET || '').trim().length < 32 || Date.now() - hostsAt < 3600000) return;
|
||||
hostsAt = Date.now(); const r = await post({ username: '', op: 'spins' }, 6000).catch(() => ({}));
|
||||
for (const h of Array.isArray(r.hosts) ? r.hosts : []) if (/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(String(h))) lsHosts.add(String(h).toLowerCase());
|
||||
if (!Array.isArray(r.hosts)) hostsAt = Date.now() - 3000000; // no answer: try again in 10 minutes
|
||||
}
|
||||
const base = () => String(process.env.LS_TRACK_URL || (C && C.lsBase) || '').replace(/\/+$/, '');
|
||||
const on = () => !!(C && process.env.LS_TRACK !== '0' && process.env.LS_TRACK !== undefined && 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 ownerName = a => { const m = store.member(a.owner); return m && m.username ? String(m.username) : null; };
|
||||
// what the member sees about tracking for their ad
|
||||
function state(a) {
|
||||
if (!a) return null;
|
||||
if (a.spin) return 'spin';
|
||||
if (a.track === false) return 'off';
|
||||
if (MACRO.test(String(a.link || ''))) return 'macros';
|
||||
if (a.ls && a.ls.url === a.link && a.ls.link) return 'tracked';
|
||||
if (!ownerName(a)) return 'no-username';
|
||||
if (a.lsNoAccount && a.lsTry && Date.now() - a.lsTry < 86400000) return 'no-account';
|
||||
return 'pending';
|
||||
}
|
||||
const wants = a => a && !a.spin && a.status !== 'removed' && a.track !== false && !MACRO.test(String(a.link || '')) && !(a.ls && a.ls.url === a.link && a.ls.link) && !!ownerName(a);
|
||||
function dest(a) { return a && !a.spin && a.track !== false && a.ls && a.ls.link && a.ls.url === a.link && !MACRO.test(String(a.link || '')) ? a.ls.link : null; }
|
||||
|
||||
async function ensureAd(a) {
|
||||
if (!on() || !wants(a)) return { skipped: true };
|
||||
const username = ownerName(a);
|
||||
const r = await post({ username, op: 'ensure', links: [{ id: String(a.id), name: a.headline, url: a.link }] });
|
||||
a.lsTry = Date.now();
|
||||
if (r.error) { st.failed++; st.lastError = String(r.error).slice(0, 160); a.lsErr = st.lastError; store.saveAd(a); return r; }
|
||||
if (r.account === false) { st.noAccount++; a.lsNoAccount = true; delete a.lsErr; store.saveAd(a); return r; }
|
||||
const l = r.links && r.links[String(a.id)];
|
||||
if (!l) { st.failed++; a.lsErr = String((r.errors && r.errors[String(a.id)]) || 'no link').slice(0, 160); store.saveAd(a); return r; }
|
||||
a.ls = { code: l.code, link: l.link, url: a.link, at: Date.now() }; delete a.lsErr; delete a.lsNoAccount;
|
||||
st.ensured++; st.lastOkAt = Date.now(); cache.delete(username.toLowerCase()); store.saveAd(a);
|
||||
return { ok: true, link: l.link };
|
||||
}
|
||||
// the retry sweep: ads that want a tracked link and have not been tried lately (failures back off 10 minutes, no account a day)
|
||||
async function sweep(max) {
|
||||
warmHosts().catch(() => {});
|
||||
if (!on()) return 0; st.sweeps++; let n = 0;
|
||||
const backoff = Number(process.env.LS_RETRY_MS || 600000);
|
||||
for (const a of store.liveAds()) {
|
||||
if (n >= (max || 25)) break;
|
||||
if (!wants(a)) continue;
|
||||
if (a.lsTry && Date.now() - a.lsTry < (a.lsNoAccount ? 86400000 : backoff)) continue;
|
||||
n++; const r = await ensureAd(a).catch(() => ({ error: 'x' }));
|
||||
if (r && r.error === 'LinkSpin did not answer.') break; // LinkSpin is down: stop this round
|
||||
}
|
||||
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;
|
||||
}
|
||||
// the member's own spin links (read only)
|
||||
async function spins(username) {
|
||||
if (!base() || String(process.env.NETWORK_SSO_SECRET || '').trim().length < 32) return { error: 'The LinkSpin link is not set up yet.' };
|
||||
if (!username) return { error: 'Sign in through InstantAdPay or LinkSpin once to link your LinkSpin account.' };
|
||||
const r = await post({ username: String(username), op: 'spins' }, 6000);
|
||||
if (r.error) { st.lastError = String(r.error).slice(0, 160); return { error: 'LinkSpin did not answer just now. Try again in a minute.' }; }
|
||||
for (const h of (Array.isArray(r.hosts) ? r.hosts : []).concat(r.host ? [r.host] : [])) if (/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(String(h))) lsHosts.add(String(h).toLowerCase());
|
||||
if (r.account === false) return { account: false, spins: [] };
|
||||
const spins = (Array.isArray(r.spins) ? r.spins : []).filter(x => x && /^[a-z0-9]{4,12}$/i.test(String(x.code || '')) && /^https:\/\//.test(String(x.url || '')))
|
||||
.map(x => ({ code: String(x.code).toLowerCase(), name: String(x.name || '').slice(0, 80), url: String(x.url), destinations: Number(x.destinations) || 0, paused: !!x.paused }));
|
||||
return { account: true, host: r.host || null, hosts: Array.from(lsHosts), spins };
|
||||
}
|
||||
// is this ad link a LinkSpin spin link, and is it the member's own? (asked on every save of an ad link that looks like one)
|
||||
async function checkSpin(url, username) {
|
||||
let u; try { u = new URL(String(url || '')); } catch (e) { return { spin: false }; }
|
||||
const m = /^\/r\/([a-z0-9]{4,12})\/?$/i.exec(u.pathname); if (!m) return { spin: false };
|
||||
const host = u.hostname.toLowerCase().replace(/^www\./, ''); const code = m[1].toLowerCase();
|
||||
const mine = lsHosts.has(host) || (base() && (() => { try { return new URL(base()).hostname.toLowerCase() === host; } catch (e) { return false; } })());
|
||||
const r = await spins(username);
|
||||
if (r.error) return mine ? { error: 'LinkSpin could not confirm that spin link is yours just now. ' + r.error } : { spin: false };
|
||||
if (!lsHosts.has(host)) return { spin: false }; // a /r/ link on some other site: an ordinary link
|
||||
if (NET_CODES.has(code)) return { spin: false }; // the network's own fixed links stay allowed as before
|
||||
if (r.account === false) return { error: 'No LinkSpin account was found for your network username, so that spin link cannot be confirmed as yours.' };
|
||||
const sp = r.spins.find(x => x.code === code);
|
||||
if (!sp) return { error: 'That spin link is not one of yours. Use one of your own LinkSpin spin links (pick it under "Use one of my spin links").' };
|
||||
if (sp.paused) return { error: 'That spin link is paused on LinkSpin. Turn it back on there first, or pick another.' };
|
||||
if (!sp.destinations) return { error: 'That spin link has no active pages on LinkSpin yet. Add a page to it there first.' };
|
||||
return { spin: true, code };
|
||||
}
|
||||
// a LinkSpin link (tracked link or the member's spin link) carries the branch: s2 = the resharer's network username, s3 = the share code,
|
||||
// so LinkSpin Reports show which branch brought each click and sign-up. Other links are left exactly as the member wrote them.
|
||||
function withBranch(url, share, resharerName) {
|
||||
if (!share || share.step === 0) return url;
|
||||
let u; try { u = new URL(String(url)); } catch (e) { return url; }
|
||||
const host = u.hostname.toLowerCase().replace(/^www\./, ''); if (!lsHosts.has(host)) return url;
|
||||
if (resharerName) u.searchParams.set('s2', String(resharerName).slice(0, 40)); u.searchParams.set('s3', share.id);
|
||||
return u.toString();
|
||||
}
|
||||
function view() { return Object.assign({ on: on(), base: base(), partner: SITE }, st); }
|
||||
module.exports = { withBranch, init, ensureAd, sweep, clicks, dest, state, view, on, spins, checkSpin, _hosts: lsHosts, _reset: () => cache.clear() };
|
||||
@@ -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', 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,355 @@
|
||||
// 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.
|
||||
'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 = 1200; // seconds: the state cookie on a deliberate tap (time to sign in on the provider first, 2026-11-14)
|
||||
const BACK_AGE = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in
|
||||
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;
|
||||
}
|
||||
|
||||
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() } }
|
||||
|
||||
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 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(() => {}); } }
|
||||
|
||||
// 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;
|
||||
const peerName = NAMES[C.peer] || C.peer;
|
||||
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
|
||||
const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
|
||||
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)];
|
||||
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
|
||||
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')), clear);
|
||||
}
|
||||
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 ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
|
||||
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 = NAMES[aud] || 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())) { 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 and still has to finish it after signing in
|
||||
const pendingBack = req => !!cookies(req)['nsso.back'];
|
||||
|
||||
module.exports = { init, handle, page, enabled, pendingBack, 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 };
|
||||
@@ -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,81 @@
|
||||
// Promo kit (the VBB pattern, 2026-11-14): the ONE place the ViralAdSource 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 (Boost price + days on top). Copy rules: advertising, not income; nothing is
|
||||
// promised; no em dashes; no earnings caps; wallets = "SafePal or any other crypto wallet".
|
||||
// Creatives: public/art/kit/vas-<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 = { free: 'Post a free text ad', tree: 'Watch your ad travel', boost: 'Boost the source' };
|
||||
|
||||
function copy() {
|
||||
const boost = '$' + C.boost.usd + ' one-time Boost puts your ad on top of the reshare board for ' + C.boost.days + ' days';
|
||||
return {
|
||||
lines: [
|
||||
'Every ad has a source. Post a free text ad on ViralAdSource and watch who passes it on. {{LINK}}',
|
||||
'Post one free text ad, let people reshare it, and see its whole family tree: every branch, every step. {{LINK}}',
|
||||
'ViralAdSource: free text ads that travel by reshares. One network account, sign in with InstantAdPay or LinkSpin. {{LINK}}'
|
||||
],
|
||||
headlines: ['Every ad has a source', 'Watch your ad travel', 'See who passed your ad on', 'Your ad, branch by branch'],
|
||||
email: { subject: 'Watch your ad travel',
|
||||
body: ['Hi,', '', 'ViralAdSource lets you post a free text ad that anyone can reshare with their own link. Every reshare is a new branch, and you see the whole family tree of your ad: who passed it on, how far it went and what each branch brought in.', '',
|
||||
'Resharers are rewarded for results only, never for a bare share. Ad credits buy advertising, not income.', '', '{{LINK}}'].join('\n') },
|
||||
posts: [
|
||||
'Most ad sites give you a view count. ViralAdSource shows you the route: which reshare carried your ad furthest and which branch went quiet. Free to post.' + '\n\n{{LINK}}',
|
||||
'Post a free text ad, reshare the ones you like with your own link. ' + boost + '. Paid in POL with SafePal or any other crypto wallet.' + '\n\n{{LINK}}'
|
||||
]
|
||||
};
|
||||
}
|
||||
const NOTE = 'Ad credits buy advertising, not income. 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 => /^vas-[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 = 'vas-' + 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) : '';
|
||||
// the member's own page is their link (viraladsource.com/<username>); a wallet falls back to ?ref=
|
||||
const link = ref && !/^0x/i.test(ref) ? base() + '/' + encodeURIComponent(ref) : base() + '/' + (ref ? '?ref=' + encodeURIComponent(ref) : '');
|
||||
const q = ref ? '?ref=' + encodeURIComponent(ref) : '';
|
||||
const fill = s => s.split('{{LINK}}').join(link);
|
||||
const track = seg => netsites.tracked(C.siteId, C.siteId, { s1: ref, s2: seg });
|
||||
const t = copy();
|
||||
return {
|
||||
v: 1, site: C.site, name: C.siteName, updated: '2026-11-16', username: ref || null,
|
||||
tagline: 'Every ad has a source. Watch yours travel.',
|
||||
links: [
|
||||
{ key: 'page', label: 'Your page', url: link, tracked: track('') },
|
||||
{ key: 'boost', label: 'Boost', url: base() + '/boost' + q, tracked: track('boost') },
|
||||
{ key: 'ledger', label: 'Live ledger', url: base() + '/ledger' + q, tracked: track('ledger') }
|
||||
],
|
||||
linkTemplate: base() + '/{username}', trackedTemplate: netsites.tracked(C.siteId, C.siteId) + '&s1={username}',
|
||||
creatives: creatives().map(c => Object.assign({}, c, { html: '<a href="' + link + '" target="_blank" rel="noopener"><img src="' + c.url + '" width="' + c.w + '" height="' + c.h + '" alt="ViralAdSource"></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,121 @@
|
||||
// Trust pack (Marty 2026-11-14, standing for every network site): live ledger, contract proof, toasts, a Telegram photo card per sale.
|
||||
// - ledger(): every Boost (the Purchase events shop.js recorded) with its split read from the receipt: the resharer's cut (kind 6),
|
||||
// each sponsor level (kinds 1..5, with the person's place in the line), who was passed over, the reward pot slice and the company;
|
||||
// plus the sign-up rewards ledger (signup.js publicRows: name, amount, status, tx; never an email).
|
||||
// - contract(): live facts for /contract (owner, company, keeper, paused, split, pot, reward rules), cached 5 minutes.
|
||||
// - Telegram: one photo card per Boost 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/vas-proof-river.png', '/art/proof/vas-proof-ink.png'];
|
||||
const st = { posted: 0, skipped: 0, failed: 0, lastError: null };
|
||||
let C = null, shop = null, wire = null, signup = 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; signup = deps.signup; }
|
||||
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' : k === 6 ? 'resharer' : 'level ' + k;
|
||||
|
||||
// the split of one Boost: from its receipt when read, else from the Purchase event totals
|
||||
function split(x) {
|
||||
if (Array.isArray(x.pays) && x.pays.length) return x.pays;
|
||||
const out = [];
|
||||
if (x.resharer && x.resharerPaid && x.resharerPaid !== '0') out.push({ kind: 6, depth: 0, to: x.resharer, wei: x.resharerPaid });
|
||||
out.push({ kind: 0, depth: 0, to: lc(C.companyWallet), wei: String(x.companyPaid || '0') });
|
||||
return out;
|
||||
}
|
||||
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 a = x.adId ? store.ad(x.adId) : null; const dv = wire.boostView(x);
|
||||
let levelsWei = 0n; for (const p of split(x)) if (p.kind >= 1 && p.kind <= 5) { try { levelsWei += BigInt(p.wei); } catch (e) {} }
|
||||
return { kind: 'boost', 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, days: dv.days,
|
||||
usdCents: x.usdCents, weiPaid: x.weiPaid, potWei: x.potAdded || '0', ad: a ? { id: a.id, headline: a.headline } : null,
|
||||
resharer: x.resharer ? { to: x.resharer, name: nameLocal(x.resharer), wei: x.resharerPaid } : null,
|
||||
pays: split(x).map(p => ({ kind: p.kind, label: KIND(p.kind), depth: p.depth, to: p.to, name: p.to ? nameLocal(p.to) : null, wei: p.wei, failed: p.failed || undefined })),
|
||||
passedOver: (x.over || []).map(o => ({ depth: o.depth, name: nameLocal(o.who) || null, who: o.who })) };
|
||||
}).sort((a, b) => (b.at || 0) - (a.at || 0));
|
||||
let wei = 0n, pot = 0n, resh = 0n, cents = 0, boosts = 0;
|
||||
for (const x of rows()) { boosts += Number(x.qty) || 1; cents += Number(x.usdCents) || 0; try { wei += BigInt(x.weiPaid || 0); pot += BigInt(x.potAdded || 0); resh += BigInt(x.resharerPaid || 0); } catch (e) {} }
|
||||
const rw = signup ? signup.publicRows(lim) : [];
|
||||
return { contract: C.contractAddress || null, explorer: C.explorer, items: list.slice(0, lim), rewards: rw.map(r => Object.assign(r, { to: short(r.to) })),
|
||||
payoutsOn: C.reward.payouts, totals: { boosts, orders: list.length, usdCents: cents, weiPaid: wei.toString(), potWei: pot.toString(), resharerWei: resh.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, proposal: true,
|
||||
split: { resharerBps: C.split.resharerBps, potBps: C.split.potBps, levelBps: C.split.levelBps, maxDepth: C.split.maxDepth },
|
||||
reward: { cents: C.reward.cents, dailyCap: C.reward.dailyCap, payouts: C.reward.payouts }, boost: { usd: C.boost.usd, days: C.boost.days },
|
||||
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, potBalance, potFunded, potPaid] = await Promise.all(['owner', 'company', 'keeper', 'paused', 'totalOwed', 'orderCount', 'potBalance', 'potFunded', 'potPaid'].map(one));
|
||||
const r = await shop.liveRules();
|
||||
Object.assign(v, { owner: lc(owner), company: lc(company), keeper: lc(keeper), paused: !!paused, totalOwedWei: totalOwed.toString(), orderCount: Number(orderCount),
|
||||
pot: { balanceWei: potBalance.toString(), fundedWei: potFunded.toString(), paidWei: potPaid.toString() }, live: true, proposal: false, readAt: Date.now() });
|
||||
if (r) { v.split = { resharerBps: r.resharerBps, potBps: r.potBps, levelBps: r.levelBps, maxDepth: 20 }; v.reward.maxCents = r.rewardMaxCents; v.reward.chainDailyCap = r.rewardDailyCap; }
|
||||
} 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 a = x.adId ? store.ad(x.adId) : null;
|
||||
const lines = ['\u{1F30A} <b>ViralAdSource</b>', '\u{26A1} ' + esc(who(x.buyer)) + ' boosted ' + (a ? '"' + esc(a.headline) + '"' : 'a text ad') + ' · ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL)'];
|
||||
for (const p of split(x)) {
|
||||
if (p.kind === 0) lines.push('\u{1F3E6} ViralAdSource: ' + pol(p.wei) + ' POL');
|
||||
else if (p.kind === 6) lines.push('\u{1F33F} Resharer ' + esc(who(p.to)) + ': ' + pol(p.wei) + ' POL (the branch that sold it)');
|
||||
else lines.push((p.failed ? '⚠️ ' : '\u{1F4B8} ') + 'Level ' + p.kind + ': ' + pol(p.wei) + ' POL → ' + esc(who(p.to)) + (p.failed ? ' (bounced, waits in the contract to claim)' : ''));
|
||||
}
|
||||
if (x.potAdded && x.potAdded !== '0') lines.push('\u{1F4A7} Reward pot: +' + pol(x.potAdded) + ' POL');
|
||||
lines.push('Paid by the contract in this same transaction.');
|
||||
lines.push('\u{1F4CA} This week: ' + w.boosts + ' Boosts · ' + w.reshares + ' reshares · ' + 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, over: sp.over }); store.save(); } Object.assign(x, { pays: sp.pays, over: sp.over }); }
|
||||
// the branch that sold it
|
||||
if (rec.resharer) { const S = store.state(); const ov = (S.orderVia || {})[rec.buyer]; const s = ov ? store.share(ov.code) : null;
|
||||
if (s && s.owner === rec.resharer) { s.boosts = (s.boosts || 0) + (Number(rec.qty) || 1); store.saveShare(s); rec.share = s.id; store.save(); } }
|
||||
} 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('vastg:' + 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,43 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>An ad on ViralAdSource</title>
|
||||
<meta name="description" content="A text ad on ViralAdSource. Reshare it with your own link and grow a new branch.">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="An ad on ViralAdSource"><meta property="og:description" content="A text ad on ViralAdSource. Reshare it with your own link and grow a new branch."><meta property="og:url" content="https://viraladsource.com/s/">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap" style="padding-top:40px;padding-bottom:56px">
|
||||
<p class="kicker" id="chain">On ViralAdSource</p>
|
||||
<div id="adBox"><p class="muted">Loading the ad...</p></div>
|
||||
<div class="split" style="margin-top:28px">
|
||||
<div class="panel" id="reshareBox">
|
||||
<h2 style="font-size:28px">Pass it on</h2>
|
||||
<p class="muted" style="margin:8px 0 0">Reshare this ad with your own link. Your link is unique to you, so everything that comes through it is booked to your branch. A share alone is never paid: only verified results are.</p>
|
||||
<div id="reshareOut" style="margin-top:14px"></div>
|
||||
<div class="row" style="margin-top:14px"><button class="btn ink" id="reshareBtn" type="button">Reshare this ad</button><a class="btn" href="/rewards">How rewards work</a></div>
|
||||
<p id="status" class="note" hidden></p>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h2 style="font-size:28px">New to the network?</h2>
|
||||
<p class="muted" style="margin:8px 0 0">Join free with one account for every network site, then post your own ad here and watch it travel.</p>
|
||||
<div class="row" style="margin-top:14px"><a class="btn coral" id="joinBtn" href="/join">Join free</a><a class="btn" href="/my">I have an account</a></div>
|
||||
</div>
|
||||
</div>
|
||||
<section id="featured" hidden style="margin-top:32px"><h2 style="font-size:24px">Featured with credits</h2><div class="ads"></div></section>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/adpage.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,33 @@
|
||||
<!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 | ViralAdSource</title>
|
||||
<meta name="description" content="Admin.">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="Admin | ViralAdSource"><meta property="og:description" content="Admin."><meta property="og:url" content="https://viraladsource.com/admin">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap" style="padding-top:30px;padding-bottom:56px">
|
||||
<h1 style="font-size:36px">Admin</h1>
|
||||
<div class="row" style="margin-top:12px"><input type="text" id="tok" placeholder="admin token" style="max-width:320px"><button class="btn sm ink" id="go" type="button">Load</button></div>
|
||||
<section class="panel" style="margin-top:18px"><h2 style="font-size:22px">Status</h2><pre id="statusOut" style="white-space:pre-wrap;font-size:12px;max-height:420px;overflow:auto"></pre></section>
|
||||
<section class="panel" style="margin-top:18px"><h2 style="font-size:22px">Sign-ups (L2 checks)</h2><div class="tbl"><table><thead><tr><th>Id</th><th>Status</th><th>Email</th><th>Resharer</th><th>Checks</th><th>Action</th></tr></thead><tbody id="suRows"></tbody></table></div></section>
|
||||
<section class="panel" style="margin-top:18px"><h2 style="font-size:22px">Pending-rewards ledger</h2><div class="tbl"><table><thead><tr><th>Id</th><th>To</th><th>Kind</th><th>Cents</th><th>Status</th><th>Voucher</th></tr></thead><tbody id="rwRows"></tbody></table></div></section>
|
||||
<section class="panel" style="margin-top:18px" id="testBox"><h2 style="font-size:22px">Staging: mark a test member</h2><p class="muted">Staging only. Lets a wallet post and reshare without a real network account.</p>
|
||||
<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</button></div><p id="status" class="note" hidden></p></section>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/admin.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 185 KiB |
|
After Width: | Height: | Size: 75 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1,19 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="619.46 375.11 25.76 25.76" width="48" height="48"><g stroke-width="1.75" fill="none" stroke-linecap="round" stroke-linejoin="round"><g>
|
||||
|
||||
<rect x="622.464" y="378.106" fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" width="7.601" height="7.6" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<rect x="622.464" y="390.266" fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" width="7.601" height="7.6" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<rect x="634.624" y="378.106" fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" width="7.601" height="7.6" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<rect x="634.624" y="390.266" fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" width="7.601" height="7.6" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="626.265" y1="381.906" x2="626.265" y2="389.859" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="638.424" y1="381.906" x2="630.17" y2="381.906" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<polyline fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" points=" 638.424,394.066 638.424,390.368 638.424,385.812 " vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="626.265" y1="394.066" x2="634.119" y2="394.066" vector-effect="non-scaling-stroke" />
|
||||
</g>
|
||||
</g></svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,43 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="51.58 369.90 36.18 36.18" width="48" height="48"><g stroke-width="1.75" fill="none" stroke-linecap="round" stroke-linejoin="round"><g>
|
||||
|
||||
<rect x="61.888" y="389.337" fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" width="3.974" height="3.974" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="78.259" y1="383.479" x2="69.277" y2="383.479" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="75.967" y1="385.724" x2="69.277" y2="385.724" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<polyline fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" points=" 75.669,377.025 81.208,377.025 81.208,403.074 58.154,403.074 58.154,377.025 63.693,377.025 " vector-effect="non-scaling-stroke" />
|
||||
|
||||
<path fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" d=" M64.142,377.623c0,1.406,1.139,2.545,2.546,2.545h5.985c1.406,0,2.546-1.139,2.546-2.545v-1.945H64.142V377.623z" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<path fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" d=" M66.985,375.593c0-1.488,1.207-2.695,2.696-2.695c1.489,0,2.695,1.207,2.695,2.695" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="78.259" y1="390.104" x2="74.844" y2="390.104" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="72.599" y1="390.104" x2="69.277" y2="390.104" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="76.566" y1="392.349" x2="69.277" y2="392.349" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="73.572" y1="396.728" x2="69.277" y2="396.728" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="78.259" y1="396.728" x2="75.742" y2="396.728" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="71.7" y1="398.974" x2="69.277" y2="398.974" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="78.259" y1="398.974" x2="73.946" y2="398.974" vector-effect="non-scaling-stroke" />
|
||||
<g>
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="65.413" y1="396.411" x2="62.337" y2="399.487" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="62.336" y1="396.411" x2="65.413" y2="399.487" vector-effect="non-scaling-stroke" />
|
||||
</g>
|
||||
<g>
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="65.413" y1="383.124" x2="62.337" y2="386.2" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="62.336" y1="383.124" x2="65.413" y2="386.2" vector-effect="non-scaling-stroke" />
|
||||
</g>
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="66.985" y1="377.884" x2="72.376" y2="377.884" vector-effect="non-scaling-stroke" />
|
||||
</g>
|
||||
</g></svg>
|
||||
|
After Width: | Height: | Size: 3.4 KiB |
@@ -0,0 +1,27 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="114.92 368.80 38.37 38.37" width="48" height="48"><g stroke-width="1.75" fill="none" stroke-linecap="round" stroke-linejoin="round"><g>
|
||||
<g>
|
||||
|
||||
<path fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" d=" M143.658,391.748l-6.518,6.517c-0.576,0.576-1.509,0.576-2.086,0c-0.575-0.575-0.575-1.509,0-2.085l6.518-6.517" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<path fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" d=" M141.307,389.268l5.67-5.671c0.758-0.759,1.987-0.759,2.745,0c0.757,0.758,0.757,1.986,0.001,2.744l-5.671,5.671L141.307,389.268z " vector-effect="non-scaling-stroke" />
|
||||
|
||||
<polyline fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" points=" 146.329,384.187 144.082,384.188 139.046,389.222 " vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="134.076" y1="399.242" x2="135.054" y2="398.264" vector-effect="non-scaling-stroke" />
|
||||
</g>
|
||||
<g>
|
||||
|
||||
<polyline fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" points=" 142.139,393.66 142.139,403.074 117.923,403.074 117.923,379.23 " vector-effect="non-scaling-stroke" />
|
||||
|
||||
<polyline fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" points=" 124.257,372.898 142.139,372.898 142.139,385.65 " vector-effect="non-scaling-stroke" />
|
||||
</g>
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="136.178" y1="384.911" x2="125.001" y2="384.911" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="136.178" y1="388.264" x2="125.001" y2="388.264" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="133.99" y1="391.618" x2="125.001" y2="391.618" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<polygon fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" points=" 124.257,379.23 117.923,379.23 124.257,372.898 " vector-effect="non-scaling-stroke" />
|
||||
</g>
|
||||
</g></svg>
|
||||
|
After Width: | Height: | Size: 2.2 KiB |
@@ -0,0 +1,25 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="372.44 544.86 41.25 41.25" width="48" height="48"><g stroke-width="1.75" fill="none" stroke-linecap="round" stroke-linejoin="round"><g>
|
||||
|
||||
<circle fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" cx="382.254" cy="555.951" r="3.408" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<circle fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" cx="401.954" cy="551.798" r="3.94" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<circle fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" cx="392.584" cy="565.642" r="5.219" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<circle fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" cx="380.124" cy="574.374" r="2.45" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<circle fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" cx="396.204" cy="579.591" r="3.514" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<path fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" d=" M408.45,567.983c0,1.237-1.001,2.238-2.237,2.238c-1.234,0-2.235-1.001-2.235-2.238c0-1.233,1.001-2.235,2.235-2.235 C407.449,565.748,408.45,566.75,408.45,567.983z" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="395.278" y1="576.027" x2="393.939" y2="570.865" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="397.904" y1="566.556" x2="403.871" y2="567.583" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="399.646" y1="555.207" x2="395.566" y2="561.233" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="388.682" y1="561.981" x2="384.844" y2="558.38" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<line fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" x1="382.26" y1="572.877" x2="388.205" y2="568.71" vector-effect="non-scaling-stroke" />
|
||||
</g>
|
||||
</g></svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
@@ -0,0 +1,2 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="558.79 372.99 29.99 29.99" width="48" height="48"><g stroke-width="1.75" fill="none" stroke-linecap="round" stroke-linejoin="round"><path fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" d=" M577.008,378.97c0.718,1.557,1.962,2.833,3.453,3.533v1.009c0,5.161-2.519,9.978-6.672,12.943 c-4.152-2.966-6.671-7.782-6.671-12.943v-1.009c1.49-0.701,2.734-1.978,3.453-3.533H577.008 M579.325,375.99h-11.071 c0,2.039-1.653,4.117-3.69,4.117h-0.426v3.405c0,7.074,3.894,13.236,9.651,16.469c5.76-3.232,9.652-9.395,9.652-16.469v-3.405 h-0.426C580.978,380.107,579.325,378.029,579.325,375.99L579.325,375.99z" vector-effect="non-scaling-stroke" />
|
||||
<polyline vector-effect="non-scaling-stroke" fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" points="569.54,387.03 572.73,390.21 578.25,384.05"/></g></svg>
|
||||
|
After Width: | Height: | Size: 891 B |
@@ -0,0 +1,12 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="54.94 75.46 29.47 29.47" width="48" height="48"><g stroke-width="1.75" fill="none" stroke-linecap="round" stroke-linejoin="round"><g>
|
||||
|
||||
<path fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" d=" M76.722,81.38c1.788,0,3.237,1.45,3.237,3.238V98.7c0,1.788-1.449,3.238-3.237,3.238H62.64c-1.788,0-3.238-1.45-3.238-3.238V84.618 c0-1.788,1.45-3.238,3.238-3.238" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<path fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" d=" M79.959,84.618c0,1.788-1.449,3.237-3.237,3.237H62.64c-1.788,0-3.238-1.449-3.238-3.237" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<path fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" d=" M79.959,89.141c0,1.787-1.449,3.237-3.237,3.237h-4.854c-1.468,0-2.657,1.19-2.657,2.658c0,1.469,1.189,2.658,2.657,2.658h4.854 c1.788,0,3.237-1.449,3.237-3.237" vector-effect="non-scaling-stroke" />
|
||||
<circle fill="#FF9479" cx="71.865" cy="95.038" r="0.857" vector-effect="non-scaling-stroke" />
|
||||
|
||||
<rect x="62.74" y="78.464" fill="none" stroke="#FF9479" stroke-linecap="round" stroke-linejoin="round" width="13.881" height="5.996" vector-effect="non-scaling-stroke" />
|
||||
</g>
|
||||
</g></svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 262 KiB |
|
After Width: | Height: | Size: 438 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 80 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 652 KiB |
|
After Width: | Height: | Size: 825 KiB |
|
After Width: | Height: | Size: 6.6 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 80 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 650 KiB |
|
After Width: | Height: | Size: 831 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="34" height="34" viewBox="0 0 34 34"><rect width="34" height="34" rx="8" fill="#EAF6F4"/><circle cx="17" cy="8" r="5" fill="#C4371B"/><path d="M17 13 V20 M17 20 L8 29 M17 20 L26 29 M17 20 V30" stroke="#0B2730" stroke-width="2.4" fill="none" stroke-linecap="round"/></svg>
|
||||
|
After Width: | Height: | Size: 318 B |
|
After Width: | Height: | Size: 652 KiB |
|
After Width: | Height: | Size: 270 KiB |
|
After Width: | Height: | Size: 662 KiB |
|
After Width: | Height: | Size: 384 KiB |
@@ -0,0 +1,23 @@
|
||||
// Admin: status, the L2 sign-up checks (release / reject / recheck), the pending-rewards ledger, and (staging only) the test-member switch.
|
||||
// The token stays in this tab only (sessionStorage).
|
||||
(function () {
|
||||
const $ = VAS.$, esc = VAS.esc;
|
||||
let tok = ''; try { tok = sessionStorage.getItem('vas.admin') || ''; } catch (e) {}
|
||||
const H = () => ({ 'x-admin-token': tok, 'Content-Type': 'application/json' });
|
||||
const api = (p, body) => VAS.getJSON(p, body ? { method: 'POST', headers: H(), body: JSON.stringify(body) } : { headers: H() });
|
||||
async function load() {
|
||||
if (!tok) return;
|
||||
const s = await api('/api/admin/status'); $('statusOut').textContent = JSON.stringify(s, null, 2); $('testBox').hidden = !s.testSwitch;
|
||||
const su = await api('/api/admin/signups');
|
||||
$('suRows').innerHTML = (su.signups || []).map(x => '<tr><td class="mono">' + esc(x.id) + '</td><td>' + esc(x.status) + '</td><td>' + esc(x.email) + (x.confirmLink ? '<br><a href="' + esc(x.confirmLink) + '">staging confirm link</a>' : '') + '</td><td>' + esc(x.resharer || '')
|
||||
+ '</td><td style="font-size:12px">' + esc(JSON.stringify(x.checks || {})) + (x.fail.length ? '<br><b>fail:</b> ' + esc(x.fail.join(', ')) : '') + (x.hold.length ? '<br><b>hold:</b> ' + esc(x.hold.join(', ')) : '')
|
||||
+ '</td><td><button class="btn sm" data-a="release" data-id="' + esc(x.id) + '">Release</button> <button class="btn sm" data-a="reject" data-id="' + esc(x.id) + '">Reject</button> <button class="btn sm" data-a="recheck" data-id="' + esc(x.id) + '">Recheck</button></td></tr>').join('') || '<tr><td colspan="6" class="muted">none</td></tr>';
|
||||
const rw = await api('/api/admin/rewards');
|
||||
$('rwRows').innerHTML = (rw.rewards || []).map(r => '<tr><td class="mono">' + esc(r.id) + '</td><td>' + esc(r.toName || r.to) + '</td><td>' + esc(r.kind) + '</td><td>' + esc(r.cents) + '</td><td>' + esc(r.status)
|
||||
+ '</td><td class="mono" style="font-size:12px">' + (r.voucher ? 'signed, nonce ' + esc(String(r.voucher.nonce).slice(0, 10)) + '...' : esc(r.note || '')) + '</td></tr>').join('') || '<tr><td colspan="6" class="muted">none</td></tr>';
|
||||
}
|
||||
document.addEventListener('click', async e => { const b = e.target.closest('button[data-a]'); if (!b) return; const r = await api('/api/admin/signup', { id: b.dataset.id, action: b.dataset.a }); if (r.error) VAS.status(r.error, 'err'); load(); });
|
||||
$('go').onclick = () => { tok = $('tok').value.trim(); try { sessionStorage.setItem('vas.admin', tok); } catch (x) {} load(); };
|
||||
$('tGo').onclick = async () => { const r = await api('/api/admin/test-member', { address: $('tAddr').value.trim(), username: $('tName').value.trim() || undefined }); VAS.status(r.error || 'Marked as a test member.', r.error ? 'err' : 'ok'); };
|
||||
load();
|
||||
})();
|
||||
@@ -0,0 +1,26 @@
|
||||
// An ad through a reshare link (/s/<code>): the ad, whose branch it came through, "Reshare this ad" (the member's own unique link,
|
||||
// under this one) and "Join free" for people new to the network. The visit counts as a verified view for that branch once seen.
|
||||
(async function () {
|
||||
const $ = VAS.$, esc = VAS.esc;
|
||||
const code = (location.pathname.match(/^\/s\/([a-z0-9]{8})/) || [])[1];
|
||||
const d = await VAS.wire('share', code).catch(() => ({}));
|
||||
if (!d.ad) { $('adBox').innerHTML = '<p class="note err">' + esc(d.error || 'That ad is not running right now.') + ' <a href="/#board">See the board</a></p>'; $('reshareBox').hidden = true; return; }
|
||||
const sh = d.share || {};
|
||||
document.title = d.ad.headline + ' | ViralAdSource';
|
||||
$('chain').textContent = sh.step > 0 ? 'Reshared by @' + (sh.resharer || 'a member') + ' · step ' + sh.step + ' from the source' + (sh.owner ? ' (@' + sh.owner + ')' : '')
|
||||
: 'At the source' + (sh.owner ? ': @' + sh.owner + '\'s ad' : '');
|
||||
$('adBox').innerHTML = VAS.adCard(d.ad, { big: true, place: 'share', share: sh.code });
|
||||
VAS.featured($('featured'), d);
|
||||
const out = (url, note) => {
|
||||
$('reshareOut').innerHTML = '<div class="sharebox"><span>' + esc(url) + '</span><button class="btn sm" type="button" id="cp">Copy</button></div>' + (note ? '<p class="muted" style="font-size:14px;margin:8px 0 0">' + esc(note) + '</p>' : '');
|
||||
$('cp').onclick = () => VAS.copy(url, $('cp'));
|
||||
};
|
||||
if (d.mine) out(d.mine.url, d.mine.own ? 'This is your own ad: this is its source link.' : 'Your reshare link for this ad.');
|
||||
$('reshareBtn').onclick = async () => {
|
||||
const me = await VAS.getJSON('/api/me'); if (!me.signedIn) { location.href = '/my?back=' + encodeURIComponent(location.pathname); return; }
|
||||
const r = await VAS.post('/api/my/reshare', { adId: d.ad.id, from: sh.code });
|
||||
if (r.error) return VAS.status(r.error, 'err');
|
||||
out(r.url, r.own ? 'This is your own ad: share its source link.' : r.created ? 'Your new branch: step ' + r.step + ' from the source. Share this link anywhere.' : 'You already reshared this ad. Here is your link again.');
|
||||
VAS.status('');
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,29 @@
|
||||
// Boost page: the split (live from the contract, else the proposal), the live POL price, and the Buy button.
|
||||
(async function () {
|
||||
const $ = VAS.$;
|
||||
VAS.wire('other').catch(() => {});
|
||||
const c = await VAS.getConfig().catch(() => ({})); const sp = c.split || {}; const b = c.boost || {};
|
||||
const rows = [['Resharer whose branch sold it', VAS.pct(sp.resharerBps)], ['Reward pot (pays sign-up rewards only)', VAS.pct(sp.potBps)]]
|
||||
.concat((sp.levelBps || []).map((x, i) => ['Sponsor level ' + (i + 1), VAS.pct(x)]));
|
||||
const used = (sp.resharerBps || 0) + (sp.potBps || 0) + (sp.levelBps || []).reduce((t, x) => t + x, 0);
|
||||
rows.push(['Company (the rest, plus any level nobody qualifies for)', VAS.pct(10000 - used)]);
|
||||
$('splitRows').innerHTML = rows.map(r => '<tr><td>' + r[0] + '</td><td class="n">' + r[1] + '</td></tr>').join('') + (sp.live ? '' : '<tr><td colspan="2" class="muted">Proposed numbers, not final.</td></tr>');
|
||||
const live = !!(c.shop && c.shop.live);
|
||||
const qty = () => Number($('qty').value) || 1;
|
||||
async function price() {
|
||||
if (!live) { $('quote').textContent = 'Boosts open when the contract goes live.'; $('buy').disabled = true; return; }
|
||||
const q = await VASBuy.quote(qty()).catch(() => ({ error: 'x' }));
|
||||
$('quote').textContent = q.error ? 'price unavailable right now' : '$' + (b.usd * qty()) + ', about ' + VASBuy.fmtPol(q.wei, 2) + ' POL at today\'s price';
|
||||
}
|
||||
price(); $('qty').onchange = price;
|
||||
$('buy').onclick = async () => {
|
||||
$('buy').disabled = true;
|
||||
try {
|
||||
const me = await VAS.getJSON('/api/me'); if (!me.signedIn) { location.href = '/my'; return; }
|
||||
const before = ((await VAS.getJSON('/api/my')).boosts || []).length;
|
||||
const r = await VASBuy.run({ qty: qty(), done: async () => (((await VAS.getJSON('/api/my')).boosts || []).length > before) });
|
||||
VAS.status((r.recorded ? 'Your Boost is live: your ad is at the top of the reshare board.' : 'Paid and confirmed. Your Boost shows within a few minutes.') + (r.link ? ' Transaction: ' + r.link : ''), 'ok');
|
||||
} catch (e) { VAS.status(String(e && e.message || e).slice(0, 400), 'err'); }
|
||||
finally { $('buy').disabled = !live; }
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,39 @@
|
||||
// One-time Boosts through VASShop. The server builds the signed buy() call for the signed-in member (POST /api/my/order: the hub sponsor line + the resharer whose link they came through)
|
||||
// line voucher when the member's sponsor line is not on the contract yet); the member's own wallet sends it. The wallet that
|
||||
// pays must be the member's ViralAdSource account. After the transaction confirms the page waits for the watcher to record it.
|
||||
window.VASBuy = (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 VAS.getJSON('/api/quote?qty=' + (qty || 1)); }
|
||||
// o: { qty, done() -> bool (the Boost shows on /api/my), say(msg, cls) }
|
||||
async function run(o) {
|
||||
const say = o.say || VAS.status;
|
||||
const c = await VAS.getConfig();
|
||||
if (!c.shop || !c.shop.live) throw new Error('Boosts are not open right now.');
|
||||
const me = await VAS.getJSON('/api/me');
|
||||
if (!me.signedIn) throw new Error('Sign in on My ad tree first, so the Boost lands on your ad.');
|
||||
say('Connecting your wallet...');
|
||||
const addr = String(await VASWallet.activeAddress(await VASWallet.connect()) || '').toLowerCase();
|
||||
if (!addr) throw new Error('No wallet connected. Tap Boost again and pick SafePal or any other crypto wallet.');
|
||||
if (addr !== me.address) throw new Error('Your wallet is connected as ' + VAS.short(addr) + ', but your ViralAdSource account is ' + VAS.short(me.address) + '. A Boost goes to the wallet that pays, so switch your wallet app to ' + VAS.short(me.address) + ', or sign out and sign in with ' + VAS.short(addr) + '.');
|
||||
const od = await VAS.post('/api/my/order', { qty: o.qty || 1 });
|
||||
if (od.error) throw new Error(od.error);
|
||||
const value = BigInt(od.value);
|
||||
try { const bal = await VASWallet.balance(addr); if (bal < value) throw new Error('This wallet holds ' + fmtPol(bal) + ' POL. The Boost 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 VASWallet.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 VASWallet.waitTx(hash);
|
||||
if (r.status !== '0x1') throw new Error('The transaction did not go through, so nothing was charged except gas. ' + (link ? 'Details: ' + link : ''));
|
||||
VAS.post('/api/my/paid', {}).catch(() => {});
|
||||
say('Confirmed on Polygon. Your Boost shows on My page within about a minute.', 'ok');
|
||||
for (let i = 0; i < 72; i++) {
|
||||
await new Promise(res => setTimeout(res, 5000));
|
||||
if (i % 4 === 3) VAS.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 ViralAdSource watershed look (vas.css): ink header, rounded white panel, coral send, aqua 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)}}
|
||||
/* ViralAdSource watershed look */
|
||||
#scChat{--sc-ink:#0B2730;--sc-sub:#3D5D65;--sc-head:#0B2730;--sc-accent:#C4371B;--sc-me:#123845;--sc-bot:#EAF6F4;--sc-line:#CFE6E2;--sc-chip:#DDF3EF;--sc-chip-ink:#0B5A57;--sc-gold:#2BA39A;
|
||||
--sc-font:'IBM Plex Sans',system-ui,sans-serif;--sc-headfont:'Bricolage Grotesque',system-ui,sans-serif;--sc-cut:none}
|
||||
#scChat #scBtn{clip-path:none;border-radius:50%;box-shadow:0 6px 18px rgba(11,39,48,.35)}
|
||||
#scChat #scBtn:hover{background:#A8321A}
|
||||
#scChat #scPanel{clip-path:none;border-radius:18px;overflow:hidden}
|
||||
#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,125 @@
|
||||
// Shared page helpers (VAS namespace, the network common.js pattern): header, footer (legal, company line, the network line from the
|
||||
// hub), verified visits, ad cards, toasts of real events, small formatters. The watershed look lives in vas.css.
|
||||
window.VAS = (function () {
|
||||
let cfgP = null, vt = null;
|
||||
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);
|
||||
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"><circle cx="17" cy="8" r="5" fill="#C4371B"></circle><path d="M17 13 V20 M17 20 L8 29 M17 20 L26 29 M17 20 V30" stroke="#0B2730" stroke-width="2.4" fill="none" stroke-linecap="round"></path></svg>';
|
||||
function renderNav(active) {
|
||||
const h = document.createElement('header'); h.className = 'top';
|
||||
const links = [['/#how', 'How it spreads'], ['/#board', 'Reshare board'], ['/rewards', 'Rewards'], ['/boost', 'Boost'], ['/ledger', 'Ledger'], ['/my', 'My ad tree']];
|
||||
h.innerHTML = '<a class="skip" href="#main">Skip to content</a><div class="wrap"><a class="brand" href="/" aria-label="ViralAdSource, front page">' + MARK + '<span class="wm">ViralAd<b>Source</b></span></a>'
|
||||
+ '<nav class="links" aria-label="Main">' + links.map(l => '<a href="' + l[0] + '"' + (l[0] === active ? ' class="on" aria-current="page"' : '') + '>' + l[1] + '</a>').join('') + '</nav>'
|
||||
+ '<div class="row"><a class="btn sm" id="navSign" href="/my">Sign in</a><a class="btn sm ink" href="/my#post">Post your ad free</a></div></div>';
|
||||
document.body.prepend(h);
|
||||
getConfig().then(c => { if (c.staging) { const b = document.createElement('div'); b.className = 'stage-bar'; b.textContent = 'Staging copy for testing. Numbers marked as proposals are not final. No real payouts happen here.'; 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'; });
|
||||
}
|
||||
// a link through the click relay: share + placement + the visitor's verified token once their visit has verified
|
||||
const goHref = (id, p, s) => '/go/' + id + '?p=' + encodeURIComponent(p || 'site') + (s ? '&s=' + s : '') + (vt ? '&v=' + vt : '');
|
||||
function decorate() { document.querySelectorAll('a[data-go]').forEach(a => { a.href = goHref(a.dataset.go, a.dataset.p, a.dataset.s); }); }
|
||||
// an ad card. o = { place, share, big, extra (html) }
|
||||
function adCard(t, o) {
|
||||
o = o || {};
|
||||
const tags = [];
|
||||
if (t.boosted) tags.push('<span class="chip coral">Boosted</span>');
|
||||
if (t.credit) tags.push('<span class="chip">Featured with credits</span>');
|
||||
if (t.rank) tags.push('<span class="chip grey">#' + t.rank + '</span>');
|
||||
return '<article class="ad' + (t.boosted ? ' boosted' : '') + (t.credit ? ' credit' : '') + (o.big ? ' big' : '') + '">'
|
||||
+ '<div class="tag"><span>' + tags.join(' ') + '</span><span>' + n(t.reshares) + ' reshare' + (t.reshares === 1 ? '' : 's') + '</span></div>'
|
||||
+ '<h3>' + esc(t.headline) + '</h3><p>' + esc(t.line1) + (t.line2 ? ' ' + esc(t.line2) : '') + '</p>'
|
||||
+ '<div class="foot"><a class="visit" data-go="' + t.id + '" data-p="' + esc(o.place || 'card') + '"' + (o.share ? ' data-s="' + esc(o.share) + '"' : '') + ' target="_blank" rel="noopener sponsored" href="' + goHref(t.id, o.place, o.share) + '">Visit ' + esc(t.host) + '</a>'
|
||||
+ '<span class="muted">' + esc(t.owner) + '</span></div>' + (o.extra || '') + '</article>';
|
||||
}
|
||||
// the page's data and its verified visit: ads come with a ticket; after visitSeconds of the page being visible the visit is sent once
|
||||
async function wire(page, s) {
|
||||
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) + (s ? '&s=' + encodeURIComponent(s) : '') + (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('vas:verified', { detail: r })); }
|
||||
}, 500);
|
||||
document.addEventListener('visibilitychange', () => { last = Date.now(); });
|
||||
}
|
||||
return d;
|
||||
}
|
||||
function featured(el, d) { if (!el) return; const f = d.featured || []; el.hidden = !f.length; if (f.length) el.querySelector('.ads').innerHTML = f.map(t => adCard(t, { place: 'credit' })).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'], ['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: 'viraladsource', name: 'ViralAdSource', url: 'https://viraladsource.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 === 'viraladsource'
|
||||
? '<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 === 'viraladsource') ? l : l.concat([HERE])); }).catch(() => {});
|
||||
}
|
||||
function renderFooter() {
|
||||
const f = document.createElement('footer'); f.className = 'foot';
|
||||
f.innerHTML = '<div class="wrap"><p><b>ViralAdSource</b>: every ad has a source. Ad credits buy advertising, not income. Nothing is promised.</p>'
|
||||
+ '<p><a href="/">Front page</a> · <a href="/#how">How it spreads</a> · <a href="/rewards">Rewards</a> · <a href="/my">My ad tree</a> · <a href="/boost">Boost</a> · <a href="/promote">Promote</a></p>'
|
||||
+ '<p><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=viraladsource" target="_blank" rel="noopener">Support</a></p>'
|
||||
+ '<p>TrustClickz · 615 Green Valley Drive, Moody, AL 35004</p><p class="netline"></p></div>';
|
||||
document.body.appendChild(f);
|
||||
netLine(f.querySelector('.netline'));
|
||||
toasts();
|
||||
}
|
||||
let toastsOn = false;
|
||||
function toasts() {
|
||||
if (toastsOn) 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 === 'boost') { el.href = '/ledger'; el.innerHTML = '<b>' + who(c) + ' boosted an ad</b><br><span>' + (c.resharer ? 'through @' + esc(c.resharer) + '\'s branch, paid in the same transaction' : 'split on chain by the contract') + '</span>'; }
|
||||
else if (c.kind === 'reshare') { el.href = '/#board'; el.innerHTML = '<b>' + who(c) + ' reshared an ad</b><br><span>a new branch, step ' + esc(c.step) + ' from the source</span>'; }
|
||||
else { el.href = '/#board'; el.innerHTML = '<b>' + who(c) + ' posted a new ad</b><br><span>' + esc(c.headline) + '</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 link above to copy it'; } } }
|
||||
return { MARK, $, esc, getConfig, short, framed, status, getJSON, post, n, pct, usd, renderNav, renderFooter, adCard, wire, featured, decorate, goHref, polOf, when, copy };
|
||||
})();
|
||||
// every page: header, footer and the numbers from /api/config (proposals are labelled as proposals)
|
||||
(function () {
|
||||
const boot = () => {
|
||||
VAS.renderNav(document.body.dataset.nav || ''); VAS.renderFooter();
|
||||
VAS.getConfig().then(c => {
|
||||
const sp = c.split || {}, rw = c.reward || {}, cr = c.credits || {}, b = c.boost || {};
|
||||
const prop = sp.live ? '' : '(proposal)';
|
||||
const lv = sp.levelBps || []; const lvTxt = lv.length ? (lv.every(x => x === lv[0]) ? lv.length + ' x ' + VAS.pct(lv[0]) : lv.map(VAS.pct).join(' / ')) : 'none';
|
||||
const tier = (rw.tiers || [])[0] || {};
|
||||
const V = { cut: VAS.pct(sp.resharerBps), pot: VAS.pct(sp.potBps), levels: lvTxt, signup: VAS.usd(rw.cents), cap: String(rw.dailyCap), lockDays: String(tier.lockDays || 14),
|
||||
creditsPer: String(cr.per), creditsViews: String(cr.views), boostDays: String(b.days), boostUsd: '$' + b.usd, headline: String((c.ad || {}).headline || 60),
|
||||
proposalTag: prop, proposalNote: sp.live ? '' : 'The percentages and amounts shown are proposals and are not final yet.',
|
||||
payoutsNote: rw.payouts ? '' : 'Sign-up reward payouts are switched off for now: verified rewards wait in the pending ledger.' };
|
||||
document.querySelectorAll('[data-cfg]').forEach(el => { const k = el.dataset.cfg; if (V[k] != null) el.textContent = V[k]; });
|
||||
}).catch(() => {});
|
||||
};
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
|
||||
})();
|
||||
@@ -0,0 +1,17 @@
|
||||
// Contract page: live facts from /api/contract (read from Polygon, cached 5 minutes), or the proposed rules before it is deployed.
|
||||
(async function () {
|
||||
const el = VAS.$('facts'); const esc = VAS.esc;
|
||||
const d = await VAS.getJSON('/api/contract').catch(() => ({}));
|
||||
const ex = d.explorer || 'https://polygonscan.com';
|
||||
const addr = (a, note) => (a ? '<a class="mono" href="' + esc(ex) + '/address/' + esc(a) + '" target="_blank" rel="noopener">' + esc(a) + '</a>' : '<span class="muted">not deployed yet</span>') + (note ? '<br><span class="muted" style="font-size:13px">' + note + '</span>' : '');
|
||||
const sp = d.split || {}; const lv = (sp.levelBps || []).map(VAS.pct).join(' / ');
|
||||
const rows = [
|
||||
['Contract', addr(d.address, 'VASShop on Polygon' + (d.proposal ? '. Not deployed: the numbers below are proposals.' : ''))],
|
||||
['Owner', addr(d.owner, 'Marty\'s Tangem hardware wallet. It can pause, set future prices and percentages, and change the keeper. It cannot take the reward pot.')],
|
||||
['Split of each Boost', 'Resharer ' + VAS.pct(sp.resharerBps) + ' · reward pot ' + VAS.pct(sp.potBps) + ' · sponsor levels ' + esc(lv) + ' · company the rest'],
|
||||
['Sign-up reward', VAS.usd(d.reward && d.reward.cents) + ' in POL, up to ' + esc(d.reward && d.reward.dailyCap) + ' a day per wallet' + (d.reward && !d.reward.payouts ? ' (payouts switched off for now)' : '')],
|
||||
['Reward pot', d.live && d.pot ? VAS.polOf(d.pot.balanceWei) + ' POL now · ' + VAS.polOf(d.pot.fundedWei) + ' POL in · ' + VAS.polOf(d.pot.paidWei) + ' POL paid out' : '<span class="muted">' + esc(d.error || 'not deployed yet') + '</span>'],
|
||||
['Sales', d.live ? (d.paused ? '<b>Paused</b>' : 'Open') + ' · ' + VAS.n(d.orderCount) + ' orders' : '<span class="muted">not open yet</span>']
|
||||
];
|
||||
el.innerHTML = rows.map(r => '<tr><th>' + r[0] + '</th><td>' + r[1] + '</td></tr>').join('');
|
||||
})();
|
||||
@@ -0,0 +1,14 @@
|
||||
// Front page: the reshare board, credit-featured ads, today's numbers and the PolHunter embed (hunters' visits never count).
|
||||
(async function () {
|
||||
const $ = VAS.$;
|
||||
const d = await VAS.wire('front').catch(() => ({}));
|
||||
const t = d.today || {};
|
||||
$('todayStats').innerHTML = [[t.ads, 'ads running'], [t.reshares, 'reshares today'], [t.views, 'verified views today'], [t.vclicks, 'verified clicks today']]
|
||||
.map(x => '<div class="stat"><b>' + VAS.n(x[0]) + '</b><span>' + x[1] + '</span></div>').join('');
|
||||
const b = d.board || [];
|
||||
$('boardAds').innerHTML = b.length ? b.map(x => VAS.adCard(x, { place: 'board', extra: '<a class="btn sm" style="margin-top:8px" href="/a/' + x.id + '">Open and reshare</a>' })).join('')
|
||||
: '<p class="muted">No ads yet. <a href="/my#post">Post the first one free</a>.</p>';
|
||||
VAS.featured($('featured'), d);
|
||||
// PolHunter mission embed (the network pattern; the mission is saved inactive until go-live)
|
||||
const ph = document.createElement('script'); ph.async = true; ph.src = 'https://polhunter.com/embed.js'; ph.setAttribute('data-site', 'viraladsource'); $('phEmbed').appendChild(ph);
|
||||
})();
|
||||
@@ -0,0 +1,20 @@
|
||||
// Join the network free (/join) and confirm the email (/confirm?t=). The join is booked to the reshare link the visitor came through.
|
||||
(async function () {
|
||||
const $ = VAS.$;
|
||||
if ($('joinForm')) {
|
||||
const f = await VAS.getJSON('/api/join/form');
|
||||
if (f.via && f.via.resharer) $('viaNote').textContent = 'You came through @' + f.via.resharer + '\'s reshare of "' + f.via.headline + '". One free account for every network site.';
|
||||
$('joinForm').addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
const r = await VAS.post('/api/join', { email: $('email').value.trim(), username: $('username').value.trim(), form: f.form });
|
||||
if (r.error) return VAS.status(r.error, 'err');
|
||||
$('joinForm').hidden = true;
|
||||
VAS.status(r.mailed ? 'Check your inbox: open the link we sent to confirm your email.' : 'Thanks. This is the staging copy, so no email is sent: the confirm link is on the admin page for testing.', 'ok');
|
||||
});
|
||||
} else {
|
||||
const t = new URLSearchParams(location.search).get('t') || '';
|
||||
const r = await VAS.post('/api/confirm', { t });
|
||||
if (r.error) return VAS.status(r.error, 'err');
|
||||
VAS.status('Your email is confirmed. Welcome to the network. Sign in with your network account to post your own ad.', 'ok');
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,22 @@
|
||||
// Live ledger: every Boost with its split (resharer, sponsor levels, pot, company) and every sign-up reward, refreshed every 30 s.
|
||||
(function () {
|
||||
const $ = VAS.$, esc = VAS.esc; const pol = w => VAS.polOf(w) + ' POL';
|
||||
const who = (a, nm) => nm ? '@' + esc(nm) : '<span class="mono">' + esc(VAS.short(a || '')) + '</span>';
|
||||
async function load() {
|
||||
const d = await VAS.getJSON('/api/ledger?n=100').catch(() => null); if (!d || !d.items) return;
|
||||
const ex = d.explorer || 'https://polygonscan.com'; const t = d.totals || {};
|
||||
$('ledStats').innerHTML = [[VAS.n(t.boosts), 'Boosts on chain'], [pol(t.resharerWei), 'paid to resharers'], [pol(t.potWei), 'added to the reward pot'],
|
||||
[VAS.n((d.rewards || []).filter(r => r.status === 'paid').length), 'sign-up rewards paid']].map(x => '<div class="stat"><b>' + x[0] + '</b><span>' + x[1] + '</span></div>').join('');
|
||||
const tx = h => h ? '<a href="' + esc(ex) + '/tx/' + esc(h) + '" target="_blank" rel="noopener">verify</a>' : '';
|
||||
if (d.items.length) $('rows').innerHTML = d.items.map(r => {
|
||||
const lv = (r.pays || []).filter(p => p.kind >= 1 && p.kind <= 5).map(p => 'L' + p.kind + ' ' + pol(p.wei) + ' ' + who(p.to, p.name)).join('<br>') || '<span class="muted">none qualified</span>';
|
||||
const co = (r.pays || []).find(p => p.kind === 0);
|
||||
return '<tr><td>' + VAS.when(r.at) + '</td><td>' + who(r.buyer, r.buyerName) + '</td><td class="n">' + VAS.usd(r.usdCents) + '<br>' + pol(r.weiPaid) + '</td><td>'
|
||||
+ (r.resharer ? who(r.resharer.to, r.resharer.name) + '<br>' + pol(r.resharer.wei) : '<span class="muted">none</span>') + '</td><td>' + lv + '</td><td class="n">' + pol(r.potWei) + '</td><td class="n">' + (co ? pol(co.wei) : '') + '</td><td>' + tx(r.tx) + '</td></tr>';
|
||||
}).join('');
|
||||
$('payNote').textContent = d.payoutsOn ? '' : 'Payouts are switched off for now: verified rewards wait here as pending until the amounts are confirmed.';
|
||||
if ((d.rewards || []).length) $('rrows').innerHTML = d.rewards.map(r => '<tr><td>' + VAS.when(r.at) + '</td><td>' + (r.name ? '@' + esc(r.name) : esc(r.to)) + '</td><td>' + (r.kind === 'tier' ? 'tier bonus' : 'new member') + '</td><td class="n">' + VAS.usd(r.cents) + '</td><td><span class="chip' + (r.status === 'paid' ? '' : ' grey') + '">' + esc(r.status) + '</span>'
|
||||
+ (r.unlockAt && r.unlockAt > Date.now() ? '<br><span class="muted" style="font-size:13px">withdrawable ' + VAS.when(r.unlockAt) + '</span>' : '') + '</td><td>' + tx(r.tx) + '</td></tr>').join('');
|
||||
}
|
||||
VAS.wire('other').catch(() => {}); load(); setInterval(load, 30000);
|
||||
})();
|
||||
@@ -0,0 +1,67 @@
|
||||
// My ad tree (the member dashboard): sign in (network account through the hub, or wallet), the free ad with the spin-link picker,
|
||||
// the ad's family tree (branch, step, reshares under it, views, clicks, sign-ups, Boosts), the ads I reshared, credits and rewards.
|
||||
(async function () {
|
||||
const $ = VAS.$, esc = VAS.esc;
|
||||
VAS.wire('other').catch(() => {});
|
||||
const c = await VAS.getConfig().catch(() => ({}));
|
||||
const me = await VAS.getJSON('/api/me');
|
||||
const back = new URLSearchParams(location.search).get('back');
|
||||
if (!me.signedIn) {
|
||||
try { const ss = await VAS.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 { VAS.status('Check your wallet for the sign-in message.', '', 'status'); await VASWallet.signIn(); location.href = back && /^\/s\/[a-z0-9]{8}$/.test(back) ? back : '/my'; }
|
||||
catch (e) { VAS.status(String(e && e.message || e).slice(0, 300), 'err'); }
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (back && /^\/s\/[a-z0-9]{8}$/.test(back)) { location.replace(back); return; }
|
||||
$('dash').hidden = false;
|
||||
$('logout').onclick = async () => { await VAS.post('/api/auth/logout'); location.reload(); };
|
||||
$('logoutAll').onclick = async () => { $('logoutAll').disabled = true; await VAS.post('/api/auth/logout-everywhere'); location.reload(); };
|
||||
|
||||
// spin-link picker: only the member's own LinkSpin spin links (LinkSpin confirms again on every save)
|
||||
let spins = null;
|
||||
$('loadSpins').onclick = async () => {
|
||||
const box = $('spinList'); box.innerHTML = '<p class="muted" style="margin:0;padding:10px 12px;font-size:14px">Asking LinkSpin for your spin links...</p>';
|
||||
const r = await VAS.getJSON('/api/my/spins').catch(() => ({ error: 'LinkSpin did not answer. Try again in a minute.' }));
|
||||
if (r.error) { box.innerHTML = '<p class="note err" style="margin:8px">' + esc(r.error) + '</p>'; return; }
|
||||
spins = r.spins || [];
|
||||
if (!r.account) { box.innerHTML = '<p style="margin:0;padding:10px 12px;font-size:14px">No LinkSpin account was found for your network username yet. <a href="https://linkspin.app" target="_blank" rel="noopener">Open LinkSpin</a></p>'; return; }
|
||||
if (!spins.length) { box.innerHTML = '<p style="margin:0;padding:10px 12px;font-size:14px">You have no spin links yet. Make one on <a href="https://linkspin.app/links" target="_blank" rel="noopener">LinkSpin</a>, then pick it here.</p>'; return; }
|
||||
box.innerHTML = spins.map((x, i) => '<button type="button" data-i="' + i + '"' + (x.paused || !x.destinations ? ' disabled' : '') + (x.url === $('link').value ? ' class="on"' : '') + '>' + esc(x.name || x.code) + ' <span>' + (x.paused ? 'paused' : x.destinations + ' page' + (x.destinations === 1 ? '' : 's')) + '</span></button>').join('');
|
||||
box.querySelectorAll('button[data-i]').forEach(b => { b.onclick = () => { const x = spins[Number(b.dataset.i)]; $('link').value = x.url; box.querySelectorAll('button').forEach(y => y.classList.remove('on')); b.classList.add('on'); $('track').checked = false; VAS.status('Spin link picked. Save your ad to use it.', 'ok'); }; });
|
||||
};
|
||||
$('adForm').addEventListener('submit', async e => {
|
||||
e.preventDefault(); $('saveAd').disabled = true;
|
||||
const r = await VAS.post('/api/my/ad', { headline: $('headline').value, line1: $('line1').value, line2: $('line2').value, link: $('link').value.trim(), track: $('track').checked });
|
||||
$('saveAd').disabled = false;
|
||||
if (r.error) return VAS.status(r.error, 'err');
|
||||
VAS.status(r.created ? 'Your ad is live. Share your source link below: every reshare grows a branch.' : 'Saved.', 'ok'); load();
|
||||
});
|
||||
$('copySource').onclick = () => VAS.copy($('sourceUrl').textContent, $('copySource'));
|
||||
|
||||
async function load() {
|
||||
const d = await VAS.getJSON('/api/my'); if (d.error) return VAS.status(d.error, 'err');
|
||||
$('who').innerHTML = 'Signed in as ' + (d.username ? '@' + esc(d.username) : '<span class="mono">' + esc(VAS.short(d.address)) + '</span>') + (d.netVerified ? ' · network member' : ' · <b>not found in the network yet</b>: sign in with your network account to post and reshare') + (d.test ? ' · <span class="chip gold">staging test member</span>' : '');
|
||||
const a = d.ad, t = d.tree;
|
||||
if (a) {
|
||||
$('adTitle').textContent = 'My ad'; $('headline').value = a.headline; $('line1').value = a.line1; $('line2').value = a.line2 || ''; $('link').value = a.link; $('track').checked = a.track !== false; $('saveAd').textContent = 'Save changes';
|
||||
$('treeChip').textContent = a.status + (a.boostedUntil && a.boostedUntil > Date.now() ? ' · boosted until ' + VAS.when(a.boostedUntil) : '');
|
||||
}
|
||||
if (d.source) { $('sourceBox').hidden = false; $('sourceUrl').textContent = d.source.url; }
|
||||
const cr = d.credits || {}, rw = d.rewards || {};
|
||||
$('myStats').innerHTML = [[t ? t.totals.shares : 0, 'reshares of my ad'], [t ? t.totals.reach : 0, 'furthest step'], [a ? a.views : 0, 'verified views'], [a ? a.vclicks : 0, 'verified clicks'], [cr.balance, 'ad credits']].map(x => '<div class="stat"><b>' + VAS.n(x[0]) + '</b><span>' + x[1] + '</span></div>').join('');
|
||||
if (t && t.rows && t.rows.length) {
|
||||
$('treeStats').innerHTML = [[t.root.views, 'views at the source'], [t.totals.views, 'views through branches'], [t.totals.signups, 'sign-ups through branches'], [t.totals.boosts, 'Boosts through branches']].map(x => '<div class="stat"><b>' + VAS.n(x[0]) + '</b><span>' + x[1] + '</span></div>').join('');
|
||||
$('treeRows').innerHTML = t.rows.map(r => '<tr class="' + (r.step > 1 ? 'sub' : '') + '" style="--d:' + (r.step - 1) + '"><td>' + esc(r.who) + '</td><td class="n">' + r.step + '</td><td class="n">' + VAS.n(r.under) + '</td><td class="n">' + VAS.n(r.views) + '</td><td class="n">' + VAS.n(r.clicks) + '</td><td class="n">' + VAS.n(r.signups) + '</td><td class="n">' + VAS.n(r.boosts) + '</td></tr>').join('');
|
||||
}
|
||||
if ((d.reshares || []).length) $('myShares').innerHTML = d.reshares.map(s => '<tr><td>' + esc(s.headline || 'ad #' + s.adId) + (s.owner ? '<br><span class="muted" style="font-size:13px">by @' + esc(s.owner) + '</span>' : '') + (s.live ? '' : ' <span class="chip grey">not running</span>') + '</td><td class="n">' + s.step + '</td><td class="n">' + VAS.n(s.views) + '</td><td class="n">' + VAS.n(s.clicks) + '</td><td class="n">' + VAS.n(s.signups) + '</td><td class="n">' + VAS.n(s.boosts) + '</td><td><button class="btn sm" type="button" data-copy="' + esc(s.url) + '">Copy link</button></td></tr>').join('');
|
||||
document.querySelectorAll('button[data-copy]').forEach(b => { b.onclick = () => VAS.copy(b.dataset.copy, b); });
|
||||
let earnedWei = 0n; try { earnedWei = BigInt((d.earned || {}).wei || 0); } catch (e) {}
|
||||
$('rewardStats').innerHTML = [[VAS.n(cr.balance), 'ad credits to spend'], [VAS.n(cr.nextAt), 'branch views to the next ' + VAS.n(cr.per) + ' credits'], [VAS.usd(rw.pendingCents), 'sign-up rewards pending'], [VAS.polOf(earnedWei.toString()) + ' POL', 'paid to me by the contract']].map(x => '<div class="stat"><b>' + x[0] + '</b><span>' + x[1] + '</span></div>').join('');
|
||||
$('rewardNote').textContent = rw.payoutsOn ? '' : 'Sign-up reward payouts are switched off for now. Verified rewards wait here as pending until the amounts are confirmed.';
|
||||
if ((rw.items || []).length) $('rewardRows').innerHTML = rw.items.map(r => '<tr><td>' + VAS.when(r.at) + '</td><td>' + (r.kind === 'tier' ? 'Tier bonus' : 'New member through my link') + '</td><td class="n">' + VAS.usd(r.cents) + '</td><td>' + esc(r.status) + (r.unlockAt && r.unlockAt > Date.now() ? ' (withdrawable ' + VAS.when(r.unlockAt) + ')' : '') + '</td></tr>').join('');
|
||||
}
|
||||
load();
|
||||
})();
|
||||
@@ -0,0 +1,15 @@
|
||||
// Promote page: the promo kit from /api/promo-kit with the member's network username in every link.
|
||||
(async function () {
|
||||
const $ = VAS.$, esc = VAS.esc;
|
||||
let u = new URLSearchParams(location.search).get('u') || '';
|
||||
if (!u) { const me = await VAS.getJSON('/api/me').catch(() => ({})); if (me.signedIn && me.username) u = me.username; }
|
||||
$('kitUser').value = u;
|
||||
async function show() {
|
||||
const k = await VAS.getJSON('/api/promo-kit?u=' + encodeURIComponent($('kitUser').value.trim().replace(/^@/, '')));
|
||||
$('kit').innerHTML = '<section class="panel"><h2 style="font-size:24px">Your links</h2>' + k.links.map(l => '<p><b>' + esc(l.label) + '</b><br><span class="mono" style="word-break:break-all">' + esc(l.tracked || l.url) + '</span></p>').join('') + '</section>'
|
||||
+ '<section class="panel" style="margin-top:18px"><h2 style="font-size:24px">Lines to post</h2>' + k.lines.map(x => '<p>' + esc(x) + '</p>').join('') + '<h3>Email</h3><p><b>' + esc(k.email.subject) + '</b></p><p style="white-space:pre-wrap">' + esc(k.email.body) + '</p></section>'
|
||||
+ (k.creatives.length ? '<section class="panel" style="margin-top:18px"><h2 style="font-size:24px">Creatives</h2><div class="row">' + k.creatives.map(c => '<figure style="margin:0"><img src="' + esc(c.url) + '" width="' + Math.min(c.w, 300) + '" alt="' + esc(c.angleLabel) + '"><figcaption class="muted" style="font-size:13px">' + esc(c.label) + ' ' + c.w + 'x' + c.h + '</figcaption></figure>').join('') + '</div></section>' : '')
|
||||
+ '<p class="muted">' + esc(k.note) + '</p>';
|
||||
}
|
||||
$('kitUser').addEventListener('change', show); show();
|
||||
})();
|
||||
@@ -0,0 +1,2 @@
|
||||
// Static pages: header, footer and the live numbers come from common.js; the visit is a plain verified visit.
|
||||
VAS.wire('other').catch(() => {});
|
||||
@@ -0,0 +1,115 @@
|
||||
/* ViralAdSource "watershed" look (approved mockup 2026-11-16, canvas 2XuFAog3KEiuXbfEvVvTZk): aqua ground, deep ink, coral source,
|
||||
teal streams. Bricolage Grotesque headlines, IBM Plex Sans body, IBM Plex Mono figures. Distinct from every other network site. */
|
||||
:root{--aqua:#EAF6F4;--ink:#0B2730;--ink2:#123845;--ink3:#23444D;--muted:#3D5D65;--line:#CFE6E2;--line2:#E3EFED;--teal:#0B5A57;--teal2:#2BA39A;--mint:#8FCFC7;
|
||||
--mist:#B9DCD7;--coral:#C4371B;--coral2:#FF9479;--paper:#FFFFFF;--pale:#F6FBFA;--chip:#DDF3EF;--warn:#8A4B00;--ok:#0B5A57;--bad:#A3281A;
|
||||
--h:'Bricolage Grotesque',system-ui,sans-serif;--b:'IBM Plex Sans',system-ui,sans-serif;--m:'IBM Plex Mono',ui-monospace,monospace}
|
||||
*{box-sizing:border-box}
|
||||
html{scroll-behavior:smooth}
|
||||
body{margin:0;background:var(--aqua);color:var(--ink);font-family:var(--b);font-size:17px;line-height:1.55;-webkit-text-size-adjust:100%}
|
||||
a{color:var(--teal)}a:hover{color:var(--ink)}
|
||||
img{max-width:100%}
|
||||
[hidden]{display:none!important}
|
||||
.wrap{max-width:1240px;margin:0 auto;padding:0 24px}
|
||||
@media (max-width:600px){.wrap{padding:0 16px}}
|
||||
h1,h2,h3{font-family:var(--h);letter-spacing:-.01em;margin:0;text-wrap:balance}
|
||||
h1{font-weight:800;font-size:clamp(38px,6vw,62px);line-height:1.02;letter-spacing:-.02em}
|
||||
h2{font-weight:800;font-size:clamp(30px,4.2vw,42px);line-height:1.08}
|
||||
h3{font-family:var(--b);font-weight:600;font-size:21px}
|
||||
.kicker{margin:0 0 14px;font-family:var(--m);font-size:13px;letter-spacing:.14em;text-transform:uppercase;color:var(--teal)}
|
||||
.lead{font-size:19px;color:var(--ink3);max-width:600px;margin:20px 0 0}
|
||||
.muted{color:var(--muted)}.mono{font-family:var(--m)}
|
||||
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:48px;padding:0 22px;border-radius:12px;border:1.5px solid var(--ink);background:transparent;color:var(--ink);font:600 16px var(--b);text-decoration:none;cursor:pointer}
|
||||
.btn:hover{background:var(--chip);color:var(--ink)}
|
||||
.btn.ink{background:var(--ink);color:#fff;border-color:var(--ink)}.btn.ink:hover{background:var(--ink2)}
|
||||
.btn.coral{background:var(--coral);border-color:var(--coral);color:#fff}.btn.coral:hover{background:#A8321A}
|
||||
.btn.sm{min-height:40px;padding:0 14px;font-size:14px;border-radius:10px}
|
||||
.btn[disabled]{opacity:.5;cursor:not-allowed}
|
||||
.row{display:flex;flex-wrap:wrap;gap:12px;align-items:center}
|
||||
/* header */
|
||||
header.top{background:#fff;border-bottom:1px solid var(--line);position:relative;z-index:5}
|
||||
header.top .wrap{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px 16px;padding-top:14px;padding-bottom:14px}
|
||||
.brand{display:flex;align-items:center;gap:10px;text-decoration:none;color:var(--ink)}
|
||||
.brand .wm{font-family:var(--h);font-weight:800;font-size:22px}.brand .wm b{color:var(--coral);font-weight:800}
|
||||
nav.links{display:flex;flex-wrap:wrap;gap:6px 20px;font-size:15px;font-weight:500}
|
||||
nav.links a{text-decoration:none;color:var(--ink)}nav.links a.on{color:var(--coral);text-decoration:underline;text-underline-offset:5px}
|
||||
.stage-bar{background:#FFF4D6;color:#5A3A00;font:500 13px var(--m);text-align:center;padding:6px 12px}
|
||||
/* hero */
|
||||
.hero{background:linear-gradient(90deg,var(--aqua) 0%,rgba(234,246,244,.92) 34%,rgba(234,246,244,0) 58%),url(/art/hero.webp) right center/cover no-repeat}
|
||||
@media (max-width:860px){.hero{background:linear-gradient(180deg,rgba(234,246,244,.95) 0%,rgba(234,246,244,.95) 62%,rgba(234,246,244,.2) 100%),url(/art/hero.webp) center bottom/cover no-repeat}}
|
||||
.hero .wrap{display:flex;flex-wrap:wrap;gap:40px;align-items:center;padding-top:72px;padding-bottom:72px}
|
||||
.hero .copy{flex:1 1 460px;min-width:0}.hero .spacer{flex:1 1 380px;min-height:400px}
|
||||
@media (max-width:860px){.hero .spacer{min-height:220px}}
|
||||
.hero.slim .wrap{padding-top:48px;padding-bottom:48px}.hero.slim .spacer{min-height:200px}
|
||||
.topo{background:var(--ink) url(/art/topo.png) repeat;background-size:600px 600px;color:var(--aqua)}
|
||||
.topo .wrap{padding-top:64px;padding-bottom:64px}
|
||||
.topo p{color:var(--mist)}
|
||||
.topo a{color:var(--coral2)}
|
||||
.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:20px;margin-top:32px}
|
||||
.card-ink{background:var(--ink2);border-radius:16px;padding:24px}
|
||||
.card-ink .step{margin:0;font-family:var(--m);color:var(--coral2);font-size:14px}
|
||||
.card-ink h3{margin:10px 0 8px;color:#fff}
|
||||
.card-ink img{display:block;margin-bottom:12px;width:34px;height:34px}
|
||||
.card-ink.c1{border-top:4px solid var(--coral2)}.card-ink.c2{border-top:4px solid var(--teal2)}.card-ink.c3{border-top:4px solid var(--mint)}
|
||||
.card-ink.c2 .step,.card-ink.c3 .step{color:var(--mint)}
|
||||
ol.verify{margin:18px 0 0;padding:0;list-style:none;display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px}
|
||||
ol.verify li{background:var(--ink2);border-radius:14px;padding:18px}ol.verify b{font-family:var(--m);color:var(--coral2)}ol.verify p{margin:6px 0 0}
|
||||
section.band{padding:64px 0}
|
||||
.split{display:flex;flex-wrap:wrap;gap:40px;align-items:flex-start}
|
||||
.split>*{flex:1 1 380px;min-width:0}
|
||||
.panel{background:#fff;border:1px solid var(--line);border-radius:20px;padding:22px}
|
||||
.panel.pale{background:var(--pale);border:2px solid var(--ink)}
|
||||
ul.ticks{margin:18px 0 0;padding-left:20px;color:var(--ink3);display:flex;flex-direction:column;gap:8px}
|
||||
.chip{display:inline-block;font-family:var(--m);font-size:13px;padding:4px 10px;border-radius:999px;background:var(--chip);color:var(--teal)}
|
||||
.chip.coral{background:#FCE3DC;color:var(--coral)}.chip.gold{background:#FFF1C9;color:#6B4A00}.chip.grey{background:#E7EEED;color:var(--muted)}
|
||||
/* ad cards */
|
||||
.ads{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;margin-top:22px}
|
||||
.ad{background:#fff;border:1px solid var(--line);border-radius:16px;padding:18px;display:flex;flex-direction:column;gap:8px;position:relative}
|
||||
.ad.boosted{border:2px solid var(--coral);box-shadow:0 6px 0 rgba(196,55,27,.12)}
|
||||
.ad.credit{border:2px dashed var(--teal2)}
|
||||
.ad .tag{font-family:var(--m);font-size:12px;color:var(--muted);display:flex;gap:8px;flex-wrap:wrap;justify-content:space-between}
|
||||
.ad h3{font-family:var(--h);font-weight:800;font-size:21px;line-height:1.15}
|
||||
.ad p{margin:0;color:var(--ink3);font-size:15px}
|
||||
.ad .foot{display:flex;flex-wrap:wrap;gap:8px;justify-content:space-between;align-items:center;margin-top:auto;padding-top:8px;font-size:14px}
|
||||
.ad .visit{font-weight:600;color:var(--coral);text-decoration:none}.ad .visit:hover{text-decoration:underline}
|
||||
.ad.big{padding:26px;border-radius:20px}.ad.big h3{font-size:30px}.ad.big p{font-size:17px}
|
||||
/* forms */
|
||||
label.f{display:flex;flex-direction:column;gap:6px;font-weight:600;font-size:14px}
|
||||
label.f small{font-weight:400;color:var(--muted)}
|
||||
input[type=text],input[type=email],input[type=url],input[type=number],select,textarea{min-height:46px;padding:0 12px;border:1.5px solid var(--line);border-radius:10px;font:400 16px var(--b);background:#fff;color:var(--ink);width:100%}
|
||||
input:focus,select:focus,textarea:focus{outline:3px solid rgba(43,163,154,.35);border-color:var(--teal2)}
|
||||
form.stack{display:flex;flex-direction:column;gap:12px}
|
||||
.picker{border:1.5px solid var(--ink);border-radius:12px;overflow:hidden}
|
||||
.picker .ph{padding:10px 12px;background:var(--aqua);font:500 13px var(--m);display:flex;justify-content:space-between;gap:8px}
|
||||
.picker button{display:flex;width:100%;justify-content:space-between;align-items:center;gap:10px;min-height:48px;padding:0 12px;border:0;border-top:1px solid var(--line);background:#fff;font:400 15px var(--b);text-align:left;cursor:pointer;color:var(--ink)}
|
||||
.picker button.on{font-weight:600;background:var(--chip)}.picker button span{color:var(--muted);font-size:13px}
|
||||
.note{margin:12px 0 0;padding:12px 14px;border-radius:12px;background:#fff;border:1px solid var(--line);font-size:15px}
|
||||
.note.ok{border-color:var(--teal2);background:#E5F6F2}.note.err{border-color:var(--coral);background:#FDECE7;color:var(--bad)}.note.warn{border-color:#E9B949;background:#FFF7DF;color:#5A3A00}
|
||||
/* tables */
|
||||
.tbl{overflow-x:auto;margin-top:14px}
|
||||
table{width:100%;border-collapse:collapse;font-size:15px}
|
||||
th{text-align:left;color:var(--muted);font-size:13px;font-weight:600;padding:8px 6px;white-space:nowrap}
|
||||
td{padding:10px 6px;border-top:1px solid var(--line2);vertical-align:top}
|
||||
td.n{font-family:var(--m);white-space:nowrap}
|
||||
tr.sub td:first-child{padding-left:calc(6px + var(--d,1) * 18px)}
|
||||
tr.sub td:first-child::before{content:'\21B3 ';color:var(--teal2)}
|
||||
/* stats */
|
||||
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-top:18px}
|
||||
.stat{background:#fff;border:1px solid var(--line);border-radius:14px;padding:14px}
|
||||
.stat b{display:block;font:800 28px var(--h)}.stat span{font-size:13px;color:var(--muted)}
|
||||
.topo .stat{background:var(--ink2);border:0}.topo .stat span{color:var(--mist)}
|
||||
/* dashboard */
|
||||
.dash{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,520px),1fr));gap:20px;margin-top:24px}
|
||||
.sharebox{display:flex;gap:8px;flex-wrap:wrap;align-items:center;background:var(--aqua);border-radius:12px;padding:10px 12px;font:500 14px var(--m);word-break:break-all}
|
||||
.chain{font:500 13px var(--m);color:var(--muted)}
|
||||
/* footer */
|
||||
footer.foot{background:var(--ink);color:var(--mist);font-size:14px;margin-top:0}
|
||||
footer.foot .wrap{padding-top:36px;padding-bottom:36px;display:flex;flex-direction:column;gap:10px}
|
||||
footer.foot p{margin:0}footer.foot b{color:var(--aqua)}footer.foot a{color:var(--mist)}footer.foot a:hover{color:#fff}
|
||||
footer.foot .here{color:var(--coral2);font-weight:600}
|
||||
.legal main{max-width:820px}.legal h2{font-size:26px;margin-top:28px}.legal p,.legal li{color:var(--ink3)}
|
||||
/* toasts */
|
||||
.toasts{position:fixed;left:16px;bottom:16px;z-index:40;display:flex;flex-direction:column;gap:8px;max-width:min(360px,calc(100vw - 32px))}
|
||||
.toast{display:block;background:var(--ink);color:var(--aqua);border-left:4px solid var(--coral2);border-radius:12px;padding:12px 14px;font-size:14px;text-decoration:none;transform:translateY(20px);opacity:0;transition:.35s}
|
||||
.toast.in{transform:none;opacity:1}.toast b{color:#fff}.toast span{color:var(--mist)}
|
||||
.net-zone{margin:20px auto;text-align:center}.net-zone-label{font:500 11px var(--m);color:var(--muted);margin-bottom:4px}
|
||||
.skip{position:absolute;left:-999px}.skip:focus{left:16px;top:8px;z-index:50;background:#fff;padding:8px}
|
||||
@@ -0,0 +1,233 @@
|
||||
// ViralAdSource 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.VASWallet = (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: 'ViralAdSource', description: 'Every ad has a source.',
|
||||
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 VAS.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 { VAS.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 VAS.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 VAS.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,45 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Boost your ad | ViralAdSource</title>
|
||||
<meta name="description" content="A one-time Boost puts your ad at the top of the reshare board. Paid in POL; the contract splits it in the same transaction.">
|
||||
<link rel="canonical" href="https://viraladsource.com/boost">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="Boost your ad | ViralAdSource"><meta property="og:description" content="A one-time Boost puts your ad at the top of the reshare board. Paid in POL; the contract splits it in the same transaction."><meta property="og:url" content="https://viraladsource.com/boost">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="/boost">
|
||||
<main id="main">
|
||||
<div class="hero slim"><section class="wrap"><div class="copy"><p class="kicker">One-time, never a subscription</p><h1>Boost the source</h1>
|
||||
<p class="lead">A Boost puts your ad at the top of the reshare board for <span data-cfg="boostDays">7</span> days per Boost, so more people see it and pass it on.</p></div><div class="spacer" aria-hidden="true"></div></section></div>
|
||||
<section class="band"><div class="wrap split">
|
||||
<div class="panel pale">
|
||||
<p class="kicker" style="color:var(--muted)">Boost <span data-cfg="proposalTag"></span></p><p style="margin:0;font:800 48px var(--h)"><span data-cfg="boostUsd">$5</span></p><p class="muted" style="margin:0" id="quote">paid once in POL at the live rate</p>
|
||||
<label class="f" style="margin-top:16px">How many<select id="qty"><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>10</option></select></label>
|
||||
<button class="btn coral" style="width:100%;margin-top:16px" id="buy" type="button">Boost my ad</button>
|
||||
<p id="status" class="note" hidden></p>
|
||||
</div>
|
||||
<div>
|
||||
<h2 style="font-size:28px">Where the POL goes</h2>
|
||||
<p style="color:var(--ink3)">The VASShop contract splits every Boost in the buyer's own transaction. Nobody holds it.</p>
|
||||
<div class="tbl"><table><tbody id="splitRows"></tbody></table></div>
|
||||
<p class="muted" style="font-size:14px">Sponsor levels pay people in your network sponsor line who have bought a Boost; anyone who has not is passed over and the share goes up the line (up to 20 places). A level nobody qualifies for goes to the company. If you did not arrive through someone's reshare link, the resharer share goes to the company.</p>
|
||||
<p class="muted" style="font-size:14px">Pay with SafePal or any other crypto wallet on Polygon. Anything you send above the exact price comes back in the same transaction. A Boost buys advertising, not income.</p>
|
||||
</div>
|
||||
</div></section>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/wallet.js?v=1"></script>
|
||||
<script src="/assets/buy.js?v=1"></script>
|
||||
<script src="/assets/boost.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,29 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Confirm your email | ViralAdSource</title>
|
||||
<meta name="description" content="Confirm your free network account.">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="Confirm your email | ViralAdSource"><meta property="og:description" content="Confirm your free network account."><meta property="og:url" content="https://viraladsource.com/confirm">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap" style="padding-top:40px;padding-bottom:56px;max-width:720px">
|
||||
<h1 style="font-size:clamp(32px,5vw,46px)">Confirming your email</h1>
|
||||
<p id="status" class="note">One moment...</p>
|
||||
<div class="row" style="margin-top:16px"><a class="btn ink" href="/my">Sign in</a><a class="btn" href="/">Front page</a></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/join.js?v=1"></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>The contract | ViralAdSource</title>
|
||||
<meta name="description" content="VASShop on Polygon: who it pays, the reward pot and its rules, live from the chain.">
|
||||
<link rel="canonical" href="https://viraladsource.com/contract">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="The contract | ViralAdSource"><meta property="og:description" content="VASShop on Polygon: who it pays, the reward pot and its rules, live from the chain."><meta property="og:url" content="https://viraladsource.com/contract">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap" style="padding-top:40px;padding-bottom:56px">
|
||||
<p class="kicker">VASShop on Polygon</p><h1 style="font-size:clamp(32px,5vw,48px)">The contract</h1>
|
||||
<p class="lead">Every Boost is paid to the contract, which splits it in the same transaction. Sign-up rewards come only from the reward pot, which only Boosts fill.</p>
|
||||
<section class="panel" style="margin-top:22px"><div class="tbl"><table><tbody id="facts"><tr><td class="muted">Loading...</td></tr></tbody></table></div></section>
|
||||
<section class="panel" style="margin-top:22px"><h2 style="font-size:24px">The rules it enforces</h2>
|
||||
<ul class="ticks"><li>Every purchase needs an order signed by the site's keeper key, naming the buyer's sponsor line and the resharer. Each order can be used once.</li>
|
||||
<li>The resharer cut, the sponsor levels, the reward pot slice and the company are paid in the buyer's own transaction. A payment that cannot be delivered waits in the contract for that wallet to claim.</li>
|
||||
<li>A sign-up reward needs a keeper-signed voucher, used once, under the per-reward cap and the per-wallet daily cap, and never more than the pot holds.</li>
|
||||
<li>No proxy, no owner withdrawal of the pot, no self-destruct. The owner is Marty's Tangem hardware wallet.</li></ul></section>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/contract.js?v=1"></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>Earnings Disclaimer | ViralAdSource</title>
|
||||
<meta name="description" content="Earnings Disclaimer for ViralAdSource, run by TrustClickz.">
|
||||
<link rel="canonical" href="https://viraladsource.com/disclaimer">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="Earnings Disclaimer | ViralAdSource"><meta property="og:description" content="Earnings Disclaimer for ViralAdSource, run by TrustClickz."><meta property="og:url" content="https://viraladsource.com/disclaimer">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body class="legal" data-nav="">
|
||||
<main id="main" class="wrap" style="padding-top:40px;padding-bottom:56px"><p class="kicker">Updated November 16, 2026</p><h1 style="font-size:clamp(32px,5vw,46px)">Earnings Disclaimer</h1>
|
||||
<p>ViralAdSource sells advertising. Ad credits buy advertising, not income. Nothing is promised.</p>
|
||||
<p>Any POL paid to resharers or sponsors depends entirely on what other people choose to buy or do. Most people earn nothing or very little. Do not spend money you cannot afford to lose, and never treat a Boost as an investment.</p>
|
||||
<p>Crypto prices change. A reward or payment priced in dollars is paid in POL at the price when it is paid; its value can go down afterwards. Network fees apply to every transaction.</p>
|
||||
<p>Any example on this site is an illustration of how the contract splits a payment, not a prediction of what you will receive.</p>
|
||||
<p>TrustClickz, 615 Green Valley Drive, Moody, AL 35004. Questions: <a href="https://instantadpay.com/support?from=viraladsource">network support</a>.</p></main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/static.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,115 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>ViralAdSource | Every ad has a source. Watch yours travel.</title>
|
||||
<meta name="description" content="Post a text ad free. Anyone can reshare it with their own link, and every reshare grows a new branch. See the whole family tree of your ad: who passed it on, how far it went, where the views came from.">
|
||||
<link rel="canonical" href="https://viraladsource.com/">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="ViralAdSource | Every ad has a source. Watch yours travel."><meta property="og:description" content="Post a text ad free. Anyone can reshare it with their own link, and every reshare grows a new branch. See the whole family tree of your ad: who passed it on, how far it went, where the views came from."><meta property="og:url" content="https://viraladsource.com/">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebSite","name":"ViralAdSource","url":"https://viraladsource.com/"},{"@type":"Organization","name":"ViralAdSource","url":"https://viraladsource.com/","logo":"https://viraladsource.com/art/icon-192.png"}]}</script>
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="/">
|
||||
<main id="main">
|
||||
<div class="hero" role="img" aria-label="A spring at the source branching into coral streams across a map">
|
||||
<section class="wrap">
|
||||
<div class="copy">
|
||||
<p class="kicker">Part of the Crypto Team Build Network</p>
|
||||
<h1>Every ad has a source. Watch yours travel.</h1>
|
||||
<p class="lead">Post a text ad free. Anyone can reshare it to their own people, and every reshare grows a new branch. You see the whole family tree of your ad: who passed it on, how far it went, where the views came from.</p>
|
||||
<div class="row" style="margin-top:30px"><a class="btn coral" href="/my#post">Post your first ad free</a><a class="btn" href="#how">See how it spreads</a></div>
|
||||
<p class="muted" style="margin:18px 0 0;font-size:14px">One free account across the network. Sign in with InstantAdPay or LinkSpin.</p>
|
||||
</div>
|
||||
<div class="spacer" aria-hidden="true"></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section id="how" class="topo"><div class="wrap">
|
||||
<h2>How an ad spreads from its source</h2>
|
||||
<p style="margin:10px 0 0;max-width:680px">Not five levels down your own team. Out through anyone who thinks it is worth passing on.</p>
|
||||
<div class="cards">
|
||||
<div class="card-ink"><img src="/art/icons/post-write.svg" alt="" width="34" height="34"><p class="step">01 · Post</p><h3>Write your ad at the source</h3><p>A headline, two lines and your link. One active ad is free. Your link can be a LinkSpin spin link so every click is tracked.</p></div>
|
||||
<div class="card-ink"><img src="/art/icons/reshare.svg" alt="" width="34" height="34"><p class="step">02 · Reshare</p><h3>Others pass it on</h3><p>Members reshare ads they like to their own pages and lists with their reshare link. Each reshare is a new branch on your tree.</p></div>
|
||||
<div class="card-ink"><img src="/art/icons/branch.svg" alt="" width="34" height="34"><p class="step">03 · Credit flows back</p><h3>Resharers are rewarded for results</h3><p>Real views earn ad credits. A verified new member or a Boost sold through a branch pays that resharer in POL on Polygon. Shares alone never pay: results do.</p></div>
|
||||
</div>
|
||||
<div class="stats" id="todayStats" aria-label="Today on ViralAdSource"></div>
|
||||
</div></section>
|
||||
|
||||
<section id="board" class="band"><div class="wrap">
|
||||
<div class="row" style="justify-content:space-between"><h2>The reshare board</h2><a class="btn sm" href="/boost">Boost your ad to the top</a></div>
|
||||
<p class="muted" style="margin:8px 0 0">Boosted ads first, then this week's movers by new reshares and verified clicks. Open an ad to reshare it with your own link.</p>
|
||||
<div class="ads" id="boardAds"><p class="muted">Loading the board...</p></div>
|
||||
</div></section>
|
||||
|
||||
<section id="featured" class="wrap" hidden><h2 style="font-size:26px">Featured with credits</h2><p class="muted" style="margin:6px 0 0">Members who earned ad credits through their reshares spend them here.</p><div class="ads"></div></section>
|
||||
|
||||
<section id="post" class="band"><div class="wrap split">
|
||||
<div>
|
||||
<h2>Post at the source, track it in LinkSpin</h2>
|
||||
<p class="lead" style="font-size:17px">Point your ad at one of your LinkSpin spin links. One free ad then rotates every page you promote, and every branch of your tree shows up in your LinkSpin Reports as its own source.</p>
|
||||
<ul class="ticks">
|
||||
<li>Only your own spin links can be picked. LinkSpin confirms it on every save.</li>
|
||||
<li>Each reshare link tags the click with the resharer, so LinkSpin shows which branch brought each sign-up.</li>
|
||||
<li>Sign in once with InstantAdPay or LinkSpin. Your network account already works here.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="panel"><p style="margin:0;font-weight:600">Your ad's family tree, live</p>
|
||||
<p class="muted" style="margin:6px 0 0">Most ad sites give you a view count. Here you see the route: which reshare carried your ad furthest, which branch went quiet, and which page of yours the clicks landed on.</p>
|
||||
<ul class="ticks"><li>Branch by branch: who reshared, when, and what each branch brought in</li><li>Furthest reach: how many steps from the source</li><li>Clicks by page when your link is a LinkSpin spin link</li></ul>
|
||||
<div class="row" style="margin-top:16px"><a class="btn ink" href="/my#post">Post my free ad</a><a class="btn" href="/my#tree">See my tree</a></div></div>
|
||||
</div></section>
|
||||
|
||||
<section id="rewards" class="topo"><div class="wrap">
|
||||
<h2>Three ways a reshare is rewarded</h2>
|
||||
<p style="margin:10px 0 0;max-width:720px">A share alone is never paid, because anyone can claim a share. What your branch actually causes is paid, and the bigger the result, the stronger the proof.</p>
|
||||
|
||||
<div class="cards">
|
||||
<div class="card-ink c1"><img src="/art/icons/wallet.svg" alt="" width="34" height="34"><p class="step">Level 1 · POL, same transaction</p>
|
||||
<h3>A Boost sold through your branch</h3>
|
||||
<p>The buyer came in through your reshare link. The contract pays you <span data-cfg="cut">20%</span> of that Boost in POL in the same transaction as the sponsor line. Nobody holds it; anyone can check it on Polygonscan.</p></div>
|
||||
<div class="card-ink c2"><img src="/art/icons/verify-shield-check.svg" alt="" width="34" height="34"><p class="step">Level 2 · POL from the reward pot</p>
|
||||
<h3>A verified new member from your branch</h3>
|
||||
<p>Someone brand new to the whole network joins through your link and confirms their email. Once the checks pass, <span data-cfg="signup">$0.25</span> in POL is paid from the reward pot to your wallet, up to <span data-cfg="cap">10</span> a day. Bigger tiers are credited at once and withdrawable after <span data-cfg="lockDays">14</span> days.</p>
|
||||
<p data-cfg="payoutsNote" class="mono" style="font-size:13px"></p></div>
|
||||
<div class="card-ink c3"><img src="/art/icons/ledger-list.svg" alt="" width="34" height="34"><p class="step">Level 3 · ad credits</p>
|
||||
<h3>Real views from your branch</h3>
|
||||
<p>Views are the easiest thing to fake, so they earn ad space only: <span data-cfg="creditsPer">10</span> credits per <span data-cfg="creditsViews">100</span> verified views, spent on your own ad. Ad credits buy advertising, not income.</p></div>
|
||||
</div>
|
||||
<h3 style="margin:44px 0 0;font-family:var(--h);font-weight:800;font-size:30px;color:#fff">How a reward is verified</h3>
|
||||
<ol class="verify">
|
||||
<li><b>1</b><p>Every reshare link is unique to the resharer, so each click carries whose branch it came from.</p></li>
|
||||
<li><b>2</b><p>The result happens: a Boost is bought on chain, or a new member confirms their email.</p></li>
|
||||
<li><b>3</b><p>Real-time checks: brand new on the network hub, not the resharer's own device, IP or wallet, no throwaway email, daily cap, fraud score.</p></li>
|
||||
<li><b>4</b><p>The site signs a voucher for the reward. The contract checks the signature and pays. Voucher and payment both show on the public ledger.</p></li>
|
||||
</ol>
|
||||
<p style="margin:22px 0 0;max-width:760px">Where the POL comes from: <span data-cfg="pot">10%</span> of every Boost goes into the reward pot by the contract, so rewards can never exceed what came in. Visits alone never create new money. <span data-cfg="proposalNote"></span></p>
|
||||
</div></section>
|
||||
|
||||
<section class="band" style="background:#fff;border-top:1px solid var(--line);border-bottom:1px solid var(--line)"><div class="wrap split" style="align-items:center">
|
||||
<div><h2>Boost the source</h2>
|
||||
<p style="color:var(--ink3)">Want a head start? A Boost puts your ad at the top of the reshare board for <span data-cfg="boostDays">7</span> days, so more people see it and pass it on. One-time, never a subscription.</p>
|
||||
<p style="color:var(--ink3)">Paid in POL by smart contract with SafePal or any other crypto wallet. The split is in the contract and every payment is on the public ledger.</p></div>
|
||||
<div class="panel pale"><p class="kicker" style="color:var(--muted)">Boost</p><p style="margin:0;font:800 48px var(--h)"><span data-cfg="boostUsd">$5</span></p><p class="muted" style="margin:0">paid once in POL at the live rate <span data-cfg="proposalTag"></span></p>
|
||||
<ul class="ticks"><li>Top of the reshare board for <span data-cfg="boostDays">7</span> days</li><li><span data-cfg="levels">5 x 5%</span>: sponsor line share, paid in the same transaction</li><li><span data-cfg="cut">20%</span> to the resharer whose branch sold it, <span data-cfg="pot">10%</span> to the reward pot</li><li>Proof on Polygon, linked from the ledger</li></ul>
|
||||
<a class="btn coral" style="width:100%;margin-top:18px" href="/boost">Boost my ad</a></div>
|
||||
</div></section>
|
||||
|
||||
<section id="ledger" class="band"><div class="wrap"><div class="cards" style="margin-top:0">
|
||||
<div class="panel"><h3 style="margin:0 0 6px;font-size:19px">Already a ViralAdSource member?</h3><p style="margin:0;color:var(--ink3)">Sign in with your network account. Your account came across by email and your sponsor was kept.</p></div>
|
||||
<div class="panel"><h3 style="margin:0 0 6px;font-size:19px"><a href="/ledger">Live ledger</a></h3><p style="margin:0;color:var(--ink3)">Every Boost and every split, each linked to its Polygon transaction, and every sign-up reward.</p></div>
|
||||
<div class="panel" id="hunt"><h3 style="margin:0 0 6px;font-size:19px">Hunt it on PolHunter</h3><p style="margin:0;color:var(--ink3)">A find code hides in one of the three "How an ad spreads" steps.</p><div id="phEmbed"></div></div>
|
||||
</div></div></section>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/front.js?v=1"></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>Join the network free | ViralAdSource</title>
|
||||
<meta name="description" content="One free account for every network site.">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="Join the network free | ViralAdSource"><meta property="og:description" content="One free account for every network site."><meta property="og:url" content="https://viraladsource.com/join">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap" style="padding-top:40px;padding-bottom:56px;max-width:720px">
|
||||
<h1 style="font-size:clamp(32px,5vw,46px)">Join the network free</h1>
|
||||
<p class="lead" id="viaNote">One free account for every network site: InstantAdPay, LinkSpin, ViralAdSource and the rest.</p>
|
||||
<form class="panel stack" id="joinForm" style="margin-top:22px" autocomplete="on">
|
||||
<label class="f">Email <small>we send one link to confirm it</small><input type="email" id="email" required autocomplete="email"></label>
|
||||
<label class="f">Username <small>optional, 3 to 30 letters or numbers</small><input type="text" id="username" maxlength="30" autocomplete="username"></label>
|
||||
<button class="btn coral" type="submit">Join free</button>
|
||||
<p class="muted" style="font-size:13px;margin:0">By joining you agree to the <a href="/terms">Terms</a> and <a href="/privacy">Privacy</a>. Already have a network account? <a href="/my">Sign in</a>.</p>
|
||||
</form>
|
||||
<p id="status" class="note" hidden></p>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/join.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,32 @@
|
||||
<!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 | ViralAdSource</title>
|
||||
<meta name="description" content="Every Boost, every split and every sign-up reward on ViralAdSource, each with its Polygon transaction.">
|
||||
<link rel="canonical" href="https://viraladsource.com/ledger">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="Live ledger | ViralAdSource"><meta property="og:description" content="Every Boost, every split and every sign-up reward on ViralAdSource, each with its Polygon transaction."><meta property="og:url" content="https://viraladsource.com/ledger">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="/ledger">
|
||||
<main id="main" class="wrap" style="padding-top:40px;padding-bottom:56px">
|
||||
<p class="kicker">Proof, not promises</p><h1 style="font-size:clamp(32px,5vw,48px)">Live ledger</h1>
|
||||
<div class="stats" id="ledStats"></div>
|
||||
<section class="panel" style="margin-top:22px"><h2 style="font-size:26px">Boosts and their splits</h2>
|
||||
<div class="tbl"><table><thead><tr><th>When</th><th>Buyer</th><th>Paid</th><th>Resharer</th><th>Sponsor levels</th><th>Reward pot</th><th>Company</th><th>Proof</th></tr></thead><tbody id="rows"><tr><td colspan="8" class="muted">No Boosts yet.</td></tr></tbody></table></div></section>
|
||||
<section class="panel" style="margin-top:22px"><h2 style="font-size:26px">Sign-up rewards</h2><p class="muted" id="payNote" style="margin:6px 0 0"></p>
|
||||
<div class="tbl"><table><thead><tr><th>When</th><th>Resharer</th><th>Kind</th><th>Amount</th><th>Status</th><th>Proof</th></tr></thead><tbody id="rrows"><tr><td colspan="6" class="muted">No rewards yet.</td></tr></tbody></table></div></section>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/ledger.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,72 @@
|
||||
<!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 ad tree | ViralAdSource</title>
|
||||
<meta name="description" content="Your ad, its family tree, your reshare links, ad credits and rewards.">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="My ad tree | ViralAdSource"><meta property="og:description" content="Your ad, its family tree, your reshare links, ad credits and rewards."><meta property="og:url" content="https://viraladsource.com/my">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="/my">
|
||||
<main id="main" class="wrap" style="padding-top:36px;padding-bottom:56px">
|
||||
<h1 style="font-size:clamp(32px,5vw,48px)">My ad tree</h1>
|
||||
<section id="signin" class="panel" style="margin-top:22px" hidden>
|
||||
<h2 style="font-size:26px">Sign in</h2>
|
||||
<p class="muted" style="margin:8px 0 0">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:16px"><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/join">Join free</a>.</p>
|
||||
</section>
|
||||
<div id="dash" hidden>
|
||||
<p class="muted" id="who" style="margin:8px 0 0"></p>
|
||||
<div class="stats" id="myStats"></div>
|
||||
<div class="dash">
|
||||
<section class="panel" id="post">
|
||||
<h2 style="font-size:26px" id="adTitle">Post your free ad</h2>
|
||||
<form class="stack" id="adForm" style="margin-top:12px" autocomplete="off">
|
||||
<label class="f">Headline <small>3 to <span data-cfg="headline">60</span> characters</small><input type="text" id="headline" maxlength="60" required></label>
|
||||
<label class="f">First line<input type="text" id="line1" maxlength="90" required></label>
|
||||
<label class="f">Second line <small>optional</small><input type="text" id="line2" maxlength="90"></label>
|
||||
<label class="f">Your link <small>an https page that loads, or one of your own LinkSpin spin links</small><input type="url" id="link" placeholder="https://" required></label>
|
||||
<div class="picker" id="picker"><div class="ph"><span>Use one of my spin links</span><button type="button" class="btn sm" id="loadSpins" style="min-height:30px">Show my spin links</button></div><div id="spinList"></div></div>
|
||||
<label class="row" style="gap:8px;font-size:14px"><input type="checkbox" id="track" checked> Track clicks with LinkSpin (a tracked link on your own LinkSpin account)</label>
|
||||
<button class="btn coral" type="submit" id="saveAd">Post my free ad</button>
|
||||
</form>
|
||||
<p id="status" class="note" hidden></p>
|
||||
<div id="sourceBox" hidden style="margin-top:14px"><p style="margin:0 0 6px;font-weight:600">Your source link</p><div class="sharebox"><span id="sourceUrl"></span><button class="btn sm" type="button" id="copySource">Copy</button></div></div>
|
||||
</section>
|
||||
<section class="panel" id="tree">
|
||||
<div class="row" style="justify-content:space-between"><h2 style="font-size:26px">Family tree</h2><span class="chip" id="treeChip">no ad yet</span></div>
|
||||
<div class="stats" id="treeStats"></div>
|
||||
<div class="tbl"><table><thead><tr><th>Branch</th><th>Step</th><th>Reshares under it</th><th>Views</th><th>Clicks</th><th>Sign-ups</th><th>Boosts</th></tr></thead><tbody id="treeRows"><tr><td colspan="7" class="muted">Post your ad, then share your source link. Every reshare shows up here.</td></tr></tbody></table></div>
|
||||
<p class="muted" style="font-size:13px;margin:10px 0 0">Views and clicks are verified (one per visitor per 24 hours). Sign-ups are new network members who confirmed their email. When your link is a LinkSpin link, LinkSpin Reports split clicks and sign-ups by branch (s2 = resharer, s3 = reshare link).</p>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<h2 style="font-size:26px">Ads I reshared</h2>
|
||||
<div class="tbl"><table><thead><tr><th>Ad</th><th>Step</th><th>Views</th><th>Clicks</th><th>Sign-ups</th><th>Boosts</th><th>Link</th></tr></thead><tbody id="myShares"><tr><td colspan="7" class="muted">Open any ad on the <a href="/#board">reshare board</a> and tap "Reshare this ad".</td></tr></tbody></table></div>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<h2 style="font-size:26px">Credits and rewards</h2>
|
||||
<div class="stats" id="rewardStats"></div>
|
||||
<p class="muted" style="font-size:14px" id="rewardNote"></p>
|
||||
<div class="tbl"><table><thead><tr><th>When</th><th>What</th><th>Amount</th><th>Status</th></tr></thead><tbody id="rewardRows"><tr><td colspan="4" class="muted">Nothing yet.</td></tr></tbody></table></div>
|
||||
<p class="muted" style="font-size:13px">Ad credits buy advertising, not income. Nothing is promised.</p>
|
||||
</section>
|
||||
</div>
|
||||
<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>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/wallet.js?v=1"></script>
|
||||
<script src="/assets/my.js?v=1"></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>Privacy | ViralAdSource</title>
|
||||
<meta name="description" content="Privacy for ViralAdSource, run by TrustClickz.">
|
||||
<link rel="canonical" href="https://viraladsource.com/privacy">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="Privacy | ViralAdSource"><meta property="og:description" content="Privacy for ViralAdSource, run by TrustClickz."><meta property="og:url" content="https://viraladsource.com/privacy">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body class="legal" data-nav="">
|
||||
<main id="main" class="wrap" style="padding-top:40px;padding-bottom:56px"><p class="kicker">Updated November 16, 2026</p><h1 style="font-size:clamp(32px,5vw,46px)">Privacy</h1>
|
||||
<p>TrustClickz runs ViralAdSource. Here is what we keep and why.</p>
|
||||
<h2>What we keep</h2><ul><li>Your wallet address and network username, to run your account and pay what the contract pays.</li><li>Your text ad and the reshare links you make, with their counts.</li><li>For someone who joins here: their email (to confirm it and to create their network account), the reshare link they came through, and hashed device and connection keys used for fraud checks. We never store raw IP addresses.</li><li>Visit and click records with hashed visitor keys, kept 15 days, to count verified views and clicks.</li></ul>
|
||||
<h2>Sharing</h2><p>Your account is part of the network: your username, wallet and sponsor are shared with the network hub so one account works on every network site. We do not sell personal data. Blockchain transactions are public by nature.</p>
|
||||
<h2>Your choices</h2><p>Ask network support to delete your data; the network hub removes it from every network site, except what the blockchain or the law keeps.</p>
|
||||
<p>TrustClickz, 615 Green Valley Drive, Moody, AL 35004. Questions: <a href="https://instantadpay.com/support?from=viraladsource">network support</a>.</p></main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/static.js?v=1"></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>Promote ViralAdSource | Promo kit</title>
|
||||
<meta name="description" content="Links, creatives and copy for ViralAdSource with your network username.">
|
||||
<link rel="canonical" href="https://viraladsource.com/promote">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="Promote ViralAdSource | Promo kit"><meta property="og:description" content="Links, creatives and copy for ViralAdSource with your network username."><meta property="og:url" content="https://viraladsource.com/promote">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="">
|
||||
<main id="main" class="wrap" style="padding-top:40px;padding-bottom:56px">
|
||||
<p class="kicker">Promo kit</p><h1 style="font-size:clamp(32px,5vw,48px)">Promote ViralAdSource</h1>
|
||||
<p class="lead">Your links, creatives and copy, filled in with your network username.</p>
|
||||
<label class="f" style="max-width:360px;margin-top:18px">Your network username<input type="text" id="kitUser" placeholder="username"></label>
|
||||
<div id="kit" style="margin-top:22px"></div>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/promote.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,57 @@
|
||||
<!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 resharers are rewarded | ViralAdSource</title>
|
||||
<meta name="description" content="A share alone is never paid. Boosts sold, verified new members and real views through your branch are, and every reward is checked first.">
|
||||
<link rel="canonical" href="https://viraladsource.com/rewards">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="How resharers are rewarded | ViralAdSource"><meta property="og:description" content="A share alone is never paid. Boosts sold, verified new members and real views through your branch are, and every reward is checked first."><meta property="og:url" content="https://viraladsource.com/rewards">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body data-nav="/rewards">
|
||||
<main id="main">
|
||||
<section class="topo"><div class="wrap">
|
||||
<p class="kicker" style="color:var(--mint)">Results only</p><h1 style="color:#fff">Three ways a reshare is rewarded</h1>
|
||||
<p style="margin:14px 0 0;max-width:720px">A share alone is never paid, because anyone can claim a share. What your branch actually causes is paid, and the bigger the result, the stronger the proof.</p>
|
||||
|
||||
<div class="cards">
|
||||
<div class="card-ink c1"><img src="/art/icons/wallet.svg" alt="" width="34" height="34"><p class="step">Level 1 · POL, same transaction</p>
|
||||
<h3>A Boost sold through your branch</h3>
|
||||
<p>The buyer came in through your reshare link. The contract pays you <span data-cfg="cut">20%</span> of that Boost in POL in the same transaction as the sponsor line. Nobody holds it; anyone can check it on Polygonscan.</p></div>
|
||||
<div class="card-ink c2"><img src="/art/icons/verify-shield-check.svg" alt="" width="34" height="34"><p class="step">Level 2 · POL from the reward pot</p>
|
||||
<h3>A verified new member from your branch</h3>
|
||||
<p>Someone brand new to the whole network joins through your link and confirms their email. Once the checks pass, <span data-cfg="signup">$0.25</span> in POL is paid from the reward pot to your wallet, up to <span data-cfg="cap">10</span> a day. Bigger tiers are credited at once and withdrawable after <span data-cfg="lockDays">14</span> days.</p>
|
||||
<p data-cfg="payoutsNote" class="mono" style="font-size:13px"></p></div>
|
||||
<div class="card-ink c3"><img src="/art/icons/ledger-list.svg" alt="" width="34" height="34"><p class="step">Level 3 · ad credits</p>
|
||||
<h3>Real views from your branch</h3>
|
||||
<p>Views are the easiest thing to fake, so they earn ad space only: <span data-cfg="creditsPer">10</span> credits per <span data-cfg="creditsViews">100</span> verified views, spent on your own ad. Ad credits buy advertising, not income.</p></div>
|
||||
</div>
|
||||
<h3 style="margin:44px 0 0;font-family:var(--h);font-weight:800;font-size:30px;color:#fff">How a reward is verified</h3>
|
||||
<ol class="verify">
|
||||
<li><b>1</b><p>Every reshare link is unique to the resharer, so each click carries whose branch it came from.</p></li>
|
||||
<li><b>2</b><p>The result happens: a Boost is bought on chain, or a new member confirms their email.</p></li>
|
||||
<li><b>3</b><p>Real-time checks: brand new on the network hub, not the resharer's own device, IP or wallet, no throwaway email, daily cap, fraud score.</p></li>
|
||||
<li><b>4</b><p>The site signs a voucher for the reward. The contract checks the signature and pays. Voucher and payment both show on the public ledger.</p></li>
|
||||
</ol>
|
||||
<p style="margin:22px 0 0;max-width:760px">Where the POL comes from: <span data-cfg="pot">10%</span> of every Boost goes into the reward pot by the contract, so rewards can never exceed what came in. Visits alone never create new money. <span data-cfg="proposalNote"></span></p>
|
||||
</div></section>
|
||||
<section class="band"><div class="wrap split">
|
||||
<div><h2 style="font-size:30px">What can hold a sign-up reward</h2>
|
||||
<ul class="ticks"><li>The person was already in the network (on any network site).</li><li>Their email was never confirmed, or it is a throwaway address.</li><li>The sign-up came from your own device or connection.</li><li>You reached the daily cap.</li><li>The sign-up looks automated: filled in seconds, many from one connection.</li></ul>
|
||||
<p class="muted">A held sign-up is looked at by a person. A rejected one never pays.</p></div>
|
||||
<div class="panel"><h2 style="font-size:26px">Where to see it</h2><p class="muted">Your rewards and credits are on <a href="/my">My ad tree</a>. Every paid reward and every Boost split is on the <a href="/ledger">public ledger</a> with its Polygon transaction.</p></div>
|
||||
</div></section>
|
||||
</main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/static.js?v=1"></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>Terms | ViralAdSource</title>
|
||||
<meta name="description" content="Terms for ViralAdSource, run by TrustClickz.">
|
||||
<link rel="canonical" href="https://viraladsource.com/terms">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="ViralAdSource">
|
||||
<meta property="og:title" content="Terms | ViralAdSource"><meta property="og:description" content="Terms for ViralAdSource, run by TrustClickz."><meta property="og:url" content="https://viraladsource.com/terms">
|
||||
<meta property="og:image" content="https://viraladsource.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="ViralAdSource: every ad has a source">
|
||||
<meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://viraladsource.com/art/og-share.png">
|
||||
<meta name="theme-color" content="#0B2730">
|
||||
<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=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap">
|
||||
<link rel="stylesheet" href="/assets/vas.css?v=1">
|
||||
</head>
|
||||
<body class="legal" data-nav="">
|
||||
<main id="main" class="wrap" style="padding-top:40px;padding-bottom:56px"><p class="kicker">Updated November 16, 2026</p><h1 style="font-size:clamp(32px,5vw,46px)">Terms</h1>
|
||||
<p>ViralAdSource (viraladsource.com) is run by TrustClickz, 615 Green Valley Drive, Moody, AL 35004. By using the site you agree to these terms.</p>
|
||||
<h2>Accounts</h2><p>You sign in with your network account or your wallet. One free text ad per member. You keep your wallet's keys; nobody here will ever ask for your recovery phrase.</p>
|
||||
<h2>Your ad and your link</h2><p>Your ad and link must be yours or ones you have the right to use and must lead to a lawful page that loads. No adult content, malware, phishing, deceptive offers, hate or anything illegal where you or your visitors live. No link shorteners other than your own LinkSpin spin links. We can pause or remove an ad that breaks these rules.</p>
|
||||
<h2>Reshares</h2><p>Anyone can reshare a live ad with their own reshare link. Resharing never earns anything by itself. Rewards are given only for the verified results described on the Rewards page and only after the checks there pass. We can hold, reject or reverse a reward we believe came from fraud, self-dealing, automation or a duplicate person, and we can close accounts that try.</p>
|
||||
<h2>Ad credits</h2><p>Ad credits are advertising on this site for your own ad. They have no cash value, cannot be sold, transferred or withdrawn, and can expire if the program changes.</p>
|
||||
<h2>Boosts and payments</h2><p>A Boost is a one-time purchase paid in POL on Polygon through the VASShop smart contract, which splits the payment in the same transaction as shown on the Contract page. Blockchain payments are final and cannot be refunded or reversed. Nothing here is a subscription.</p>
|
||||
<h2>No promise of income</h2><p>What you buy is advertising. We do not promise any income, views, sign-ups or results. See the Earnings Disclaimer.</p>
|
||||
<h2>Changes</h2><p>We can change these terms and the program's numbers going forward; a change never alters a payment already made on chain.</p>
|
||||
<p>TrustClickz, 615 Green Valley Drive, Moody, AL 35004. Questions: <a href="https://instantadpay.com/support?from=viraladsource">network support</a>.</p></main>
|
||||
<script src="/assets/common.js?v=1"></script>
|
||||
<script src="/assets/chat.js?v=1" defer></script>
|
||||
<script src="/assets/static.js?v=1"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"site": "viraladsource",
|
||||
"home": [
|
||||
{ "q": "What is ViralAdSource?", "kb": "about", "must": ["reshare", "family tree"] },
|
||||
{ "q": "How do I reshare an ad?", "kb": "reshare", "must": ["unique", "branch"] },
|
||||
{ "q": "Do I get paid for resharing?", "kb": "rewards", "must": ["results", "not income"] },
|
||||
{ "q": "What are ad credits?", "kb": "credits", "must": ["credits", "not income"] },
|
||||
{ "q": "What is a Boost?", "kb": "boost", "must": ["one-time", "SafePal or any other crypto wallet"] }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Site assistant checks (2026-11-15): node qa/chatbot.test.mjs
|
||||
// No network: a stand-in OpenRouter and a stand-in hub. Checks the instant answers route every example question to its own entry,
|
||||
// the house rules (no em dashes, no MetaMask, never RM Circle, ad-credits line where credits come up, no income promises),
|
||||
// the network merge (home boosted, a named site boosted), the support hand-off, and the site's scripted Q&A (qa/chat-qa.json:
|
||||
// home questions must land on the named entry and contain the expected facts).
|
||||
// The SAME file ships in every rebuilt network site.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
|
||||
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'chat-'));
|
||||
process.env.DATA_DIR = DIR; delete process.env.DOCSTORE_URL; process.env.NETKB = '0'; delete process.env.OPENROUTER_API_KEY;
|
||||
let pass = 0, fail = 0; const bad = [];
|
||||
const ok = (c, m) => { if (c) pass++; else { fail++; bad.push(m); console.log('FAIL', m); } };
|
||||
|
||||
// stand-in OpenRouter: answers with what the system prompt says about the first KB entry, so we can see the prompt
|
||||
let lastPrompt = '', reply = 'Fine.';
|
||||
const or = http.createServer((req, res) => { let b = ''; req.on('data', c => { b += c; }); req.on('end', () => {
|
||||
const j = JSON.parse(b); lastPrompt = j.messages[0].content; ok(j.reasoning && j.reasoning.enabled === false, 'reasoning is switched off');
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('\n\n' + JSON.stringify({ choices: [{ message: { content: reply } }] })); }); });
|
||||
await new Promise(r => or.listen(0, r));
|
||||
process.env.OPENROUTER_URL = 'http://127.0.0.1:' + or.address().port + '/v1/chat/completions';
|
||||
|
||||
try { const cfg = require(path.join(ROOT, 'config.js')); if (cfg.reset) cfg.reset(); } catch (e) {} // Stack POL has no config.js
|
||||
const bot = require(path.join(ROOT, 'chatbot.js'));
|
||||
const core = require(path.join(ROOT, 'chatcore.js'));
|
||||
const kb = require(path.join(ROOT, 'kb.js'));
|
||||
const netkb = require(path.join(ROOT, 'netkb.js'));
|
||||
const dataDir = bot.SITE.dataDir;
|
||||
await bot.init();
|
||||
|
||||
// 1. seeds and the fast path: every example question of a canned entry lands on that entry (first match wins)
|
||||
const seeds = core.seeds();
|
||||
ok(seeds.length >= 10, 'at least 10 seeded entries (' + seeds.length + ')');
|
||||
for (const c of bot.CANNED) {
|
||||
ok(c.re instanceof RegExp, c.id + ' has a pattern');
|
||||
for (const q of c.q || []) { const hit = await kb.fastPath(q); ok(hit && hit.id === 'c-' + c.id, 'example "' + q + '" -> ' + c.id + ' (got ' + (hit && hit.id) + ')'); }
|
||||
}
|
||||
// 2. house rules in every seeded answer
|
||||
for (const s of seeds) {
|
||||
ok(!/[—―]/.test(s.answer + s.title), s.id + ': no em dashes');
|
||||
ok(!/metamask/i.test(s.answer), s.id + ': never recommends MetaMask');
|
||||
ok(!/rm ?circle/i.test(s.answer), s.id + ': never RM Circle');
|
||||
ok(!/(guarantee[ds]? (income|earnings|profit)|you will (earn|make)|passive income|get rich|up to \$?\d[\d,.]* (a|per) (day|week|month))/i.test(s.answer), s.id + ': no income promise');
|
||||
if (/\bad credits?\b/i.test(s.answer)) ok(/Ad credits buy advertising, not income\./.test(s.answer), s.id + ': ad credits line');
|
||||
if (/wallet/i.test(s.answer) && /(which|use|recommend)/i.test(s.answer) && /safepal/i.test(s.answer)) ok(/SafePal or any other crypto wallet/i.test(s.answer), s.id + ': wallet wording');
|
||||
}
|
||||
// 3. the engine: scrub, support hand-off, the AI path
|
||||
ok(core.scrub('A — B, use MetaMask or SafePal') === 'A, B, use SafePal', 'scrub: em dash and MetaMask (' + core.scrub('A — B, use MetaMask or SafePal') + ')');
|
||||
{ const r = await bot.answer('I need to talk to a real person about my account'); ok(r.handoff === true, 'asking for a person hands off'); }
|
||||
{ const r = await bot.answer(''); ok(!!r.error, 'empty question refused'); }
|
||||
if (dataDir) fs.writeFileSync(path.join(dataDir, 'openrouter.key'), 'test-key'); else process.env.OPENROUTER_API_KEY = 'test-key'; // no volume (Stack POL): the env key
|
||||
reply = 'Sure — try RM Circle'; { const r = await bot.answer('zzqx unrelated words nobody wrote down'); ok(!/rm ?circle/i.test(r.reply) && !/—/.test(r.reply), 'an RM Circle or em dash reply never leaves (' + r.reply + ')'); }
|
||||
ok(/NEVER promise or estimate income/.test(lastPrompt) && /SafePal or any other crypto wallet/.test(lastPrompt) && /Ad credits buy advertising, not income\./.test(lastPrompt), 'house rules in the system prompt');
|
||||
reply = 'Fine.';
|
||||
|
||||
// 4. the network merge: home boosted, a named site boosted, labelled with the site and its link
|
||||
const GENERAL = bot.CANNED.find(c => !['support', 'refund', 'about'].includes(c.id) && (c.q || []).length).q[0].replace(/\?$/, '');
|
||||
netkb._set({ version: 'v1', sites: { othersite: { name: 'Other Site', url: 'https://other.example', count: 1 }, [process.env.HUB_SITE || bot.SITE.hubSite]: { name: bot.SITE.name, url: bot.SITE.url } },
|
||||
entries: [{ site: 'othersite', id: 'about', title: 'What is Other Site?', questions: ['What is Other Site?', GENERAL + ' on Other Site'], answer: 'Other Site is a test site with its own rules.', tags: ['test'] }] });
|
||||
await kb.load(true);
|
||||
{ const hits = await kb.search(GENERAL, 8); const top = hits[0] && hits[0].entry; ok(top && !top.site, 'home entries first for a general question (top ' + (top && top.id) + ')'); }
|
||||
{ const hits = await kb.search(GENERAL + ' on Other Site', 8); const top = hits[0] && hits[0].entry; ok(top && top.site === 'othersite', 'a named site boosts its own entry (top ' + (top && top.id) + ')'); }
|
||||
{ const block = kb.promptBlock(await kb.context('What is Other Site', 6)); ok(/about Other Site, another network site; send people to https:\/\/other\.example/.test(block), 'remote entry labelled with site and link'); }
|
||||
{ const fp = await kb.fastPath('What is Other Site?'); ok(!fp || !String(fp.id).startsWith('othersite:'), 'other sites never take the fast path'); }
|
||||
{ const r = await bot.answer(GENERAL + ' on Other Site'); ok(!r.canned, 'a question naming another site skips this site\'s instant answers (' + r.kb + ')'); }
|
||||
{ const r = await bot.answer('I need a real person, my order on Other Site failed'); ok(r.handoff === true, 'a hand-off still wins when another site is named'); }
|
||||
{ const r = await bot.answer(bot.CANNED.find(c => c.id === 'about').q[0]); ok(r.canned && r.kb === 'c-about', 'this site\'s own name keeps the instant answer'); }
|
||||
{ const own = await kb.own(); ok(own.length === seeds.length && own.every(e => !e.site), 'publish set = this site\'s own entries only'); }
|
||||
|
||||
// 5. the scripted Q&A (home questions)
|
||||
const qaFile = path.join(ROOT, 'qa', 'chat-qa.json');
|
||||
if (fs.existsSync(qaFile)) {
|
||||
const qa = JSON.parse(fs.readFileSync(qaFile, 'utf8'));
|
||||
for (const t of qa.home || []) {
|
||||
const r = await bot.answer(t.q);
|
||||
if (t.kb) ok(r.kb === 'c-' + t.kb || (Array.isArray(r.kb) && r.kb.includes('c-' + t.kb)), 'Q&A "' + t.q + '" -> ' + t.kb + ' (got ' + JSON.stringify(r.kb) + ')');
|
||||
for (const m of t.must || []) ok(new RegExp(m, 'i').test(r.reply) || new RegExp(m, 'i').test(lastPrompt), 'Q&A "' + t.q + '" mentions /' + m + '/');
|
||||
}
|
||||
}
|
||||
or.close();
|
||||
console.log((fail ? 'FAILED ' : 'ok ') + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,219 @@
|
||||
// ViralAdSource end-to-end test on a local anvil chain (no fork, nothing leaves this machine, no real POL, no real people).
|
||||
// Deploys the real VASShop (../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:
|
||||
// sign-in by wallet; O posts an ad; R1 reshares it (step 1); R2 reshares through R1's link (step 2, same branch);
|
||||
// a visitor through R2's link -> verified view booked to R2 + ad credits; a verified click carries the branch (s2/s3 on LinkSpin links);
|
||||
// the family tree sums it up; sign-ups through R2's link: a clean one passes every check (pending reward + keeper voucher),
|
||||
// a throwaway email is rejected, R2's own device is rejected, someone already in the network is rejected;
|
||||
// B arrives through R1's link and buys a Boost: the contract pays R1 the resharer cut, the pot, the company, to the wei;
|
||||
// rewards relay (payouts ON in this test only): claimReward pays R2 from the pot; a replay is refused by the contract;
|
||||
// the staging test switch works on a staging host and is refused on the real domain.
|
||||
// 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 = 8581, PORT = 3341, 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'];
|
||||
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, 600) : '')); } };
|
||||
process.on('exit', () => { for (const p of procs) try { p.kill(); } catch (e) {} });
|
||||
|
||||
// stand-in hub: resolve by wallet / ref / id / email; everyone else is unknown (brand new)
|
||||
const people = new Map(); const knownEmails = new Set(['already@example.org']);
|
||||
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 === '/health') return r.end('{"ok":true}');
|
||||
if (q.url !== '/v1/resolve') return r.end('{"ok":true}');
|
||||
if (j.email) return r.end(JSON.stringify({ person: knownEmails.has(j.email) ? { id: 'h_' + 'e'.repeat(16), username: 'known', wallet: null, blocked: false } : null }));
|
||||
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: w, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null } : null }));
|
||||
}).listen(HPORT, '127.0.0.1').unref();
|
||||
|
||||
// a browser: its own cookie jar and user agent (so its own visitor key)
|
||||
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 });
|
||||
const sig = await w.signMessage(ch.j.message);
|
||||
return c.post('/api/auth/verify', { address: w.address, signature: sig });
|
||||
}
|
||||
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 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]), relay = new ethers.Wallet(K[7], provider);
|
||||
const [S, O, R1, R2, B] = [K[2], K[3], K[4], K[5], K[6]].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: 'owner', sponsor: lc(S) });
|
||||
people.set(lc(R1), { id: 'h_' + '1'.repeat(16), username: 'reshareone', sponsor: lc(S) });
|
||||
people.set(lc(R2), { id: 'h_' + '2'.repeat(16), username: 'resharetwo', sponsor: lc(R1) });
|
||||
people.set(lc(B), { id: 'h_' + 'b'.repeat(16), username: 'buyerb', sponsor: lc(O) });
|
||||
|
||||
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
|
||||
const feedA = art('MockV3Aggregator'), shopA = art('VASShop');
|
||||
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, 1000, [500, 500, 500, 500, 500], 25, 10, 0);
|
||||
await shopC.waitForDeployment(); await (await shopC.setSku(1, 500, 500, true)).wait();
|
||||
const CA = await shopC.getAddress(); console.log('VASShop at', CA);
|
||||
await (await deployer.sendTransaction({ to: relay.address, value: ethers.parseEther('1') })).wait();
|
||||
|
||||
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: 'vas.test.saasy.top', STAGING: '1', ADMIN_TOKEN: ADMIN, LINK_PROBE: '0', VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '50',
|
||||
CREDITS_VIEWS: '1', CHAIN_ID: '31337', CHAIN_RPC: RPC, CONTRACT_ADDRESS: CA, KEEPER_KEY: K[1], RELAY_KEY: K[7], SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '300',
|
||||
REWARD_PAYOUTS: '1', HUB_URL: 'http://127.0.0.1:' + HPORT, HUB_SECRET, HUB_SITE: 'viraladsource', HUB_ENABLED: '0', HUB_SSO: 'off', NETWORK_LOOKUP_URL: '', NODE_ENV: 'test', LS_TRACK: '0', OPENROUTER_KEY: '' });
|
||||
delete env.DOCSTORE_URL;
|
||||
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 ['/', '/my', '/boost', '/rewards', '/join', '/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/.test(t), 'page ' + p + ' 200, no dashes'); }
|
||||
const cfg = await (await fetch(BASE + '/api/config')).json();
|
||||
ok(cfg.split.resharerBps === 2000 && cfg.split.live === true && cfg.reward.cents === 25, 'config reads the live split from the contract', cfg.split);
|
||||
|
||||
console.log('\n-- sign-in, ad, reshares');
|
||||
const cO = client('Mozilla/5.0 owner'), cR1 = client('Mozilla/5.0 r1'), cR2 = client('Mozilla/5.0 r2'), cB = client('Mozilla/5.0 buyer');
|
||||
for (const [c, w] of [[cO, O], [cR1, R1], [cR2, R2], [cB, B]]) { 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 === 'owner', 'membership + username from the hub', me.j);
|
||||
const bad = await cO.post('/api/my/ad', { headline: 'x', line1: 'y', link: 'https://example.com' }); ok(bad.status === 400, 'short headline refused');
|
||||
const ad = await cO.post('/api/my/ad', { headline: 'Free traffic tool for your page', line1: 'Rotate every page you promote', link: 'https://example.com/offer' });
|
||||
ok(ad.j.ok && /\/s\/[a-z0-9]{8}$/.test(ad.j.source), 'ad posted with a source link', ad.j);
|
||||
const rootCode = ad.j.source.split('/s/')[1]; const adId = ad.j.ad.id;
|
||||
let r = await cR1.get('/s/' + rootCode); ok(r.status === 200 && cR1.jar['vas.via'], 'opening a share link tags the visitor');
|
||||
const s1 = await cR1.post('/api/my/reshare', { adId, from: rootCode }); ok(s1.j.ok && s1.j.step === 1 && s1.j.created, 'R1 reshare = step 1', s1.j);
|
||||
const again = await cR1.post('/api/my/reshare', { adId }); ok(again.j.code === s1.j.code && !again.j.created, 'one unique link per member per ad');
|
||||
await cR2.get('/s/' + s1.j.code);
|
||||
const s2 = await cR2.post('/api/my/reshare', { adId, from: s1.j.code }); ok(s2.j.ok && s2.j.step === 2, 'R2 reshare through R1 = step 2', s2.j);
|
||||
const own = await cO.post('/api/my/reshare', { adId }); ok(own.j.own && own.j.code === rootCode, 'the owner gets their source link back');
|
||||
|
||||
console.log('\n-- verified views, credits, clicks');
|
||||
const cV = client('Mozilla/5.0 visitor one');
|
||||
await cV.get('/s/' + s2.j.code);
|
||||
const w1 = await cV.get('/api/wire?page=share&s=' + s2.j.code); ok(w1.j.ticket && w1.j.share.step === 2 && w1.j.share.resharer === 'resharetwo', 'share page data + ticket', w1.j.share);
|
||||
const early = await cV.post('/api/visit/seen', { ticket: w1.j.ticket, visibleMs: 2500 }); ok(early.j.verified === false && early.j.why === 'early', 'an early send is refused');
|
||||
await sleep(2100);
|
||||
const seen = await cV.post('/api/visit/seen', { ticket: w1.j.ticket, visibleMs: 2500 }); ok(seen.j.verified && seen.j.views === 1 && seen.j.credited === 1, 'verified view booked to the branch', seen.j);
|
||||
const self = await cR2.get('/api/wire?page=share&s=' + s2.j.code); await sleep(2100); const selfSeen = await cR2.post('/api/visit/seen', { ticket: self.j.ticket, visibleMs: 2500 });
|
||||
ok(selfSeen.j.verified && selfSeen.j.credited === 0, 'a resharer viewing their own link earns nothing', selfSeen.j);
|
||||
r = await cV.get('/go/' + adId + '?s=' + s2.j.code + '&p=share&v=' + seen.j.vt); ok(r.status === 302 && r.loc === 'https://example.com/offer', 'click relay to the ad link', r.loc);
|
||||
const my2 = await cR2.get('/api/my'); ok(my2.j.credits.earned === 10 && my2.j.reshares[0].views === 1 && my2.j.reshares[0].clicks === 1, 'R2 credits + the share counts', { c: my2.j.credits, s: my2.j.reshares[0] });
|
||||
|
||||
console.log('\n-- L2 sign-ups through R2\'s link');
|
||||
const join = async (c, email, waitMs) => { const f = await c.get('/api/join/form'); await sleep(waitMs); return c.post('/api/join', { email, form: f.j.form }); };
|
||||
const cJ = client('Mozilla/5.0 newcomer'); await cJ.get('/s/' + s2.j.code);
|
||||
const fast = await join(cJ, 'fresh.person@example.net', 0); ok(fast.j.ok, 'join accepted (no mail on staging)', fast.j);
|
||||
let su = await admin('/api/admin/signups'); let row = su.signups.find(x => x.email === 'fresh.person@example.net');
|
||||
ok(row && row.status === 'unconfirmed' && /\/confirm\?t=/.test(row.confirmLink || ''), 'staging admin sees the confirm link', row);
|
||||
// a slow, clean join from another browser
|
||||
const cJ2 = client('Mozilla/5.0 newcomer two'); await cJ2.get('/s/' + s2.j.code);
|
||||
await join(cJ2, 'second.newcomer@example.net', 4300);
|
||||
su = await admin('/api/admin/signups'); row = su.signups.find(x => x.email === 'second.newcomer@example.net');
|
||||
const t = new URL(row.confirmLink).searchParams.get('t');
|
||||
const cf = await cJ2.post('/api/confirm', { t }); ok(cf.j.ok && cf.j.status === 'passed', 'clean sign-up passes every check', cf.j);
|
||||
su = await admin('/api/admin/signups'); row = su.signups.find(x => x.email === 'second.newcomer@example.net');
|
||||
ok(/dry/.test(row.checks.hubNew) && row.checks.notSelf === 'pass' && row.checks.throwaway === 'pass', 'checks recorded (hub dry, not self, not throwaway)', row.checks);
|
||||
let rw = await admin('/api/admin/rewards'); const rew = rw.rewards.find(x => x.signup === row.id);
|
||||
ok(rew && rew.cents === 25 && rew.voucher && rew.voucher.signed, 'pending reward with a keeper voucher', rew);
|
||||
// the fast one: fraud score holds it
|
||||
row = (await admin('/api/admin/signups')).signups.find(x => x.email === 'fresh.person@example.net');
|
||||
await cJ.post('/api/confirm', { t: new URL(row.confirmLink).searchParams.get('t') });
|
||||
row = (await admin('/api/admin/signups')).signups.find(x => x.email === 'fresh.person@example.net');
|
||||
ok(row.status === 'passed' || row.status === 'held', 'a form filled instantly scores high (' + row.status + ', score ' + (row.checks.fraud || {}).score + ')');
|
||||
// throwaway, already-known and self
|
||||
const cJ3 = client('Mozilla/5.0 throwaway'); await cJ3.get('/s/' + s2.j.code); await join(cJ3, 'abc@mailinator.com', 4300);
|
||||
const cJ4 = client('Mozilla/5.0 known'); await cJ4.get('/s/' + s2.j.code); await join(cJ4, 'already@example.org', 4300);
|
||||
const cSelf = client('Mozilla/5.0 r2', cR2.xff); // the same browser as R2 (same visitor key)
|
||||
await cSelf.get('/s/' + s2.j.code); await join(cSelf, 'my.other.address@example.net', 4300);
|
||||
su = await admin('/api/admin/signups');
|
||||
for (const [e, want] of [['abc@mailinator.com', 'throwaway email'], ['already@example.org', 'already in the network'], ['my.other.address@example.net', "the resharer's own device"]]) {
|
||||
const x = su.signups.find(y => y.email === e); await cJ.post('/api/confirm', { t: new URL(x.confirmLink).searchParams.get('t') });
|
||||
const y = (await admin('/api/admin/signups')).signups.find(z => z.email === e); ok(y.status === 'rejected' && y.fail.includes(want), 'rejected: ' + want, y);
|
||||
}
|
||||
|
||||
console.log('\n-- Boost through R1\'s branch, to the wei');
|
||||
await cB.post('/api/my/ad', { headline: 'Buyer ad for testing here', line1: 'A line about it', link: 'https://example.org/b' });
|
||||
await cB.get('/s/' + s1.j.code); // B came through R1's reshare link
|
||||
const od = await cB.post('/api/my/order', { qty: 1 }); ok(od.j.to === CA && od.j.resharer === lc(R1) && od.j.line === 2 && od.j.resharerName === 'reshareone', 'signed order names R1 and the 2-wallet line', 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, r10, o0, s0, b0] = await Promise.all([company, R1.address, O.address, S.address, B.address].map(a => bal(a, rc.blockNumber - 1)));
|
||||
const price = BigInt(od.j.wei); const res = price * 2000n / 10000n, pot = price * 1000n / 10000n;
|
||||
const [c1, r11, o1, s1b, b1] = await Promise.all([company, R1.address, O.address, S.address, B.address].map(a => bal(a)));
|
||||
ok(r11 - r10 === res, 'R1 got exactly 20% (' + ethers.formatEther(res) + ' POL)', (r11 - r10).toString());
|
||||
ok(c1 - c0 === price - res - pot && o1 === o0 && s1b === s0, 'company got 70% (nobody in the line has bought), sponsors 0', (c1 - c0).toString());
|
||||
ok(b0 - b1 === price + rc.gasUsed * rc.gasPrice, 'the 1% overpay came back in the same transaction');
|
||||
ok((await shopC.potBalance()) === pot, 'reward pot holds 10%');
|
||||
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) break; await sleep(250); }
|
||||
const L = await (await fetch(BASE + '/api/ledger')).json();
|
||||
ok(L.items.length === 1 && L.items[0].resharer && L.items[0].resharer.name === 'reshareone' && L.items[0].potWei === pot.toString(), 'ledger shows the resharer cut and the pot', L.items[0]);
|
||||
const tr = await admin('/api/admin/tree?ad=' + adId);
|
||||
ok(tr.totals.shares === 2 && tr.totals.reach === 2 && tr.branches.length === 1 && tr.branches[0].under === 1 && tr.branches[0].views === 1 && tr.branches[0].signups >= 1 && tr.branches[0].boosts === 1, 'family tree: 1 branch, 2 steps, views + sign-ups + the Boost roll up', tr);
|
||||
|
||||
console.log('\n-- reward relay (payouts ON here only, local chain)');
|
||||
const before = await provider.getBalance(R2.address, await provider.getBlockNumber());
|
||||
const pay = await admin('/api/admin/rewards/pay', {}); ok(pay.relayed >= 1, 'relayed claimReward', pay);
|
||||
for (let i = 0; i < 40; i++) { rw = await admin('/api/admin/rewards'); if (rw.rewards.some(x => x.status === 'paid')) break; await sleep(250); }
|
||||
for (let i = 0; i < 40; i++) { rw = await admin('/api/admin/rewards'); if (rw.rewards.filter(x => x.status === 'paid').length === rw.rewards.filter(x => x.to === lc(R2)).length) break; await sleep(250); }
|
||||
const paidL = rw.rewards.filter(x => x.status === 'paid'); const paid = paidL[0]; const got = (await provider.getBalance(R2.address, await provider.getBlockNumber())) - before;
|
||||
const one = await shopC.rewardWei(25);
|
||||
ok(paidL.length >= 1 && got === paidL.reduce((t, x) => t + BigInt(x.weiPaid), 0n) && paidL.every(x => BigInt(x.weiPaid) === one), 'R2 got exactly $0.25 in POL per verified sign-up from the pot (' + paidL.length + ' x ' + ethers.formatEther(one) + ' POL)', { got: got.toString(), n: paidL.length });
|
||||
const v = rw.rewards.find(x => x.id === paid.id);
|
||||
const fullV = JSON.parse(fs.readFileSync(path.join(DATA, 'vas.json'), 'utf8')).rewards.find(x => x.id === v.id).voucher;
|
||||
let replay = null; try { await shopC.connect(relay).claimReward.staticCall(fullV.to, fullV.usdCents, fullV.unlockAt, BigInt(fullV.nonce), fullV.deadline, fullV.sig); } catch (e) { replay = e.shortMessage || e.message; }
|
||||
ok(/Nonce used/.test(String(replay)), 'the same voucher cannot be claimed twice', replay);
|
||||
const lg = await (await fetch(BASE + '/api/ledger')).json(); ok(lg.rewards.some(x => x.status === 'paid' && x.tx), 'paid reward on the public ledger with its tx');
|
||||
ok(!JSON.stringify(lg).includes('@example.net'), 'no emails on the public ledger');
|
||||
|
||||
console.log('\n-- staging switch + misc');
|
||||
const tm = await admin('/api/admin/test-member', { address: ethers.Wallet.createRandom().address, username: 'tester1' }); ok(tm.ok && tm.member.netOk && tm.member.testMember, 'staging test switch marks a test member');
|
||||
const rec = await (await fetch(BASE + '/api/recent')).json(); ok(rec.items.some(x => x.kind === 'reshare') && rec.items.some(x => x.kind === 'boost'), 'toasts carry reshares and Boosts');
|
||||
const kit = await (await fetch(BASE + '/api/promo-kit?u=owner')).json(); ok(kit.links[0].url.endsWith('/owner') && !/[—–]/.test(JSON.stringify(kit)), 'promo kit with the username');
|
||||
r = await cV.get('/owner'); ok(r.status === 302 && r.loc === '/s/' + rootCode, '/<username> opens their ad at its source');
|
||||
r = await cV.get('/splashpg.php?pid=1&r=nobody'); ok(r.status === 301 && r.loc === '/', 'old *.php links go to the front page');
|
||||
const chat = await (await fetch(BASE + '/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 chat' }, body: JSON.stringify({ message: 'Do I get paid for resharing?' }) })).json().catch(() => ({}));
|
||||
ok(chat && /results/i.test(JSON.stringify(chat)), 'chatbot answers about resharing rewards', chat);
|
||||
app.kill(); await sleep(300);
|
||||
// the switch is refused on the real domain
|
||||
const env2 = Object.assign({}, env, { SITE_HOST: 'viraladsource.com', PORT: String(PORT + 5), DATA_DIR: DATA + '-prod' }); fs.mkdirSync(env2.DATA_DIR, { recursive: true });
|
||||
const app2 = spawn(process.execPath, ['server.js'], { cwd: APP, env: env2, stdio: 'ignore' }); procs.push(app2);
|
||||
for (let i = 0; i < 80; i++) { try { if ((await fetch('http://127.0.0.1:' + (PORT + 5) + '/health')).ok) break; } catch (e) {} await sleep(150); }
|
||||
const tm2 = await fetch('http://127.0.0.1:' + (PORT + 5) + '/api/admin/test-member', { method: 'POST', headers: { 'x-admin-token': ADMIN, 'Content-Type': 'application/json' }, body: JSON.stringify({ address: B.address }) });
|
||||
ok(tm2.status === 403, 'test switch refused on viraladsource.com even with STAGING=1');
|
||||
fs.writeFileSync(path.join(OUT, 'e2e-app.log'), log);
|
||||
console.log('\n' + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
}
|
||||
main().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,139 @@
|
||||
// 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();
|
||||
if (s.startsWith('::ffff:')) return privateIp(s.slice(7));
|
||||
return s === '::' || s === '::1' || s.startsWith('fc') || s.startsWith('fd') || s.startsWith('fe80') || 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; VASCheck/1.0; +https://viraladsource.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 };
|
||||
}
|
||||
|
||||
module.exports = { checkLink, checkImage, imageInfo, frameVerdict, probeLink, fetchImage, privateIp, MAX_UPLOAD };
|
||||
@@ -0,0 +1,556 @@
|
||||
// ViralAdSource web app (viraladsource.com rebuild, Marty approved 2026-11-16). Plain Node http server, no framework (the InstantAdPay /
|
||||
// Downline Banners / VBB / ViralAdBlitz pattern).
|
||||
// "Every ad has a source. Watch yours travel." A network member (network sign-in through the hub, membership checked with the hub)
|
||||
// posts one free text ad. Anyone reshares it with their own unique reshare link (/s/<code>); each reshare is a branch of the ad's
|
||||
// family tree (tree.js). Rewards are for verified results only (config.js): L1 Boost resharer cut on chain (VASShop), L2 verified
|
||||
// brand-new network member (signup.js, payouts OFF until Marty confirms), L3 verified views -> ad credits (wire.js).
|
||||
// Pages: / (front), /s/<code> (an ad through a reshare link), /a/<id> (an ad at its source), /<username> (a member's ad), /my, /boost,
|
||||
// /rewards, /join, /confirm, /ledger, /contract, /promote, /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 tree = require('./tree');
|
||||
const signup = require('./signup');
|
||||
const safety = require('./safety');
|
||||
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 lstrack = require('./lstrack');
|
||||
const chatbot = require('./chatbot');
|
||||
|
||||
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 CODE_RE = /^[a-z0-9]{8}$/;
|
||||
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);
|
||||
// the staging-only test switch can never run on the real domain
|
||||
const TEST_SWITCH = C.staging && !/(^|\.)viraladsource\.com$/i.test(C.site);
|
||||
|
||||
// ---- 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;
|
||||
}
|
||||
async function fillUsername(addr) {
|
||||
const m = store.member(addr); if (!m || m.username) return;
|
||||
const n = await netMember({ a: addr }).catch(() => null);
|
||||
if (n && n.address === m.address && NAME_RE.test(n.username || '') && !store.memberByName(n.username)) store.upsertMember(addr, { username: n.username });
|
||||
}
|
||||
const netVerified = m => !!m && m.netOk === true;
|
||||
async function verifyNet(addr, email) {
|
||||
const m = store.member(addr); if (!m || netVerified(m)) return;
|
||||
const h = await hubpeople.byWallet(addr);
|
||||
let known = h.ok && !!h.person, down = !h.ok;
|
||||
if (!known && !down && email) { const e = await hubpeople.resolve({ email: String(email).trim().toLowerCase() }); if (e.ok) known = !!(e.person && !e.person.blocked); else down = true; }
|
||||
if (!known && down) { const n = await netMember({ a: addr }).catch(() => null); known = (n && n.address === m.address) || m.via === 'iap' || m.via === 'linkspin' || m.via === 'hub'; }
|
||||
if (known) { store.upsertMember(addr, { netOk: true, netAt: Date.now(), netBy: down ? 'fallback' : 'hub' }); await fillUsername(addr).catch(() => {}); }
|
||||
}
|
||||
// a confirmed L2 sign-up written to the hub (HUB_JOIN=1 only): POST /v1/join {email, ref, username}, sponsor = the resharer
|
||||
async function hubJoin(email, ref, username) {
|
||||
if (!hubpeople.on()) return { ok: false };
|
||||
const raw = JSON.stringify({ email, ref: ref || undefined, username: username || undefined }); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', String(process.env.HUB_SECRET).trim()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + '/v1/join', { method: 'POST', body: raw, signal: AbortSignal.timeout(8000),
|
||||
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || 'viraladsource').trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
|
||||
if (r.status !== 200) return { ok: false, status: r.status };
|
||||
const j = await r.json(); return { ok: true, created: !!j.created, person: j.person || null };
|
||||
}
|
||||
const session = req => store.session(cookies(req)['vas.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, email).catch(() => {});
|
||||
store.seenOn(v.wallet, visitorKey(req), ipKey(req));
|
||||
return cookie('vas.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true);
|
||||
},
|
||||
landing: to => to, signinPath: to => to });
|
||||
hubevents.init({ dataDir: C.dataDir, site: 'viraladsource', end: who => store.endSessions(x => who.match(x) || who.match(store.member(x.address)), who.before) });
|
||||
|
||||
// ---- old site links (the YourFreeWorld site): /?<old username> and /index.php?<old> -> that person's ad here (oldrefs.json, matched
|
||||
// by email to the hub, loaded by POST /api/admin/oldrefs at the domain switch); /splashpg.php, /lcp.php ?r=<old> the same; 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;
|
||||
}
|
||||
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 old = (lp === '/splashpg.php' || lp === '/lcp.php') ? String(u.searchParams.get('r') || '') : (lp === '/' || lp === '/index.php') ? bare : '';
|
||||
const net = /^[A-Za-z0-9_.-]{2,40}$/.test(old) ? oldRefMap()[old.toLowerCase()] : null;
|
||||
return net ? '/' + encodeURIComponent(net) : '/';
|
||||
}
|
||||
|
||||
const PAGES = { '/': 'index.html', '/my': 'my.html', '/boost': 'boost.html', '/rewards': 'rewards.html', '/join': 'join.html', '/confirm': 'confirm.html', '/ledger': 'ledger.html',
|
||||
'/contract': 'contract.html', '/admin': 'admin.html', '/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html' };
|
||||
const RESERVED = new Set(['api', 'assets', 'art', 'go', 'r', 's', 'a', 'sso', 'health', 'promote', 'sitemap.xml', 'robots.txt', 'favicon.ico', 'index.php', 'my', 'boost', 'rewards', 'join', 'confirm', 'ledger', 'contract', 'admin', 'terms', 'disclaimer', 'privacy', 'how', 'tree']);
|
||||
const challenges = new Map();
|
||||
const tickets = new Map();
|
||||
const srcHost = raw => { try { const u = new URL(String(raw || '')); if (!/^https?:$/.test(u.protocol)) return ''; const h = u.hostname.toLowerCase().replace(/^www\./, ''); return h === C.site || h.endsWith('.' + C.site) || !h.includes('.') ? '' : h.slice(0, 80); } catch (e) { return ''; } };
|
||||
// the reshare tag a visitor carries: "<code>.<ms>" (last touch, VIA_DAYS)
|
||||
function viaOf(req) { const v = String(cookies(req)['vas.via'] || ''); const m = /^([a-z0-9]{8})\.(\d{10,14})$/.exec(v); return m ? { code: m[1], at: Number(m[2]) } : null; }
|
||||
const viaCookie = code => cookie('vas.via', code + '.' + Date.now(), C.viaDays * 86400, false);
|
||||
|
||||
function issueTicket(req, page, shown, src, via) {
|
||||
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), via: via || null, 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 todayStats = () => { const t = store.today(); return { views: t.views || 0, vclicks: t.vclicks || 0, reshares: t.reshares || 0, joins: t.confirms || 0, ads: store.liveAds().length }; };
|
||||
const joinUrl = ref => ref ? C.joinUrl.split('{ref}').join(encodeURIComponent(ref)) : C.joinUrl.replace(/\/join\/\{ref\}.*$/, '/').replace(/[?&]ref=\{ref\}/, '').split('{ref}').join('');
|
||||
const MACRO = /\{(clickid|placement)\}|%7B(clickid|placement)%7D/gi;
|
||||
function clickLink(a, placement) {
|
||||
const l = String(a.link || ''); if (!l.match(MACRO)) return l;
|
||||
const v = { clickid: crypto.randomBytes(8).toString('hex'), placement: String(placement || 'site').replace(/[^a-z0-9-]/gi, '').slice(0, 20) || 'site' };
|
||||
return l.replace(MACRO, (x, p1, p2) => v[(p1 || p2).toLowerCase()]);
|
||||
}
|
||||
function cleanText(s, max) { return String(s == null ? '' : s).replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(/[–—]/g, '-').replace(/\s+/g, ' ').trim().slice(0, max + 1); }
|
||||
const uname = a => { const m = store.member(a); return m && m.username ? m.username : null; };
|
||||
const shareUrl = s => 'https://' + C.site + '/s/' + s.id;
|
||||
function myEarned(me) {
|
||||
let wei = 0n; const items = [];
|
||||
for (const x of wire.purchases()) for (const p of x.pays || []) if (p.to === me && p.kind > 0) { try { wei += BigInt(p.wei); } catch (e) {} items.push({ tx: String(x.key).split(':')[0], at: (x.blockAt ? x.blockAt * 1000 : x.at), kind: p.kind, depth: p.depth, wei: p.wei, failed: !!p.failed, buyerName: uname(x.buyer) }); }
|
||||
return { wei: wei.toString(), items: items.sort((a, b) => (b.at || 0) - (a.at || 0)).slice(0, 50) };
|
||||
}
|
||||
|
||||
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) || ADDR_RE.test(ref))) ex['Set-Cookie'] = cookie('vas.ref', ref, 30 * 86400, false);
|
||||
if (p === '/my' || p === '/admin') ex['X-Frame-Options'] = 'DENY';
|
||||
if (p === '/how' || p === '/tree') { res.writeHead(301, { Location: '/#how' }); return res.end(); }
|
||||
return sendFile(res, path.join(PUB, PAGES[p]), ex);
|
||||
}
|
||||
if (p === '/how' || p === '/tree') { res.writeHead(301, { Location: '/#' + p.slice(1) }); return res.end(); }
|
||||
// an ad through a reshare link: tag the visitor with the share (last touch), then the ad page
|
||||
const sm = /^\/s\/([a-z0-9]{8})\/?$/.exec(p);
|
||||
if (sm) {
|
||||
const s = store.share(sm[1]); const a = s ? store.ad(s.adId) : null;
|
||||
if (!s || !a || a.status === 'removed') { res.writeHead(302, { Location: '/' }); return res.end(); }
|
||||
return sendFile(res, path.join(PUB, 'ad.html'), { 'Set-Cookie': viaCookie(s.id) });
|
||||
}
|
||||
const am = /^\/a\/(\d{1,9})\/?$/.exec(p);
|
||||
if (am) { const a = store.ad(am[1]); if (!a || a.status === 'removed') { res.writeHead(302, { Location: '/' }); return res.end(); } const r = tree.rootOf(a); res.writeHead(302, { Location: '/s/' + r.id }); return res.end(); }
|
||||
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 = ['/', '/rewards', '/boost', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy'].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/\nDisallow: /s/\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/<ad>?s=<share>&v=<verified token>&p=<placement> -> the ad's link (LinkSpin links carry the branch: s2 / s3)
|
||||
const gm = /^\/go\/(\d{1,9})$/.exec(p);
|
||||
if (gm) {
|
||||
const a = store.ad(gm[1]); if (!a || a.status === 'removed') { res.writeHead(302, { Location: '/' }); return res.end(); }
|
||||
const pl = String(u.searchParams.get('p') || '').slice(0, 20);
|
||||
const sc = String(u.searchParams.get('s') || ''); let s = CODE_RE.test(sc) ? store.share(sc) : null; if (s && s.adId !== a.id) s = null;
|
||||
if (!isBot(req) && !limited(req, 'click', 600, 3600000)) { const vk = visitorKey(req); const ss = session(req); wire.click(a, vk, wire.vtokenOk(vk, u.searchParams.get('v')), ss ? ss.address : null, s, pl); }
|
||||
const dest = lstrack.dest(a) || clickLink(a, pl);
|
||||
res.writeHead(302, { Location: lstrack.withBranch(dest, s, s ? uname(s.owner) : null), 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end();
|
||||
}
|
||||
// a member's ad: viraladsource.com/<network username> -> their ad at its source (with the ref cookie); no ad yet -> the front page
|
||||
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 a = m ? store.adOf(m.address) : null;
|
||||
if (a && a.status === 'live') { const r = tree.rootOf(a); res.writeHead(302, { Location: '/s/' + r.id, 'Set-Cookie': cookie('vas.ref', name, 30 * 86400, false) }); return res.end(); }
|
||||
const h = m ? { ok: true, person: m } : await hubpeople.byRef(name.toLowerCase()).catch(() => ({ ok: false }));
|
||||
if (h.ok && h.person) { res.writeHead(302, { Location: '/?ref=' + encodeURIComponent(name) }); return res.end(); }
|
||||
}
|
||||
}
|
||||
|
||||
// -- public API
|
||||
if (p === '/api/config' && req.method === 'GET') {
|
||||
const live = await shop.liveRules().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,
|
||||
boost: C.boost, split: live ? { resharerBps: live.resharerBps, potBps: live.potBps, levelBps: live.levelBps, maxDepth: 20, live: true } : Object.assign({ proposal: true }, C.split),
|
||||
reward: { cents: C.reward.cents, dailyCap: C.reward.dailyCap, payouts: C.reward.payouts, tiers: C.reward.tiers, proposal: true }, credits: C.credits, visitSeconds: C.visitSeconds, ad: C.ad,
|
||||
sso: networksso.enabled() || networksso.hubOn(), shop: { live: shop.watching() && shop.signerOn(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, joinUrl: joinUrl('') });
|
||||
}
|
||||
// everything a page shows, with its visit ticket. page=front|share|other, s=<share code> on share pages
|
||||
if (p === '/api/wire' && req.method === 'GET') {
|
||||
const kind = ['front', 'share'].includes(u.searchParams.get('page')) ? u.searchParams.get('page') : 'other';
|
||||
const out = { today: todayStats(), week: wire.weekStats() }; const shown = []; let via = null;
|
||||
const used = new Set();
|
||||
if (kind === 'front') { out.board = wire.board(); out.board.forEach(x => { shown.push({ id: x.id, share: null, slot: 'board' }); used.add(x.id); }); }
|
||||
if (kind === 'share') {
|
||||
const s = store.share(String(u.searchParams.get('s') || '')); const a = s ? store.ad(s.adId) : null;
|
||||
if (!s || !a || a.status !== 'live') return json(res, 404, { error: 'That ad is not running right now.' });
|
||||
const anc = tree.ancestry(s); const me = session(req);
|
||||
out.ad = wire.adCard(a, { href: '/go/' + a.id + '?s=' + s.id });
|
||||
out.share = { code: s.id, step: s.step, resharer: s.step > 0 ? uname(s.owner) : null, owner: uname(a.owner), chain: anc.slice(0, 6).map(x => uname(x.owner)).filter(Boolean), branchCount: Math.max(0, store.sharesOf(a.id).length - 1) };
|
||||
if (me) { const mine = store.shareOf(a.id, me.address); out.mine = mine ? { code: mine.id, url: shareUrl(mine), own: me.address === a.owner } : null; }
|
||||
shown.push({ id: a.id, share: s.id, slot: 'share' }); used.add(a.id); via = s.id;
|
||||
out.joinPath = '/join';
|
||||
}
|
||||
// "Featured with credits" places on every page
|
||||
const cp = wire.creditPicks(C.credits.slots, used); out.featured = cp.map(a => wire.adCard(a, { credit: true }));
|
||||
cp.forEach(a => shown.push({ id: a.id, share: null, slot: 'credit' }));
|
||||
const hunt = u.searchParams.get('hunt') === '1' || srcHost(u.searchParams.get('src')) === 'polhunter.com';
|
||||
out.ticket = hunt ? null : issueTicket(req, kind === 'share' ? 'share:' + via : kind, shown, u.searchParams.get('src'), via);
|
||||
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) } : {}));
|
||||
}
|
||||
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/recent' && req.method === 'GET') {
|
||||
const cut = Date.now() - 30 * 60000;
|
||||
const ads = store.liveAds().filter(a => a.createdAt > cut).slice(-6).map(a => ({ kind: 'ad', key: 'a' + a.id, at: a.createdAt, name: uname(a.owner), headline: a.headline }));
|
||||
const rs = store.state().shares.filter(s => s.step > 0 && s.createdAt > cut).slice(-6).map(s => ({ kind: 'reshare', key: 's' + s.id, at: s.createdAt, name: uname(s.owner), step: s.step }));
|
||||
const boosts = proof.ledger(10).items.filter(x => x.at && x.at > cut).map(x => ({ kind: 'boost', key: 'b' + x.tx + x.orderId, at: x.at, name: x.buyerName, resharer: x.resharer ? x.resharer.name : null }));
|
||||
return json(res, 200, { items: ads.concat(rs, boosts).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: 'Boosts are not open 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.boost.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.boost.maxQty + ' Boosts.' });
|
||||
try { return json(res, 200, Object.assign({ usd: C.boost.usd * qty, days: C.boost.days * qty }, await shop.quote(C.boost.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 }); }
|
||||
}
|
||||
// L2: join the network free through a reshare link. GET /api/join/form -> a form token (when the form was shown);
|
||||
// POST /api/join {email, username, form} -> confirm mail (staging: no mail); POST /api/confirm {t}
|
||||
if (p === '/api/join/form' && req.method === 'GET') {
|
||||
const via = viaOf(req); const s = via ? store.share(via.code) : null; const a = s ? store.ad(s.adId) : null;
|
||||
const t = Date.now() + '.' + hash('form|' + Date.now() + '|' + visitorKey(req)).slice(0, 16);
|
||||
return json(res, 200, { form: t, via: s ? { resharer: s.step > 0 ? uname(s.owner) : null, owner: a ? uname(a.owner) : null, headline: a ? a.headline : null } : null, mail: !!C.mail.url, staging: C.staging });
|
||||
}
|
||||
if (p === '/api/join' && req.method === 'POST') {
|
||||
if (isBot(req) || limited(req, 'join', 8, 3600000)) return json(res, 429, { error: 'Too many sign-ups from this connection. Try again later.' });
|
||||
const b = await readBody(req); const via = viaOf(req);
|
||||
const fm = /^(\d{13})\.([0-9a-f]{16})$/.exec(String(b.form || ''));
|
||||
const formOk = fm && hash('form|' + fm[1] + '|' + visitorKey(req)).slice(0, 16) === fm[2];
|
||||
if (!formOk) return json(res, 400, { error: 'Reload the page and try again.' });
|
||||
if (session(req)) return json(res, 400, { error: 'You are already signed in with a network account.' });
|
||||
const r = await signup.join({ email: b.email, username: b.username, share: via ? via.code : null, vk: visitorKey(req), iph: ipKey(req), ua: req.headers['user-agent'], formMs: Date.now() - Number(fm[1]), clickAt: via ? via.at : null });
|
||||
if (r.error) return json(res, 400, r);
|
||||
return json(res, 200, { ok: true, mailed: r.mailed, staging: C.staging && !r.mailed });
|
||||
}
|
||||
if (p === '/api/confirm' && req.method === 'POST') {
|
||||
if (limited(req, 'confirm', 30, 3600000)) return json(res, 429, { error: 'Too many tries.' });
|
||||
const b = await readBody(req); const r = await signup.confirm(String(b.t || ''));
|
||||
if (r.error) return json(res, 400, r);
|
||||
return json(res, 200, { ok: true, status: r.signup.status, joinUrl: joinUrl(''), signIn: '/my' });
|
||||
}
|
||||
|
||||
// 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\nViralAdSource 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(() => {});
|
||||
store.seenOn(a, visitorKey(req), ipKey(req));
|
||||
return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('vas.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('vas.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('vas.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) });
|
||||
}
|
||||
|
||||
// -- 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' });
|
||||
store.seenOn(me, visitorKey(req), ipKey(req)); // the L2 "not the resharer's own device or connection" check
|
||||
if (p === '/api/my' && req.method === 'GET') {
|
||||
await verifyNet(me).catch(() => {}); const m = store.member(me);
|
||||
const a = store.adOf(me); const root = a && a.status !== 'removed' ? tree.rootOf(a) : null;
|
||||
let ls = null;
|
||||
if (a) { const stt = lstrack.state(a); ls = { on: lstrack.on(), track: a.track !== false, state: stt, link: stt === 'tracked' ? a.ls.link : null, clicks: null };
|
||||
if (stt === 'tracked' && m.username) { const cs = await lstrack.clicks(m.username).catch(() => null); if (cs && cs[String(a.id)]) ls.clicks = cs[String(a.id)]; } }
|
||||
const mine = store.sharesBy(me).filter(x => x.step > 0).sort((x, y) => y.createdAt - x.createdAt).slice(0, 100).map(x => { const ad = store.ad(x.adId); return { code: x.id, url: shareUrl(x), step: x.step, adId: x.adId, headline: ad ? ad.headline : null, live: !!(ad && ad.status === 'live'), owner: ad ? uname(ad.owner) : null, views: x.views || 0, clicks: x.vclicks || 0, signups: x.signups || 0, boosts: x.boosts || 0, under: x.children || 0 }; });
|
||||
const cr = store.credits(me);
|
||||
return json(res, 200, { address: me, username: m.username, netVerified: netVerified(m), test: !!m.testMember,
|
||||
ad: a ? { id: a.id, headline: a.headline, line1: a.line1, line2: a.line2, link: a.link, status: a.status, views: a.views || 0, clicks: a.clicks || 0, vclicks: a.vclicks || 0, createdAt: a.createdAt, track: a.track !== false, spin: !!a.spin, boostedUntil: wire.boostedUntil(a.id) || null } : null,
|
||||
source: root ? { code: root.id, url: shareUrl(root) } : null, tree: a ? tree.tree(a.id) : null, linkspin: ls, reshares: mine,
|
||||
credits: { earned: cr.earned, spent: cr.spent, balance: store.creditBalance(me), views: cr.views, nextAt: C.credits.views - (cr.views % C.credits.views), per: C.credits.per, every: C.credits.views },
|
||||
rewards: signup.mine(me), boosts: wire.purchases().filter(b => b.buyer === me).sort((x, y) => (y.at || 0) - (x.at || 0)).map(wire.boostView), earned: myEarned(me),
|
||||
joinUrl: joinUrl(''), boost: C.boost });
|
||||
}
|
||||
if (p === '/api/my/spins' && req.method === 'GET') {
|
||||
if (limited(req, 'spins', 120, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
|
||||
const m = store.member(me); if (!netVerified(m)) return json(res, 403, { error: 'Sign in with your network account to use your spin links.' });
|
||||
const r = await lstrack.spins(m.username); if (r.error) return json(res, 502, { error: r.error });
|
||||
return json(res, 200, { account: r.account !== false, spins: r.spins || [] });
|
||||
}
|
||||
if (p === '/api/my/ad' && req.method === 'POST') {
|
||||
if (limited(req, 'ad', 30, 3600000)) return json(res, 429, { error: 'Too many changes this hour.' });
|
||||
const m = store.member(me); await verifyNet(me).catch(() => {});
|
||||
if (!netVerified(m)) return json(res, 403, { error: 'Text ads are free for network members. Join InstantAdPay or LinkSpin free, then sign in here with that account.', join: joinUrl('') });
|
||||
const b = await readBody(req);
|
||||
const headline = cleanText(b.headline, C.ad.headline), line1 = cleanText(b.line1, C.ad.line), line2 = cleanText(b.line2, C.ad.line);
|
||||
if (headline.length < 3 || headline.length > C.ad.headline) return json(res, 400, { error: 'Write a headline of 3 to ' + C.ad.headline + ' characters.' });
|
||||
if (line1.length < 3 || line1.length > C.ad.line) return json(res, 400, { error: 'Write the first line in 3 to ' + C.ad.line + ' characters.' });
|
||||
if (line2.length > C.ad.line) return json(res, 400, { error: 'Keep the second line to ' + C.ad.line + ' characters.' });
|
||||
const lk = safety.checkLink(b.link, 'Your link'); if (lk.error) return json(res, 400, lk);
|
||||
// a LinkSpin spin link is accepted ONLY when LinkSpin confirms it is this member's own (signed partner endpoint)
|
||||
const sp = await lstrack.checkSpin(lk.url, m.username); if (sp.error) return json(res, 400, { error: sp.error });
|
||||
const spin = sp.spin ? sp.code : null;
|
||||
const cur = store.adOf(me);
|
||||
if (C.linkProbe && (!cur || cur.link !== lk.url)) { const pr = await safety.probeLink(lk.url, { frames: false }); if (pr.error) return json(res, 400, pr); }
|
||||
const track = b.track === undefined ? (cur ? cur.track !== false : true) : b.track !== false && b.track !== 'off' && b.track !== 0;
|
||||
if (cur) { Object.assign(cur, { headline, line1, line2, link: lk.url, track, spin, status: cur.status === 'paused' ? 'paused' : 'live' }); store.saveAd(cur); if (lstrack.on()) lstrack.ensureAd(cur).catch(() => {}); return json(res, 200, { ok: true, ad: { id: cur.id }, created: false, source: shareUrl(tree.rootOf(cur)) }); }
|
||||
const a = store.addAd({ owner: me, headline, line1, line2, link: lk.url, track, spin, status: 'live', views: 0, clicks: 0, vclicks: 0 }); store.bump('adsPosted');
|
||||
const root = tree.rootOf(a); wire.attachPending(me, a.id);
|
||||
if (lstrack.on()) lstrack.ensureAd(a).catch(() => {});
|
||||
return json(res, 200, { ok: true, ad: { id: a.id }, created: true, source: shareUrl(root) });
|
||||
}
|
||||
// reshare an ad: my unique reshare link for it (under the share link I came through, when it is for the same ad)
|
||||
if (p === '/api/my/reshare' && req.method === 'POST') {
|
||||
if (limited(req, 'reshare', 120, 3600000)) return json(res, 429, { error: 'Too many reshares this hour.' });
|
||||
const m = store.member(me); await verifyNet(me).catch(() => {});
|
||||
if (!netVerified(m)) return json(res, 403, { error: 'Resharing is free for network members. Sign in with your network account first.' });
|
||||
const b = await readBody(req); const a = store.ad(Number(b.adId));
|
||||
const via = viaOf(req); const from = CODE_RE.test(String(b.from || '')) ? String(b.from) : via ? via.code : null;
|
||||
const r = tree.reshare(a, me, from); if (r.error) return json(res, 400, r);
|
||||
return json(res, 200, { ok: true, code: r.share.id, url: shareUrl(r.share), step: r.share.step, created: r.created, own: !!r.own });
|
||||
}
|
||||
if (p === '/api/my/order' && req.method === 'POST') {
|
||||
if (!shop.watching() || !shop.signerOn()) return json(res, 503, { error: 'Boosts are not open 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.boost.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.boost.maxQty + ' Boosts.' });
|
||||
const a = store.adOf(me); if (!a || a.status !== 'live') return json(res, 400, { error: 'Post your text ad first. A Boost is for your ad.' });
|
||||
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.' });
|
||||
const line = lo.line.filter(x => x.wallet && x.wallet !== me).map(x => x.wallet);
|
||||
// the resharer whose branch sold it: the reshare link this buyer came through (last touch), never the buyer
|
||||
const via = viaOf(req); const vs = via ? store.share(via.code) : null;
|
||||
const resharer = vs && vs.step > 0 && vs.owner !== me ? vs.owner : null;
|
||||
{ const S0 = store.state(); S0.orderVia = S0.orderVia || {}; if (resharer) S0.orderVia[me] = { code: vs.id, at: Date.now() }; else delete S0.orderVia[me]; store.save(); } // which branch sold it (proof.js books it on that reshare link)
|
||||
try { return json(res, 200, Object.assign({ buyer: me, usd: C.boost.usd * qty, days: C.boost.days * qty, qty, adId: a.id, resharerName: resharer ? uname(resharer) : null }, await shop.order(me, C.boost.sku, qty, a.id, line, resharer))); }
|
||||
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 }); }
|
||||
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();
|
||||
return json(res, 200, { day: store.ctDay(), week: store.ctWeek(), staging: C.staging, testSwitch: TEST_SWITCH, config: { boost: C.boost, split: C.split, reward: C.reward, credits: C.credits, hubJoin: C.hubJoin },
|
||||
today: store.today(), totals: S.totals, members: store.members().length, ads: { live: store.liveAds().length, all: store.ads().length }, shares: S.shares.length,
|
||||
rows: { visits: store.visits().length, clicks: store.clicks().length, signups: store.signups().length, rewards: store.rewards().length },
|
||||
signup: signup.view(), 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 });
|
||||
}
|
||||
if (p === '/api/admin/signups' && req.method === 'GET') {
|
||||
const st0 = String(u.searchParams.get('status') || '');
|
||||
return json(res, 200, { signups: store.signups().filter(x => !st0 || x.status === st0).slice(-200).reverse().map(x => ({ id: x.id, status: x.status, email: x.email, username: x.username, share: x.share, resharer: x.resharer ? uname(x.resharer) || x.resharer : null,
|
||||
createdAt: x.createdAt, confirmedAt: x.confirmedAt || null, checks: x.checks || null, fail: x.fail || [], hold: x.hold || [], rewards: x.rewards || [], confirmLink: TEST_SWITCH ? x.confirmLink || null : undefined })) });
|
||||
}
|
||||
if (p === '/api/admin/signup' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, await signup.decide(String(b.id || ''), String(b.action || ''))); }
|
||||
if (p === '/api/admin/rewards' && req.method === 'GET') return json(res, 200, { payouts: C.reward.payouts, rewards: store.rewards().slice(-300).reverse().map(r => Object.assign({}, r, { voucher: r.voucher ? { nonce: r.voucher.nonce, deadline: r.voucher.deadline, unlockAt: r.voucher.unlockAt, signed: true } : null })) });
|
||||
if (p === '/api/admin/rewards/pay' && req.method === 'POST') { if (!C.reward.payouts) return json(res, 409, { error: 'Payouts are off (REWARD_PAYOUTS). Marty confirms the amounts first.' }); return json(res, 200, { relayed: await signup.payDue() }); }
|
||||
// staging only: mark a wallet as a test network member so the ad / reshare / tree flows can be tried without a real account
|
||||
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 m = store.upsertMember(a, { netOk: b.on !== false, netBy: 'test', testMember: b.on !== false, username: b.username || (store.member(a) || {}).username || null });
|
||||
return json(res, 200, { ok: true, member: m });
|
||||
}
|
||||
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 });
|
||||
}
|
||||
if (p === '/api/admin/ad' && req.method === 'POST') {
|
||||
const b = await readBody(req); const a = store.ad(b.id); if (!a) return json(res, 404, { error: 'not found' });
|
||||
if (!['live', 'paused', 'removed'].includes(b.status)) return json(res, 400, { error: 'status live | paused | removed' });
|
||||
a.status = b.status; a.note = cleanText(b.note, 200); store.saveAd(a); return json(res, 200, { ok: true, ad: a });
|
||||
}
|
||||
if (p === '/api/admin/tree' && req.method === 'GET') return json(res, 200, tree.tree(Number(u.searchParams.get('ad'))));
|
||||
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 (/^#?\d{1,9}$/.test(q)) { const ad = store.ad(Number(q.replace('#', ''))); a = ad ? ad.owner : null; } 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' });
|
||||
const rec = Object.assign({}, store.member(a)); delete rec.vks; delete rec.iphs;
|
||||
return json(res, 200, { address: a, record: rec, ad: store.adOf(a), reshares: store.sharesBy(a).length, credits: store.credits(a), rewards: signup.mine(a), 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 | ViralAdSource</title><body style="background:#EAF6F4;color:#0B2730;font-family:\'IBM Plex Sans\',system-ui,sans-serif;text-align:center;padding:40px 16px"><p style="font-size:22px;font-weight:700">This stream ran dry.</p><p><a style="color:#C4371B;font-weight:700" href="/">Back to the source</a></p></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();
|
||||
signup.init({ hub: hubpeople, hubJoin, shop, netVerified });
|
||||
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, signup });
|
||||
shop.setAttach(rec => { wire.attach(rec); store.bump('boosts', Number(rec.qty) || 1); });
|
||||
shop.setHook(proof.onPurchase);
|
||||
shop.setRewardHook(signup.onPaid);
|
||||
shop.init(C);
|
||||
setInterval(() => { if (store.prune()) wire.rebuild(); }, 3600000).unref();
|
||||
if (C.reward.payouts) setInterval(() => signup.payDue().catch(() => {}), 60000).unref();
|
||||
chatbot.init();
|
||||
lstrack.init(C, store);
|
||||
{ let busy = false; const tick = () => { if (busy) return; busy = true; lstrack.sweep(25).catch(() => {}).finally(() => { busy = false; }); };
|
||||
setTimeout(tick, Number(process.env.LS_SWEEP_FIRST_MS || 20000)).unref(); setInterval(tick, Number(process.env.LS_SWEEP_MS || 120000)).unref(); }
|
||||
server.listen(C.port, () => console.log('ViralAdSource on :' + C.port + (C.staging ? ' (staging)' : '') + ', rewards payouts ' + (C.reward.payouts ? 'ON' : 'OFF') + ', 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,216 @@
|
||||
// On-chain side (VASShop, ../contracts). Each job is inert until configured:
|
||||
// (a) orders: KEEPER_KEY (the keeper the contract trusts) signs EIP-712 Order(buyer, sku, qty, ref, line[], resharer, nonce, deadline).
|
||||
// line = the buyer's network sponsor line from the hub (wallets, nearest first, up to 20); resharer = the wallet of the member whose
|
||||
// reshare link the buyer came through (or zero). The contract pays the resharer's cut, the sponsor levels (pass-up over people
|
||||
// who never bought), the reward-pot slice and the company in the same transaction. A keeper signature is required for every buy.
|
||||
// (b) rewards: the keeper signs Reward(to, usdCents, unlockAt, nonce, deadline) for an L2 sign-up reward that passed every check.
|
||||
// The voucher is kept in the pending-rewards ledger. relayReward() sends claimReward() from RELAY_KEY's wallet (gas only) and is
|
||||
// called ONLY when REWARD_PAYOUTS=1 (OFF until Marty confirms the amounts). The contract enforces the per-reward cap, the
|
||||
// per-recipient daily cap, single-use nonces and that it never pays more than the pot holds.
|
||||
// (c) watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase and RewardPaid logs (confirmed blocks only) and records each once
|
||||
// per txHash:logIndex.
|
||||
// No key ever enters config or any API answer.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const { Wallet, Interface, getAddress, JsonRpcProvider } = 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, address resharer, uint256 resharerPaid, uint256 potAdded, 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)',
|
||||
'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)',
|
||||
'event RewardPaid(uint256 indexed nonce, address indexed to, uint256 usdCents, uint256 weiPaid, uint256 day)']);
|
||||
const TOPIC = IFACE.getEvent('Purchase').topicHash, RTOPIC = IFACE.getEvent('RewardPaid').topicHash;
|
||||
const T = { paid: IFACE.getEvent('Paid').topicHash, fail: IFACE.getEvent('PaymentFailed').topicHash, over: IFACE.getEvent('PassedOver').topicHash };
|
||||
const CALLS = new Interface(['function quoteWei(uint256 sku, uint256 qty) view returns (uint256)', 'function rewardWei(uint256 usdCents) view returns (uint256)',
|
||||
'function buy(uint256 sku, uint256 qty, uint256 ref, address[] line, address resharer, uint256 nonce, uint256 deadline, bytes sig) payable returns (uint256 orderId)',
|
||||
'function claimReward(address to, uint256 usdCents, uint256 unlockAt, uint256 nonce, uint256 deadline, bytes sig) returns (uint256 weiPaid)',
|
||||
'function boostsBought(address) view returns (uint256)', 'function potBalance() view returns (uint256)', 'function potFunded() view returns (uint256)', 'function potPaid() view returns (uint256)',
|
||||
'function rewardsToday(address) view returns (uint256)', 'function rewardNonceUsed(uint256) view returns (bool)', 'function resharerBps() view returns (uint256)', 'function potBps() view returns (uint256)',
|
||||
'function levelBps() view returns (uint16[])', 'function rewardMaxCents() view returns (uint256)', 'function rewardDailyCap() view returns (uint256)', 'function potDailyMaxWei() 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 skus(uint256) view returns (uint64 usdCents, uint64 views, bool active)']);
|
||||
const TYPES = {
|
||||
Order: [{ name: 'buyer', type: 'address' }, { name: 'sku', type: 'uint256' }, { name: 'qty', type: 'uint256' }, { name: 'ref', type: 'uint256' }, { name: 'line', type: 'address[]' },
|
||||
{ name: 'resharer', type: 'address' }, { name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint256' }],
|
||||
Reward: [{ name: 'to', type: 'address' }, { name: 'usdCents', type: 'uint256' }, { name: 'unlockAt', type: 'uint256' }, { name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint256' }]
|
||||
};
|
||||
const MAX_LINE = 20;
|
||||
const st = { polls: 0, recorded: 0, rewardsSeen: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null, relayed: 0, relayFailed: 0 };
|
||||
let C = null, keeper = null, relay = null, busy = false, timer = null;
|
||||
const hooks = { onPurchase: null, attach: null, onReward: null };
|
||||
function setHook(fn) { hooks.onPurchase = typeof fn === 'function' ? fn : null; }
|
||||
function setAttach(fn) { hooks.attach = typeof fn === 'function' ? fn : null; }
|
||||
function setRewardHook(fn) { hooks.onReward = 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); relay = keyOf(process.env.RELAY_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: 'VASShop', version: '1', chainId: C.chainId, verifyingContract: C.contractAddress });
|
||||
const nonce = () => BigInt('0x' + crypto.randomBytes(16).toString('hex')); // 128 random bits: single-use on chain either way
|
||||
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`: signed order with the sponsor line and the resharer (zero when none or when it would be the buyer)
|
||||
async function order(buyer, sku, qty, ref, line, resharer) {
|
||||
if (!signerOn()) throw new Error('orders off');
|
||||
const b = getAddress(String(buyer).toLowerCase());
|
||||
let r = ADDR_RE.test(resharer || '') ? String(resharer).toLowerCase() : ZERO; if (r === b.toLowerCase()) r = ZERO;
|
||||
const o = { buyer: b, sku: BigInt(sku), qty: BigInt(qty), ref: BigInt(ref || 0), line: cleanLine(b, line), resharer: getAddress(r), 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.resharer, 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, resharer: o.resharer === getAddress(ZERO) ? null : o.resharer.toLowerCase() };
|
||||
}
|
||||
// an L2 reward voucher (kept in the ledger; relayed only with payouts on)
|
||||
async function rewardVoucher(to, usdCents, unlockAt, days) {
|
||||
if (!signerOn()) return null;
|
||||
const v = { to: getAddress(String(to).toLowerCase()), usdCents: BigInt(usdCents), unlockAt: BigInt(Math.floor((unlockAt || 0) / 1000)), nonce: nonce(), deadline: BigInt(Math.floor(Date.now() / 1000) + (days || 30) * 86400) };
|
||||
const sig = await keeper.signTypedData(domain(), { Reward: TYPES.Reward }, v);
|
||||
return { to: v.to.toLowerCase(), usdCents: Number(v.usdCents), unlockAt: Number(v.unlockAt), nonce: v.nonce.toString(), deadline: Number(v.deadline), sig, contract: C.contractAddress, chainId: C.chainId };
|
||||
}
|
||||
// send claimReward() for a stored voucher from the relay wallet. ONLY called with payouts on. -> { tx } | { error }
|
||||
async function relayReward(v) {
|
||||
if (!C.reward.payouts) return { error: 'payouts off' };
|
||||
if (!relay || !watching()) return { error: 'relay not configured' };
|
||||
try {
|
||||
const w = relay.connect(new JsonRpcProvider(C.chainRpc, C.chainId, { staticNetwork: true }));
|
||||
const tx = await w.sendTransaction({ to: C.contractAddress, data: CALLS.encodeFunctionData('claimReward', [v.to, v.usdCents, v.unlockAt, BigInt(v.nonce), v.deadline, v.sig]) });
|
||||
st.relayed++; return { tx: tx.hash };
|
||||
} catch (e) { st.relayFailed++; const m = String((e && (e.shortMessage || e.reason || e.message)) || 'failed'); st.lastError = m.slice(0, 200); return { error: m.slice(0, 200) }; }
|
||||
}
|
||||
|
||||
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, resharer: ev.resharer, resharerPaid: ev.resharerPaid, potAdded: ev.potAdded, 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: Boost order', ev.orderId, 'x' + ev.qty, a, rec.adId ? 'for ad #' + rec.adId : '(no ad yet)', rec.resharer ? 'via resharer ' + rec.resharer : '');
|
||||
return true;
|
||||
}
|
||||
function decode(l) {
|
||||
if (!l || l.removed || String(l.address || '').toLowerCase() !== C.contractAddress.toLowerCase()) return null;
|
||||
const t0 = (l.topics || [])[0];
|
||||
if (t0 === TOPIC) {
|
||||
const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; const r = String(d.resharer).toLowerCase();
|
||||
return { kind: 'purchase', 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(), resharer: r === ZERO ? null : r,
|
||||
resharerPaid: d.resharerPaid.toString(), potAdded: d.potAdded.toString(), companyPaid: d.companyPaid.toString() };
|
||||
}
|
||||
if (t0 === RTOPIC) {
|
||||
const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args;
|
||||
return { kind: 'reward', txHash: l.transactionHash, logIndex: parseInt(l.logIndex, 16), block: parseInt(l.blockNumber, 16), nonce: d.nonce.toString(), to: String(d.to).toLowerCase(), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString() };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// the split of one order from its receipt: kind 0 company, 1..5 sponsor levels (with depth), 6 resharer; who was passed over
|
||||
async function readSplit(tx, orderId) {
|
||||
const r = await rpc('eth_getTransactionReceipt', [tx]); if (!r || !Array.isArray(r.logs)) return null;
|
||||
const pays = [], over = [];
|
||||
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 && t0 !== T.over) continue;
|
||||
const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; if (Number(d.orderId) !== Number(orderId)) continue;
|
||||
if (t0 === T.over) over.push({ who: d.who.toLowerCase(), depth: Number(d.depth) });
|
||||
else 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, over };
|
||||
}
|
||||
|
||||
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 = {}); sh.rewards = sh.rewards || {};
|
||||
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, RTOPIC]], fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }]);
|
||||
for (const l of logs || []) {
|
||||
const ev = decode(l); if (!ev) { st.ignored++; continue; }
|
||||
const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex;
|
||||
if (ev.kind === 'reward') { if (sh.rewards[key]) continue; sh.rewards[key] = { nonce: ev.nonce, to: ev.to, weiPaid: ev.weiPaid, at: Date.now() }; st.rewardsSeen++; if (hooks.onReward) { try { hooks.onReward(ev); } catch (e) {} } continue; }
|
||||
if ((S.purchases || {})[key]) { 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 reward rules from the contract (cached 5 minutes); null when the chain is not set or does not answer
|
||||
let rules = null;
|
||||
async function liveRules() {
|
||||
if (!watching()) return null;
|
||||
if (rules && Date.now() - rules.at < 300000) return rules.v;
|
||||
try {
|
||||
const [r, p, l, mx, cap, pot] = await Promise.all(['resharerBps', 'potBps', 'levelBps', 'rewardMaxCents', 'rewardDailyCap', 'potBalance'].map(f => call(f).then(x => x[0])));
|
||||
const v = { resharerBps: Number(r), potBps: Number(p), levelBps: l.map(Number), rewardMaxCents: Number(mx), rewardDailyCap: Number(cap), potWei: pot.toString() };
|
||||
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, relay: relay ? relay.address : null,
|
||||
payouts: !!(C && C.reward.payouts), lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, boosts: list.reduce((t, x) => t + (Number(x.qty) || 1), 0), orderCount: list.length }, st);
|
||||
}
|
||||
module.exports = { setHook, setAttach, setRewardHook, init, order, rewardVoucher, relayReward, signerOn, watching, apply, poll, view, quote, liveRules, receipt, fees, nudge, call, rpc, readSplit, TOPIC, RTOPIC, IFACE, TYPES, CALLS, MAX_LINE, ZERO };
|
||||
@@ -0,0 +1,206 @@
|
||||
// L2: a verified brand-new network member through a branch (Marty approved 2026-11-16). A visitor who arrived through a reshare link
|
||||
// (the vas.via tag) joins the network free on /join. Nothing is paid for the join itself; the reward is only for a sign-up that
|
||||
// passes EVERY real-time check:
|
||||
// share the link belongs to a resharer (step 1+), who is a verified network member with a wallet; the ad owner's own link
|
||||
// and visitors without a reshare tag never earn a reward (their sign-up still counts on the tree)
|
||||
// confirmed the email was confirmed through the link we sent (MAIL_URL unset = no mail is sent: staging; the admin sees the link)
|
||||
// throwaway the email domain is not a known disposable-mail domain and has a normal shape
|
||||
// hubNew the network hub has never seen this email (brand new to the WHOLE network). HUB_JOIN=1 writes the join to the hub
|
||||
// (join-all, sponsor = the resharer) and requires the hub's `created: true`; without it (staging) the check is a dry
|
||||
// read only: nobody is created anywhere
|
||||
// notSelf not the resharer's own device (rejected) or connection (held), from their seen device / IP keys here
|
||||
// dailyCap the resharer has fewer than REWARD_DAILY_CAP rewards today (Central time); the contract enforces its own cap too
|
||||
// fraud fraud score (0..100) below FRAUD_HOLD: form filled too fast, many sign-ups from one connection, plus-addressing,
|
||||
// digit-heavy names, a bot browser, a sign-up within seconds of the click, a resharer with a burst of sign-ups
|
||||
// Outcomes: passed -> a reward row in the pending-rewards ledger with a keeper-signed voucher (when KEEPER_KEY + CONTRACT_ADDRESS are
|
||||
// set) and status 'pending'. Payouts are OFF (REWARD_PAYOUTS=1 relays claimReward from RELAY_KEY's wallet; the contract pays from the
|
||||
// reward pot, never more than it holds). held -> waits for an admin look (score, cap, hub unreachable). rejected -> no reward ever.
|
||||
// Tiers (PROPOSAL, REWARD_TIERS): every Nth verified sign-up of one resharer adds a bigger bonus credited now, withdrawable after N days.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const store = require('./store');
|
||||
const cfgMod = require('./config');
|
||||
|
||||
const C = () => cfgMod.get();
|
||||
const DISPOSABLE = new Set(['mailinator.com', 'yopmail.com', 'guerrillamail.com', '10minutemail.com', 'tempmail.com', 'temp-mail.org', 'trashmail.com',
|
||||
'sharklasers.com', 'getnada.com', 'dispostable.com', 'maildrop.cc', 'throwawaymail.com', 'emailondeck.com', 'fakeinbox.com', 'mintemail.com',
|
||||
'mailnesia.com', 'tempr.email', 'discard.email', 'grr.la', 'guerrillamail.info', 'spam4.me', 'mohmal.com', 'tempmailo.com', 'burnermail.io',
|
||||
'mailpoof.com', 'moakt.com', 'tmail.ws', 'inboxkitten.com', 'emailfake.com', 'fakemail.net', 'yopmail.fr', 'cuvox.de', 'armyspy.com', 'dayrep.com',
|
||||
'einrot.com', 'mailsplat.xyz', 'inboxtogo.xyz', 'inboxburn.xyz', 'apxby.com', 'alvisani.com', 'ipniel.com', 'armablog.com', 'bnovel.com', 'fleckens.hu',
|
||||
'gustr.com', 'jourrapide.com', 'rhyta.com', 'superrito.com', 'teleworm.us', 'mvrht.net', 'byom.de', '33mail.com', 'guerrillamailblock.com', 'pokemail.net',
|
||||
'mail.tm', 'emailnax.com', 'tempinbox.com', 'mytemp.email', 'trashmail.de', 'getairmail.com', 'mailcatch.com', 'spambox.us', 'mailbox.in.ua', 'harakirimail.com']);
|
||||
const EMAIL_RE = /^[a-z0-9._%+-]{1,64}@[a-z0-9.-]{1,190}\.[a-z]{2,24}$/;
|
||||
const NAME_RE = /^[A-Za-z0-9_.-]{3,30}$/;
|
||||
const st = { joins: 0, confirmed: 0, passed: 0, held: 0, rejected: 0, mailed: 0, mailFailed: 0, hubJoined: 0, relayed: 0 };
|
||||
let D = null; // { hub: hubpeople, hubJoin(email, ref, username), shop, netVerified(m) }
|
||||
function init(deps) { D = deps; }
|
||||
|
||||
const lc = s => String(s || '').trim().toLowerCase();
|
||||
const sha = s => crypto.createHash('sha256').update(String(s)).digest('hex');
|
||||
const domainOf = e => lc(e).split('@')[1] || '';
|
||||
const throwaway = e => { const d = domainOf(e); if (!d) return true; if (DISPOSABLE.has(d)) return true; for (const x of DISPOSABLE) if (d.endsWith('.' + x)) return true; return false; };
|
||||
|
||||
// a join form submitted. j = { email, username, share (code) | null, vk, iph, ua, formMs, clickAt } -> { ok, signup } | { error }
|
||||
async function join(j) {
|
||||
const email = lc(j.email); if (!EMAIL_RE.test(email)) return { error: 'Enter a working email address.' };
|
||||
const username = String(j.username || '').trim(); if (username && !NAME_RE.test(username)) return { error: 'A username is 3 to 30 letters, numbers, dots, dashes or underscores.' };
|
||||
if (store.signups().some(x => x.emailHash === sha(email) && x.status !== 'unconfirmed')) return { error: 'That email has already joined here. Sign in with InstantAdPay or LinkSpin instead.' };
|
||||
const sh = j.share ? store.share(j.share) : null;
|
||||
const token = crypto.randomBytes(24).toString('hex');
|
||||
// one pending row per email: a second submit replaces the first (new confirm link)
|
||||
const prev = store.signups().find(x => x.emailHash === sha(email) && x.status === 'unconfirmed');
|
||||
const row = prev || store.addSignup({ emailHash: sha(email), status: 'unconfirmed' });
|
||||
Object.assign(row, { email, username: username || null, share: sh ? sh.id : null, adId: sh ? sh.adId : null, resharer: sh && sh.step > 0 ? sh.owner : null,
|
||||
vk: j.vk, iph: j.iph, ua: String(j.ua || '').slice(0, 200), formMs: Number(j.formMs) || null, clickAt: Number(j.clickAt) || null, tokenHash: sha(token), submittedAt: Date.now() });
|
||||
store.saveSignup(row); st.joins++; store.bump('joins');
|
||||
const link = 'https://' + C().site + '/confirm?t=' + token;
|
||||
const sent = await mail(email, link).catch(() => false);
|
||||
if (!sent) row.confirmLink = C().staging ? link : undefined; // staging only: the admin can open it (no mail is ever sent there)
|
||||
store.saveSignup(row);
|
||||
return { ok: true, signup: row, mailed: sent };
|
||||
}
|
||||
// MAIL_URL: a mail relay that takes { from, to, subject, text } (JSON POST). Unset = no mail (staging).
|
||||
async function mail(to, link) {
|
||||
if (!C().mail.url) return false;
|
||||
const text = 'Confirm your free network account by opening this link:\n\n' + link + '\n\nIf you did not ask to join, ignore this email.\n\nViralAdSource, TrustClickz, 615 Green Valley Drive, Moody, AL 35004';
|
||||
const r = await fetch(C().mail.url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Mail-Key': String(process.env.MAIL_KEY || '') },
|
||||
body: JSON.stringify({ from: C().mail.from, to, subject: 'Confirm your free account', text }), signal: AbortSignal.timeout(10000) }).catch(() => null);
|
||||
if (r && r.ok) { st.mailed++; return true; } st.mailFailed++; return false;
|
||||
}
|
||||
|
||||
// the confirm link opened -> runs the checks. -> { ok, signup } | { error }
|
||||
async function confirm(token) {
|
||||
const h = sha(String(token || '')); const x = store.signups().find(s => s.tokenHash === h);
|
||||
if (!x) return { error: 'That confirm link is not valid or has expired. Join again to get a new one.' };
|
||||
if (x.status !== 'unconfirmed') return { ok: true, signup: x, again: true };
|
||||
x.confirmedAt = Date.now(); x.status = 'confirmed'; delete x.confirmLink; store.saveSignup(x); st.confirmed++; store.bump('confirms');
|
||||
await check(x);
|
||||
return { ok: true, signup: x };
|
||||
}
|
||||
|
||||
function score(x, res) {
|
||||
let s = 0; const why = [];
|
||||
const add = (n, w) => { s += n; why.push(w + ' +' + n); };
|
||||
if (x.formMs != null && x.formMs < 4000) add(30, 'form filled in under 4 s');
|
||||
if (x.clickAt && x.submittedAt - x.clickAt < 8000) add(15, 'joined within 8 s of the click');
|
||||
const local = x.email.split('@')[0];
|
||||
if (local.includes('+')) add(15, 'plus-addressed email');
|
||||
if ((local.match(/\d/g) || []).length >= 5) add(10, 'many digits in the email');
|
||||
if (/bot|crawl|headless|python|curl|wget|phantom|selenium|puppeteer|playwright/i.test(x.ua || '') || !x.ua) add(40, 'bot-like browser');
|
||||
const day = Date.now() - 86400000;
|
||||
const sameIp = store.signups().filter(o => o.id !== x.id && o.iph === x.iph && (o.submittedAt || o.createdAt) > day).length;
|
||||
if (sameIp >= 1) add(Math.min(40, sameIp * 20), sameIp + ' other sign-up(s) from this connection today');
|
||||
if (x.resharer) {
|
||||
const burst = store.signups().filter(o => o.id !== x.id && o.resharer === x.resharer && o.confirmedAt && o.confirmedAt > Date.now() - 3600000).length;
|
||||
if (burst >= 5) add(20, 'resharer had ' + burst + ' sign-ups in the last hour');
|
||||
const rm = store.member(x.resharer); const rn = lc(rm && rm.username);
|
||||
if (rn && rn.length >= 4 && local.replace(/[^a-z0-9]/g, '').includes(rn.replace(/[^a-z0-9]/g, ''))) add(25, 'email looks like the resharer\'s own name');
|
||||
}
|
||||
res.fraud = { score: Math.min(100, s), why };
|
||||
return Math.min(100, s);
|
||||
}
|
||||
|
||||
// run (or re-run) every check on a confirmed sign-up
|
||||
async function check(x) {
|
||||
const R = C().reward; const res = { at: Date.now() }; const fail = [], hold = [];
|
||||
// throwaway
|
||||
res.throwaway = throwaway(x.email) ? 'fail' : 'pass'; if (res.throwaway === 'fail') fail.push('throwaway email');
|
||||
// hub: brand new to the whole network
|
||||
let hubNew = null;
|
||||
const known = await D.hub.resolve({ email: x.email });
|
||||
if (!known.ok) { res.hubNew = 'unreachable'; hold.push('network hub did not answer'); }
|
||||
else if (known.person) { res.hubNew = 'fail'; hubNew = false; fail.push('already in the network'); }
|
||||
else if (C().hubJoin) {
|
||||
const sh = x.share ? store.share(x.share) : null; const ref = sh ? (store.member(sh.owner) || {}).username : null;
|
||||
const j = await D.hubJoin(x.email, ref, x.username).catch(() => null);
|
||||
if (!j || !j.ok) { res.hubNew = 'unreachable'; hold.push('network hub join failed'); }
|
||||
else if (!j.created) { res.hubNew = 'fail'; hubNew = false; fail.push('already in the network'); }
|
||||
else { res.hubNew = 'pass'; hubNew = true; x.hubId = j.person && j.person.id; st.hubJoined++; }
|
||||
} else { res.hubNew = 'pass (dry: HUB_JOIN off, nothing written)'; hubNew = true; }
|
||||
if (hubNew) { const sh = x.share ? store.share(x.share) : null; if (sh && !x.counted) { sh.signups = (sh.signups || 0) + 1; store.saveShare(sh); x.counted = true; } }
|
||||
// who would be rewarded
|
||||
const sh = x.share ? store.share(x.share) : null; const rm = x.resharer ? store.member(x.resharer) : null;
|
||||
if (!sh) res.share = 'none (no reshare link: nothing to reward)';
|
||||
else if (sh.step === 0) res.share = 'own ad link (the owner is never rewarded for their own link)';
|
||||
else if (!rm || !D.netVerified(rm)) { res.share = 'fail'; fail.push('resharer is not a verified network member'); }
|
||||
else res.share = 'pass';
|
||||
// not the resharer themself
|
||||
if (rm) {
|
||||
const selfDev = (rm.vks || []).includes(x.vk), selfIp = (rm.iphs || []).includes(x.iph);
|
||||
// the same device is never a new person; the same connection can be a household or an office: held for a person to look at
|
||||
res.notSelf = selfDev ? 'fail (same device)' : selfIp ? 'hold (same connection)' : 'pass';
|
||||
if (selfDev) fail.push('the resharer\'s own device'); else if (selfIp) hold.push('the resharer\'s own connection');
|
||||
}
|
||||
// daily cap
|
||||
if (rm) {
|
||||
const today = store.ctDay(); const n = store.rewards().filter(r => r.to === rm.address && r.kind === 'signup' && store.ctDay(r.createdAt) === today && r.status !== 'void').length;
|
||||
res.dailyCap = n < R.dailyCap ? 'pass (' + n + ' of ' + R.dailyCap + ' today)' : 'over (' + n + ' of ' + R.dailyCap + ')';
|
||||
if (n >= R.dailyCap) hold.push('daily cap reached');
|
||||
}
|
||||
const sc = score(x, res); if (sc >= R.fraudHold) hold.push('fraud score ' + sc);
|
||||
x.checks = res; x.fail = fail; x.hold = hold;
|
||||
const eligible = sh && sh.step > 0 && rm && rm.address;
|
||||
if (fail.length) { x.status = 'rejected'; st.rejected++; }
|
||||
else if (!eligible) { x.status = 'verified'; } // a real new member, but no resharer to reward
|
||||
else if (hold.length) { x.status = 'held'; st.held++; }
|
||||
else { x.status = 'passed'; st.passed++; await rewardFor(x, rm); }
|
||||
store.saveSignup(x);
|
||||
return x;
|
||||
}
|
||||
// the pending-rewards ledger: the base reward, plus a tier bonus every Nth verified sign-up of this resharer
|
||||
async function rewardFor(x, rm) {
|
||||
const R = C().reward; const wallet = rm.address;
|
||||
const made = [];
|
||||
const base = store.addReward({ kind: 'signup', signup: x.id, to: wallet, toName: rm.username || null, cents: R.cents, unlockAt: 0, status: 'pending', share: x.share, adId: x.adId });
|
||||
made.push(base);
|
||||
const n = store.signups().filter(o => o.resharer === wallet && o.status === 'passed').length;
|
||||
for (const t of R.tiers) if (t && t.every > 0 && n % t.every === 0) made.push(store.addReward({ kind: 'tier', tier: t.every, signup: x.id, to: wallet, toName: rm.username || null, cents: Number(t.cents) || 0, unlockAt: Date.now() + (Number(t.lockDays) || 0) * 86400000, status: 'pending', share: x.share, adId: x.adId }));
|
||||
for (const r of made) {
|
||||
const v = await D.shop.rewardVoucher(r.to, r.cents, r.unlockAt, R.voucherDays).catch(() => null);
|
||||
if (v) { r.voucher = v; r.nonce = v.nonce; } else r.note = 'no voucher yet (contract or keeper not set)';
|
||||
store.saveReward(r); store.bump('rewardsPending'); store.bump('rewardCents', r.cents);
|
||||
}
|
||||
x.rewards = made.map(r => r.id);
|
||||
if (R.payouts) await payDue();
|
||||
return made;
|
||||
}
|
||||
// payouts ON only: relay every pending reward that is unlocked and has a voucher (oldest first)
|
||||
async function payDue() {
|
||||
if (!C().reward.payouts) return 0; let n = 0;
|
||||
for (const r of store.rewards().filter(r => r.status === 'pending' && r.voucher && (!r.unlockAt || r.unlockAt <= Date.now())).sort((a, b) => a.createdAt - b.createdAt)) {
|
||||
const out = await D.shop.relayReward(r.voucher);
|
||||
if (out.tx) { r.status = 'sent'; r.tx = out.tx; r.sentAt = Date.now(); n++; st.relayed++; } else { r.lastError = out.error; if (/Pot empty|Daily cap|Pot daily cap/.test(out.error || '')) break; }
|
||||
store.saveReward(r);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
// the watcher saw RewardPaid for a nonce
|
||||
function onPaid(ev) { const r = store.rewards().find(x => x.nonce === ev.nonce); if (r) { r.status = 'paid'; r.tx = ev.txHash; r.weiPaid = ev.weiPaid; r.paidAt = Date.now(); store.saveReward(r); } }
|
||||
// admin: release a held sign-up (re-run the checks ignoring the hold reasons) or reject it
|
||||
async function decide(id, action) {
|
||||
const x = store.signup(id); if (!x) return { error: 'not found' };
|
||||
if (action === 'reject') { x.status = 'rejected'; x.fail = (x.fail || []).concat(['rejected by admin']); store.saveSignup(x); return { ok: true, signup: x }; }
|
||||
if (action === 'recheck') { if (x.status === 'unconfirmed') return { error: 'not confirmed yet' }; await check(x); return { ok: true, signup: x }; }
|
||||
if (action === 'release') {
|
||||
if (x.status !== 'held') return { error: 'only a held sign-up can be released' };
|
||||
const rm = store.member(x.resharer); if (!rm) return { error: 'no resharer' };
|
||||
x.status = 'passed'; x.released = Date.now(); await rewardFor(x, rm); store.saveSignup(x); return { ok: true, signup: x };
|
||||
}
|
||||
return { error: 'action reject | recheck | release' };
|
||||
}
|
||||
// what a member sees about rewards earned through their reshares
|
||||
function mine(addr) {
|
||||
const a = lc(addr); const rows = store.rewards().filter(r => r.to === a).sort((x, y) => y.createdAt - x.createdAt);
|
||||
const sum = k => rows.filter(r => r.status === k).reduce((t, r) => t + r.cents, 0);
|
||||
return { payoutsOn: C().reward.payouts, pendingCents: sum('pending'), paidCents: sum('paid'), sentCents: sum('sent'),
|
||||
items: rows.slice(0, 50).map(r => ({ id: r.id, kind: r.kind, cents: r.cents, status: r.status, at: r.createdAt, unlockAt: r.unlockAt || null, tx: r.tx || null })),
|
||||
signups: { verified: store.signups().filter(s => s.resharer === a && ['passed', 'held', 'verified'].includes(s.status)).length, held: store.signups().filter(s => s.resharer === a && s.status === 'held').length } };
|
||||
}
|
||||
// the public side of the ledger: sign-up rewards with no personal data (the resharer's name, amount, status, tx)
|
||||
function publicRows(n) {
|
||||
return store.rewards().slice().sort((a, b) => b.createdAt - a.createdAt).slice(0, n || 50)
|
||||
.map(r => ({ kind: r.kind, at: r.createdAt, to: r.to, name: r.toName, cents: r.cents, status: r.status, unlockAt: r.unlockAt || null, tx: r.tx || null }));
|
||||
}
|
||||
function view() { return Object.assign({ payouts: C().reward.payouts, hubJoin: C().hubJoin, mail: !!C().mail.url, rules: { cents: C().reward.cents, dailyCap: C().reward.dailyCap, fraudHold: C().reward.fraudHold, tiers: C().reward.tiers },
|
||||
byStatus: store.signups().reduce((o, x) => (o[x.status] = (o[x.status] || 0) + 1, o), {}), rewards: store.rewards().reduce((o, r) => (o[r.status] = (o[r.status] || 0) + 1, o), {}) }, st); }
|
||||
module.exports = { init, join, confirm, check, decide, payDue, onPaid, mine, publicRows, view, throwaway, DISPOSABLE, _score: score };
|
||||
@@ -0,0 +1,156 @@
|
||||
// ViralAdSource data. One document (vas.json) holds members, sessions, Boost purchases (the chain's Purchase events), the watcher
|
||||
// position, ad credits, daily counters and the reward nonces. The growing collections are row tables when the app runs on MySQL
|
||||
// (docstore splits): text ads, reshares (the family tree), verified visits, verified clicks, sign-ups and the pending-rewards ledger.
|
||||
// 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 = 'vas.json';
|
||||
const SPLITS = [
|
||||
{ doc: DOC, field: 'ads', table: 'vas_ads', key: 'id', ts: 'createdAt' },
|
||||
{ doc: DOC, field: 'shares', table: 'vas_shares', key: 'id', ts: 'createdAt' },
|
||||
{ doc: DOC, field: 'visits', table: 'vas_visits', key: 'id', ts: 'at' },
|
||||
{ doc: DOC, field: 'clicks', table: 'vas_clicks', key: 'id', ts: 'at' },
|
||||
{ doc: DOC, field: 'signups', table: 'vas_signups', key: 'id', ts: 'createdAt' },
|
||||
{ doc: DOC, field: 'rewards', table: 'vas_rewards', key: 'id', ts: 'createdAt' }
|
||||
];
|
||||
const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s]));
|
||||
|
||||
let S = null, saveT = null, rowMode = false;
|
||||
const adById = new Map(), adByOwner = new Map(), shareById = new Map(), shareByKey = new Map(), sharesByAd = new Map(), signupById = new Map(), rewardById = new Map();
|
||||
const FILE = () => path.join(cfgMod.get().dataDir, DOC);
|
||||
|
||||
function index() {
|
||||
adById.clear(); adByOwner.clear(); shareById.clear(); shareByKey.clear(); sharesByAd.clear(); signupById.clear(); rewardById.clear();
|
||||
for (const a of S.ads) { adById.set(a.id, a); if (a.status !== 'removed') adByOwner.set(a.owner, a); }
|
||||
for (const s of S.shares) indexShare(s);
|
||||
for (const x of S.signups) signupById.set(x.id, x);
|
||||
for (const r of S.rewards) rewardById.set(r.id, r);
|
||||
}
|
||||
function indexShare(s) { shareById.set(s.id, s); shareByKey.set(s.adId + '|' + s.owner, s); let l = sharesByAd.get(s.adId); if (!l) sharesByAd.set(s.adId, l = []); if (!l.includes(s)) l.push(s); }
|
||||
function load() {
|
||||
try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; }
|
||||
S = Object.assign({ v: 1, seq: { ad: 0, visit: 0, click: 0, signup: 0, reward: 0 }, daily: {}, totals: { visits: 0, views: 0, vclicks: 0, clicks: 0, creditViews: 0 },
|
||||
members: {}, sessions: {}, purchases: {}, shop: {}, credits: {}, rewardDays: {}, ads: [], shares: [], visits: [], clicks: [], signups: [], rewards: [] }, 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()] || {}; }
|
||||
|
||||
// ---- text ads (one active ad per member) ----
|
||||
function ad(id) { return adById.get(Number(id)) || null; }
|
||||
function adOf(owner) { return adByOwner.get(String(owner || '').toLowerCase()) || null; }
|
||||
function addAd(a) { a.id = nextId('ad'); a.createdAt = Date.now(); a.updatedAt = a.createdAt; S.ads.push(a); adById.set(a.id, a); adByOwner.set(a.owner, a); putRow('ads', a); return a; }
|
||||
function saveAd(a) { a.updatedAt = Date.now(); if (a.status === 'removed') { if (adByOwner.get(a.owner) === a) adByOwner.delete(a.owner); } else adByOwner.set(a.owner, a); putRow('ads', a); }
|
||||
function ads() { return S.ads; }
|
||||
function liveAds() { return S.ads.filter(a => a.status === 'live'); }
|
||||
|
||||
// ---- reshares: one unique link per member per ad. code = the public id in /s/<code> ----
|
||||
const newCode = () => { let c; do { c = crypto.randomBytes(6).toString('base64').replace(/[^a-zA-Z0-9]/g, '').slice(0, 8).toLowerCase(); } while (c.length < 8 || shareById.has(c)); return c; };
|
||||
function share(code) { return shareById.get(String(code || '').toLowerCase()) || null; }
|
||||
function shareOf(adId, owner) { return shareByKey.get(Number(adId) + '|' + String(owner || '').toLowerCase()) || null; }
|
||||
function sharesOf(adId) { return sharesByAd.get(Number(adId)) || []; }
|
||||
function sharesBy(owner) { const o = String(owner || '').toLowerCase(); return S.shares.filter(s => s.owner === o); }
|
||||
function addShare(s) { s.id = newCode(); s.createdAt = Date.now(); Object.assign(s, { views: 0, clicks: 0, vclicks: 0, signups: 0, boosts: 0 }); S.shares.push(s); indexShare(s); putRow('shares', s); return s; }
|
||||
function saveShare(s) { putRow('shares', s); }
|
||||
|
||||
// ---- verified visits / clicks ----
|
||||
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; }
|
||||
const visits = () => S.visits, clicks = () => S.clicks;
|
||||
function prune() {
|
||||
const now = Date.now(); let n = 0;
|
||||
for (const [f, days] of [['visits', 15], ['clicks', 15]]) { const cut = now - days * 86400000; const old = S[f].filter(x => x.at < cut).map(x => x.id); dropRows(f, old); n += old.length; }
|
||||
// unconfirmed sign-ups older than 7 days carry nothing: dropped
|
||||
const cut = now - 7 * 86400000; const stale = S.signups.filter(x => x.status === 'unconfirmed' && x.createdAt < cut).map(x => x.id);
|
||||
if (stale.length) { stale.forEach(id => signupById.delete(id)); dropRows('signups', stale); n += stale.length; }
|
||||
return n;
|
||||
}
|
||||
|
||||
// ---- sign-ups (L2) and the pending-rewards ledger ----
|
||||
function addSignup(x) { x.id = 'u' + nextId('signup'); x.createdAt = Date.now(); S.signups.push(x); signupById.set(x.id, x); putRow('signups', x); return x; }
|
||||
function saveSignup(x) { putRow('signups', x); }
|
||||
function signup(id) { return signupById.get(String(id)) || null; }
|
||||
function signups() { return S.signups; }
|
||||
function addReward(r) { r.id = 'r' + nextId('reward'); r.createdAt = Date.now(); S.rewards.push(r); rewardById.set(r.id, r); putRow('rewards', r); return r; }
|
||||
function saveReward(r) { putRow('rewards', r); }
|
||||
function reward(id) { return rewardById.get(String(id)) || null; }
|
||||
function rewards() { return S.rewards; }
|
||||
|
||||
// ---- ad credits (L3): { earned, spent, views (verified branch views counted so far) } per member ----
|
||||
function credits(addr) { const a = String(addr || '').toLowerCase(); return S.credits[a] || (S.credits[a] = { earned: 0, spent: 0, views: 0 }); }
|
||||
const creditBalance = addr => { const c = S.credits[String(addr || '').toLowerCase()]; return c ? Math.max(0, c.earned - c.spent) : 0; };
|
||||
|
||||
// ---- members ----
|
||||
function member(addr) { return S.members[String(addr || '').toLowerCase()] || null; }
|
||||
function upsertMember(addr, patch) {
|
||||
const a = String(addr).toLowerCase();
|
||||
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 = String(name || '').toLowerCase(); if (!n) return null;
|
||||
for (const m of Object.values(S.members)) if (m.username && m.username.toLowerCase() === n) return m;
|
||||
return null;
|
||||
}
|
||||
function members() { return Object.values(S.members); }
|
||||
// the device / connection keys a member has been seen on (the L2 "not the resharer's own device or IP" check): last 50 of each
|
||||
function seenOn(addr, vk, iph) {
|
||||
const m = member(addr); if (!m) return;
|
||||
const add = (k, v) => { if (!v) return; const l = m[k] || (m[k] = []); const i = l.indexOf(v); if (i >= 0) l.splice(i, 1); l.push(v); if (l.length > 50) l.shift(); };
|
||||
add('vks', vk); add('iphs', iph); save();
|
||||
}
|
||||
|
||||
// ---- sessions ----
|
||||
const SESSION_TTL = 7 * 24 * 3600000;
|
||||
function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: address.toLowerCase(), 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, ad, adOf, addAd, saveAd, ads, liveAds,
|
||||
share, shareOf, sharesOf, sharesBy, addShare, saveShare, addVisit, addClick, visits, clicks, prune,
|
||||
addSignup, saveSignup, signup, signups, addReward, saveReward, reward, rewards, credits, creditBalance,
|
||||
member, upsertMember, memberByName, members, seenOn, mintSession, session, dropSession, endSessions, SESSION_TTL };
|
||||
@@ -0,0 +1,67 @@
|
||||
// Renders the site art with Playwright (local only), in the watershed look (approved mockup 2026-11-16): the icon, the OG share image,
|
||||
// the Telegram proof cards (public/art/proof/vas-proof-{river,ink}.png) and the promo kit (public/art/kit/vas-<angle>-<shape>.png,
|
||||
// 3 angles x 8 shapes, ad-blocker-neutral names). The hero (licensed kie art) and the topo pattern (licensed Envato) are embedded.
|
||||
// node tools/art.mjs (PLAYWRIGHT = path to the playwright package)
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const require = createRequire(import.meta.url);
|
||||
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||
const { chromium } = require(PW);
|
||||
const { SHAPES } = require(path.join(APP, 'promokit.js'));
|
||||
const ART = path.join(APP, 'public', 'art');
|
||||
fs.mkdirSync(path.join(ART, 'kit'), { recursive: true }); fs.mkdirSync(path.join(ART, 'proof'), { recursive: true });
|
||||
const b64 = f => fs.readFileSync(path.join(ART, f)).toString('base64');
|
||||
const HERO = 'data:image/jpeg;base64,' + b64('hero.jpg'), TOPO = 'data:image/png;base64,' + b64('topo.png');
|
||||
const FONTS = '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,800&family=IBM+Plex+Sans:wght@500;600&family=IBM+Plex+Mono:wght@500&display=swap">';
|
||||
const MARK = s => `<svg width="${s}" height="${s}" viewBox="0 0 34 34"><circle cx="17" cy="8" r="5" fill="#C4371B"/><path d="M17 13 V20 M17 20 L8 29 M17 20 L26 29 M17 20 V30" stroke="#0B2730" stroke-width="2.4" fill="none" stroke-linecap="round"/></svg>`;
|
||||
const MARKL = s => MARK(s).replace('#0B2730', '#EAF6F4');
|
||||
const CSS = `*{box-sizing:border-box;margin:0}html,body{width:100%;height:100%;overflow:hidden}
|
||||
body{font-family:'IBM Plex Sans',sans-serif;color:#0B2730;background:#EAF6F4}
|
||||
.h{font-family:'Bricolage Grotesque',sans-serif;font-weight:800;letter-spacing:-.02em;line-height:1.02}
|
||||
.m{font-family:'IBM Plex Mono',monospace;font-weight:500;letter-spacing:.12em;text-transform:uppercase}
|
||||
.wm{font-family:'Bricolage Grotesque',sans-serif;font-weight:800;white-space:nowrap}.wm b{color:#C4371B}
|
||||
.river{background:linear-gradient(90deg,#EAF6F4 0%,rgba(234,246,244,.92) 38%,rgba(234,246,244,0) 70%),url(${HERO}) right center/cover no-repeat}
|
||||
.ink{background:#0B2730 url(${TOPO}) repeat;background-size:600px;color:#EAF6F4}.ink .wm b{color:#FF9479}
|
||||
.btn{display:inline-block;background:#C4371B;color:#fff;border-radius:12px;font-weight:600;white-space:nowrap}`;
|
||||
const page = (w, h, body, cls) => `<!doctype html><html><head>${FONTS}<style>${CSS}</style></head><body class="${cls || ''}" style="width:${w}px;height:${h}px">${body}</body></html>`;
|
||||
|
||||
const ANG = {
|
||||
free: { k: 'Free text ad', t: 'Every ad has a source.', s: 'Post one free text ad and watch who passes it on.', cta: 'Post your ad free' },
|
||||
tree: { k: 'Family tree', t: 'Watch your ad travel.', s: 'Every reshare is a branch. See them all.', cta: 'See your tree' },
|
||||
boost: { k: 'One-time Boost', t: 'Boost the source.', s: 'Top of the reshare board. Never a subscription.', cta: 'Boost my ad' }
|
||||
};
|
||||
function kit(angle, shape) {
|
||||
const [w, h] = SHAPES[shape]; const a = ANG[angle]; const cls = angle === 'boost' ? 'ink' : 'river';
|
||||
const mk = cls === 'ink' ? MARKL : MARK;
|
||||
if (h <= 90) { // strips and leaderboards
|
||||
const fs = Math.round(h * 0.36);
|
||||
return page(w, h, `<div style="display:flex;align-items:center;gap:${Math.round(h * .18)}px;height:100%;padding:0 ${Math.round(h * .25)}px">${mk(Math.round(h * .55))}<div style="flex:1;min-width:0"><div class="h" style="font-size:${fs}px;white-space:nowrap;overflow:hidden">${a.t}</div>${w >= 700 ? `<div style="font-size:${Math.round(h * .2)}px;margin-top:3px">${a.s}</div>` : ''}</div><span class="btn" style="font-size:${Math.round(h * .22)}px;padding:${Math.round(h * .12)}px ${Math.round(h * .2)}px">${a.cta}</span></div>`, cls === 'ink' ? 'ink' : '');
|
||||
}
|
||||
if (w <= 160) { // tile + tower
|
||||
const tall = h > w * 2;
|
||||
return page(w, h, `<div style="display:flex;flex-direction:column;align-items:center;justify-content:${tall ? 'space-between' : 'center'};height:100%;padding:${tall ? 24 : 8}px 8px;text-align:center;gap:6px">${mk(tall ? 54 : 34)}<div class="h" style="font-size:${tall ? 30 : 15}px">${a.t}</div>${tall ? `<div style="font-size:16px">${a.s}</div>` : ''}<div class="wm" style="font-size:${tall ? 18 : 11}px">ViralAd<b>Source</b></div>${tall ? `<span class="btn" style="font-size:15px;padding:10px 12px">${a.cta}</span>` : ''}</div>`, cls === 'ink' ? 'ink' : '');
|
||||
}
|
||||
const big = Math.min(w, h); const pad = Math.round(big * .07);
|
||||
return page(w, h, `<div style="display:flex;flex-direction:column;justify-content:space-between;height:100%;padding:${pad}px;max-width:${w > h * 1.4 ? Math.round(w * .62) : w}px">
|
||||
<div class="wm" style="font-size:${Math.round(big * .065)}px;display:flex;align-items:center;gap:8px">${mk(Math.round(big * .09))}<span>ViralAd<b>Source</b></span></div>
|
||||
<div><div class="m" style="font-size:${Math.round(big * .04)}px;color:${cls === 'ink' ? '#FF9479' : '#0B5A57'};margin-bottom:${Math.round(big * .02)}px">${a.k}</div><div class="h" style="font-size:${Math.round(big * .13)}px">${a.t}</div><div style="font-size:${Math.round(big * .052)}px;margin-top:${Math.round(big * .03)}px">${a.s}</div></div>
|
||||
<div><span class="btn" style="font-size:${Math.round(big * .05)}px;padding:${Math.round(big * .028)}px ${Math.round(big * .05)}px">${a.cta}</span></div></div>`, cls);
|
||||
}
|
||||
const shots = [
|
||||
['icon-192.png', 192, 192, page(192, 192, `<div style="display:flex;align-items:center;justify-content:center;height:100%;background:#EAF6F4;border-radius:36px">${MARK(150)}</div>`)],
|
||||
['og-share.png', 1200, 630, kit('free', 'social')],
|
||||
['proof/vas-proof-river.png', 1200, 630, page(1200, 630, `<div style="display:flex;flex-direction:column;justify-content:space-between;height:100%;padding:60px;max-width:760px"><div class="wm" style="font-size:40px;display:flex;align-items:center;gap:10px">${MARK(54)}<span>ViralAd<b>Source</b></span></div><div><div class="m" style="font-size:22px;color:#0B5A57">Paid on chain</div><div class="h" style="font-size:84px">A Boost flowed back to the branch that sold it.</div></div><div style="font-size:24px">Resharer, sponsor line, reward pot: one transaction. Verify it on Polygonscan.</div></div>`, 'river')],
|
||||
['proof/vas-proof-ink.png', 1200, 630, page(1200, 630, `<div style="display:flex;flex-direction:column;justify-content:space-between;height:100%;padding:60px"><div class="wm" style="font-size:40px;display:flex;align-items:center;gap:10px">${MARKL(54)}<span>ViralAd<b>Source</b></span></div><div><div class="m" style="font-size:22px;color:#FF9479">Live ledger</div><div class="h" style="font-size:90px">Every ad has a source.<br>Every payment has a proof.</div></div><div style="font-size:24px;color:#B9DCD7">Results are rewarded, never a bare share.</div></div>`, 'ink')]
|
||||
];
|
||||
for (const angle of Object.keys(ANG)) for (const shape of Object.keys(SHAPES)) { const [w, h] = SHAPES[shape]; shots.push(['kit/vas-' + angle + '-' + shape + '.png', w, h, kit(angle, shape)]); }
|
||||
const browser = await chromium.launch();
|
||||
const pg = await browser.newPage();
|
||||
for (const [file, w, h, html] of shots) {
|
||||
await pg.setViewportSize({ width: w, height: h }); await pg.setContent(html, { waitUntil: 'networkidle' });
|
||||
await pg.screenshot({ path: path.join(ART, file), clip: { x: 0, y: 0, width: w, height: h } });
|
||||
}
|
||||
await browser.close();
|
||||
console.log('art written:', shots.length);
|
||||