10 Commits

Author SHA1 Message Date
martbost 027107b0fd Chatbot: the coming-soon tank batches entry needs its pattern (seeds() reads c.re.source; boot failed without it)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:07:07 -06:00
martbost ccfaacc935 Holding tank batches (Marty 2026-11-15), master switch tankBatches OFF
Active members with their own paid package ($20+ InstantAdPay, $25+ LinkSpin via the
refuel record) receive tank people in batches: Paid 10, Fueled 20 (counted refuel streak
or a $50+ package), Twin Engine 25 (both engines this cycle or the top package, the live
catalog's highest, $500 today), +5 per further consecutive refuel month up to 50. Every
2 days per sponsor, topped up to their size, dealt by rotation highest tier first from
tank.adoptable() (grace, rule 3, LinkSpin adoptions respected), never self, own upline,
adopted twice, flagged, spam, mistyped, erased or unsubscribed. Same tank.adopt path
(sponsor change, chat, "X is now your sponsor" email, switch-on reminders); one notice
per batch to the sponsor. Uncontacted after 7 days -> back to the tank as 'unreached'
(not counted). Tank feed: payments-topic card + live toast, sponsor/count/level only.
Member panel "How to get fed leads" (tankfeed.js). Every number is a site setting.

5xYourTeam draft gets its own cap (fiveXDraftCap, default 10): open draft picks only;
plain adoptions, the 24-hour safety net and batches each count their own people.
Admin: GET /api/admin/tank/batches/preview (read-only) + /api/admin/tank/batches.
Chatbot: coming soon only. qa/tank-batch.test.mjs (60 checks) in run.sh member.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:59:20 -06:00
martbost 1a13f53b9c Login ad on a clock + 5xYourTeam sign-in loop fix (Marty 2026-11-15)
Login ad: shown on the next member page load whenever the member's last finished view on this site is older than loginAdEveryHours (site setting, default 3), signed in just now or not. One row per member in MySQL (loginadclock.js, table login_ad_views; the same file in LinkSpin): /api/ads/slot?type=login answers notDue inside the window and marks the serve; POST /api/ads/login/seen at the end of the countdown restarts the clock only if the serve was at least dwell-2 s earlier (a reload during the countdown does not skip it). Framed gate, 10 s timer, click relay, frameable fallback, delivery and credit accounting unchanged. Welcome tour still outranks it. Member erase forgets the row. Admin site setting label added.

5xYourTeam loop: IAP answered /sso/check?r=fivex as if LinkSpin asked (fivex was missing from the wallets map), so tokens went to LinkSpin and Marty never got back. fivex added (FIVEX_URL, default https://5xyourteam.com); networksso.js now refuses an unknown r instead of answering as the peer. A pending network hop (nsso.back) is finished after sign-in: the login ad (if due) then /sso/resume; the gate's finish button says Continue and goes back to the site and page the member came from. /api/me carries nssoBack. The session pop-up (welcome.js) waits until the login gate is closed.

networksso.js: loop guard TRIED_AGE 30 min -> 120 s (it blocked Marty's silent sign-in on LinkSpin), NAMES gains fivex. The same file now ships byte-identical in IAP, LinkSpin, VBB, DLB, ViralAdBlitz, DownlineHydra, 5xYourTeam.

Tests: qa/networksso-partner.e2e.mjs (new, in run.sh member): a stand-in wallet partner on its own host; signed in on IAP -> straight back with a session, no dashboard, no ad; signed out -> sign in, login ad, Continue -> back on the partner page; the clock (due, too-soon refused, no re-show on reload or another tab, reload during the countdown brings it back); LinkSpin -> partner. networksso unit test: 2-minute guard, unknown site gets nothing. qa member: ALL PASSED (2 known admin warnings).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:45:12 -06:00
martbost ad533a0d56 Promo tools > Network sites: ViralAdBlitz, DownlineHydra, 5xYourTeam join Downline Banners and Viral Banner Blitz (Marty 2026-11-15), read live from each site's /api/promo-kit; CSP connect-src admits the three; netkits.js?v=20261115nk. qa member ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:09:29 -06:00
martbost 3a00ddf3dc Shared network knowledge (Marty 2026-11-15): the chatbot publishes its KB to the network hub and reads the other network sites' entries (netkb.js, the same file in every network site), home entries boosted, a named site's entries first and labelled with its LinkSpin tracked link, a question naming another site skips the instant answers (a hand-off still wins). Wallet answers follow Marty's rule (SafePal or any other crypto wallet, never recommend MetaMask), since they are now shared network-wide. /support prefills the subject when a network site's chat hands off (?from=&subject=), support.js v=20261115cb. KNOWLEDGE_DATE 2026-11-15. qa kb (incl. netkb-merge 98) + member pass
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:31:22 -06:00
martbost 6ef7a023df Member erase: their username leaves the messages that stay (another member's chat to them, a notice to their sponsor about them), whole words, 5+ characters; names option for a second pass after the account is gone; residue sweep also finds a long username inside text (REGEXP whole word)
Found on the LS-1021 erase: two kept messages still said "rajumiddha". qa/erase.mysql.test.cjs 3 pass (disposable mysql:8 on core), qa/erase.test.cjs 6 pass. NOT deployed (one InstantAdPay deploy today for this lane); ships with the next one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:43:14 -06:00
martbost 84d566e784 Member erase (Marty 2026-11-15, ticket LS-1021): POST /api/admin/erase {email, dryRun (default true), force} + the hub's member.erased event
erase.js runs inside the app so the documents modules keep in memory and the MySQL rows stay consistent. Refused unless
force: a main wallet, an on-chain member number, positions, a team here, ads still running or queued. SQL: the account,
sessions, signals, credits (unspent ad credits go away), credit log, views, visits, drips, nudges, digests, adoptions,
marks, promo redemptions, prospects, pipeline notes, their ads and every row hanging off them; messages they sent and
notices to them; a chat another member sent them stays for that member with a tombstone recipient; help-desk tickets
stay as history with the requester tombstoned and their own messages blanked; other members' mute lists. Documents:
every doc that mentions them is scrubbed by scrub.js (new, same file in LinkSpin) through the owning module's live copy
(lsinbound, lssync, sponsorfollow, refill, tank-ready, hubsync) or through docstore (legacy reloaded). A residue sweep
over every text column reports anything left. A 30-day email-hash tombstone (erase.json) stops lsinbound and the hub
path from bringing them back; the log keeps hashes and counts only. hubsync handles member.erased {emailHash}.
qa/erase.test.cjs 6 pass (JSON mode); qa/erase.mysql.test.cjs passes against a disposable mysql:8 on core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:29:31 -06:00
martbost b925661eac Network footer links: CODES adds viraladblitz nwvab, fivex nw5x and downlinehydra nwdh (Marty 2026-11-15), identical to LinkSpin's netsites.js. qa member ALL PASSED
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 10:17:31 -06:00
martbost dd50674d96 Merge dh-networksso (1c06c58 DownlineHydra network sign-in) for the 5x/DH IAP deploy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:05:54 -06:00
martbost ea07861b36 Footer network links carry a referral username (Marty 2026-11-15): the signed-in member's own (/api/me), else the sponsor the visitor came in on (iap.sponsor cookie, usernames only, never a member number or wallet). Tracked links get it as s1 (LinkSpin sends it on as ?ref=), plain links as ?ref=, none for Earners Corner. common.js + netline.js, same approach as VBB 6798503; ?v=20261115nr. iap-qa member: ALL PASSED. NOT deployed (5xYourTeam lane owns today's IAP deploy).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:05:30 -06:00
64 changed files with 1740 additions and 116 deletions
+1 -1
View File
@@ -110,7 +110,7 @@ function head(o) {
+ '</head><body><div class="wrap bl">';
}
function tail() {
return '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20261101th"></script></body></html>';
return '</div><script src="/assets/common.js?v=20261115nr"></script><script src="/assets/blog-page.js?v=20261101th"></script></body></html>';
}
const authorBox = () => '<div class="author"><img src="/logo-icon.png" alt="InstantAdPay"><div><b>' + AUTHOR + '</b><span>Founder of InstantAdPay and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.</span></div></div>';
const cardHtml = p => '<a class="post-card" href="/blog/' + esc(p.slug) + '">' + (p.cover ? '<img src="' + esc(p.cover) + '" alt="" loading="lazy" style="width:100%;border-radius:10px;margin:0 0 12px">' : '') + '<h2>' + esc(p.title) + '</h2><p>' + esc(p.excerpt) + '</p><p class="meta">' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '</p></a>';
+33 -10
View File
@@ -16,6 +16,7 @@ const https = require('https');
const http = require('http');
const kb = require('./kb');
const kbSeed = require('./kb-seed');
const netkb = require('./netkb'); // the shared network knowledge base on the hub (2026-11-15): publishes this site's entries, reads the other sites'
let DATA_DIR = null;
let chain = null;
@@ -26,7 +27,19 @@ const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro'
function init(opts) {
if (opts && typeof opts.gameLive === 'function') GAME_LIVE = opts.gameLive;
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn;
if (opts && typeof opts.bixLive === 'function') BIX_LIVE = opts.bixLive; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; HERO_SALE = typeof opts.heroSale === 'function' ? opts.heroSale : null; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
if (opts && typeof opts.bixLive === 'function') BIX_LIVE = opts.bixLive; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; HERO_SALE = typeof opts.heroSale === 'function' ? opts.heroSale : null; const ready = kb.init({ dataDir: DATA_DIR, seeds: seeds() });
netkb.init({ dataDir: DATA_DIR, site: process.env.HUB_SITE || 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com', entries: () => kb.own(), linkFor: netLink });
return ready; }
// the link to another network site: its LinkSpin tracked link with ?src=iap (netsites.js), else its plain address
function netLink(url) {
try { const ns = require('./netsites'); const h = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
const m = ns.list().concat(ns.FALLBACK || []).find(x => h(x.url) === h(url)); return (m && m.id !== 'iap' && ns.tracked(m.id, 'iap')) || url; } catch (e) { return url; }
}
// the other network sites for the system prompt (from the hub's merged set)
function networkBlock() {
const l = netkb.sites(); if (!l.length) return '';
return '\n- OTHER NETWORK SITES (one network account works across them): ' + l.map(x => x.name + ' ' + x.go).join('; ') + '. A question about one of them: answer from its KNOWLEDGE BASE entries below, say which site it is about, give its link exactly as shown, and never mix two sites\' prices, splits or rules. Wallets: say "SafePal or any other crypto wallet". Ad credits buy advertising, not income. Never mention RM Circle.';
}
function key() {
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
@@ -34,7 +47,7 @@ function key() {
function enabled() { return !!key(); }
// ---- canned answers: instant, free, always in voice ----
const KNOWLEDGE_DATE = '2026-11-14'; // bump whenever the canned answers / prompt are brought up to date
const KNOWLEDGE_DATE = '2026-11-15'; // bump whenever the canned answers / prompt are brought up to date
const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i;
const CANNED = [
// network sign-in (2026-11-12): signed in on one of InstantAdPay / LinkSpin = signed in on the other, no code (networksso.js)
@@ -207,6 +220,9 @@ const CANNED = [
{ id: 'tank-activate-link', title: 'Switch on payouts after you were picked up (one-tap link)', q: ['I got a Switch on payouts link from my new sponsor', 'How do I switch on payouts after I was adopted?'], tags: ['holding tank', 'switch on payouts', 'adopted', 'one tap', 'reminder'],
re: /((switch on|turn on|activate) payouts? (link|email|reminder)|activate=1|(picked (me )?up|adopted( me)?).*(switch on|activate)|one.?tap.*(payouts|activate)|reminder.*switch on payouts)/i,
a: 'When a member picks you up from the holding tank (or the site assigns you to one after 24 hours), the chat and the email you get both carry a Switch on payouts link: instantadpay.com/my?activate=1#wallet. Tap it, sign in if asked, and your wallet opens with your new sponsor already filled in. It is one free transaction, no package needed, and it locks that sponsor in as yours on the contract. No wallet linked yet? The same link asks you to link one first (one free signature) and then carries on. On a phone without a wallet browser, the wallet picker opens and hands you to your wallet app to confirm. Nobody, not even the site, can switch payouts on for you: it has to come from your own wallet. If you have not done it 24 hours after you were picked up you get one reminder email (and your sponsor gets a note to give you a nudge), and one last reminder at 72 hours. They stop as soon as your payouts are on or you buy a package.' },
{ id: 'tank-batches', title: 'Holding tank batches (coming soon)', q: ['Will the site send me people from the holding tank?', 'How do I get fed leads?', 'What are holding tank batches?'], tags: ['holding tank', 'batches', 'fed leads', 'auto-assign', 'coming soon'],
re: /(holding tank batch|fed leads|get (fed )?leads from the (holding )?tank|batch(es)? (of people )?from the (holding )?tank)/i,
a: 'Coming soon, not switched on yet: holding tank batches. The plan is that active members who bought their own package receive a batch of people from the holding tank every 2 days, people who joined without a sponsor and become your referrals to welcome and help. The planned ladder: your own $20 package on InstantAdPay or $25 on LinkSpin = 10 people at a time; a counted monthly refuel or a higher package ($50 or more) = 20; both engines refueled in the same cycle, or the top package = 25; then 5 more for every further refuel month in a row, up to 50. You would need to sign in at least once a week, and anyone you have not contacted within 7 days (a chat, or Contacted them on their row in My line) goes back to the tank for another member. These are leads you can sponsor, not income: what they do next depends on them and on your follow-up. Until it is switched on, adopt by hand from Members > My line > Holding tank as today, and the 24-hour safety net keeps running as it does now.' },
{ id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'unsponsored'],
re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/i,
a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come once they have been here 24 hours. A new sign-up shows an Opens in badge until then, with no Adopt button, so they have a day to tell us who invited them (the 24-hour safety net for wallet-linked members still runs on its own clock). To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold up to 10 people from the tank at one time (counting the ones who have not switched on payouts yet) and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances. Members who have linked a wallet show a Ready to activate badge with the hours left and sit at the top of the list: their payouts are on hold until someone adopts them, and after 24 hours the site assigns them to the next eligible adopter in turn (own $20 package, fewer than 10 people held from the tank who have not switched on payouts yet, signed in within the last 7 days). Adopters take turns, so the one assigned least recently goes first.' },
@@ -233,7 +249,7 @@ const CANNED = [
a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, an Objection handling bank with the truth plus a ready-to-send reply, and a Games tab with a kit for every network game plus the EnjoyBestGames arcade (enjoybestgames.com, hundreds of free games; only the featured Polygon games pay, and your ?r= link cookies visitors as your referral for 30 days). Everything is personalized with your invite link.' },
{ id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this transaction will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning', 'walletconnect'],
re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (MetaMask, Phantom, SafePal have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again. Phantom, SafePal and MetaMask do not have the hard block.' },
a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (SafePal and most other wallets have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again.' },
{ id: 'prohibited-content', title: 'What content is not allowed?', q: ['What content is not allowed?', 'Can I put a link in my bio?', 'Can I advertise a casino or CBD?'], tags: ['prohibited content', 'rules', 'bio links', 'gambling', 'adult', 'link farm'],
re: /(not allowed|prohibited|forbidden|banned (content|words|niches?)|content (rules|policy)|what (content|ads|niches?) (is|are) (not )?(allowed|ok|accepted)|can i (post|promote|advertise|run) .*(casino|gambling|betting|adult|porn|cbd|weed|pharma|guns?)|link ?farm|backlinks?|links? in (the |my |your )?bio|bio (link|url)|why was my (bio|profile|link) (refused|rejected|blocked))/i,
a: 'Not allowed anywhere on InstantAdPay (ads, campaigns, line banners, wall offers, bios and social links): gambling, casinos, betting, lotteries and sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing and counterfeit goods; misleading financial promises. The bio is text only: no links and no domain names, links go in the social fields in Profile. Your bio, avatar and social links show on your public wall once you have bought a package; free accounts show only their name and the line’s ads there. Accounts created just to place links in profile fields (link farming) are removed without notice, with their profile text. The full list is in the Terms, section 8: https://instantadpay.com/terms#prohibited' },
@@ -269,10 +285,10 @@ const CANNED = [
a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' },
{ id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Do you accept other coins?'], tags: ['pol', 'polygon', 'crypto', 'network'],
re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Any Polygon wallet works (MetaMask, SafePal, Phantom, Coinbase Wallet), and you can buy POL with a card from Buy packages if you have never held crypto.' },
a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Use SafePal or any other crypto wallet on Polygon, and you can buy POL with a card from Buy packages if you have never held crypto.' },
{ id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'metamask', 'safepal', 'phantom', 'moonpay', 'buy pol'],
re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i,
a: 'Preferred wallets: MetaMask (recommended, and the one for Qualified Start extra accounts), Phantom (turn Polygon on first: Settings, Active Networks), SafePal or Coinbase Wallet. Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' },
a: 'Use SafePal or any other crypto wallet on Polygon (in Phantom, turn Polygon on first: Settings, Active Networks). Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' },
{ id: 'safe', title: 'Is it safe? What if the company disappears?', q: ['Is this safe?', 'Can you run away with the money?', 'What if the company disappears?'], tags: ['safe', 'contract', 'trust', 'custody'],
re: /(safe|trust|rug|run away|company disappear)/i,
a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' }
@@ -372,15 +388,16 @@ ${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${w
- YOUR LINKS (top of Members > Promo tools): the plain invite link plus five angle links (?v=instant paid-in-seconds, ?v=adspend you-buy-ads-anyway, ?v=free costs-nothing-to-try, ?v=ledger no-back-office, ?v=two two-buyers-open-level-two, ?v=wide width-unlocks-depth with the Build Wide video; ?v=play opens the games angle), each with a who-it-is-for note, Copy and Share. Same credit either way; only the first page differs. Link stats on the Overview's coaching card show views/joins/buyers per angle.
- PROMO TOOLS (Members > Promo tools, pill menu): Social posts for X/Facebook/LinkedIn/Telegram-WhatsApp with post/share buttons; Text a friend (5 SMS-sized messages with Text it / WhatsApp / Telegram / Copy); Email swipes (short, standard, long, follow-up); Banners in every standard ad size plus 1080x1080, 1080x1920 and 1280x720 (download or copy URL); the member's Banner wall link; an Objection handling bank (truth + ready-to-send reply); a Videos tab with five hook videos, one per angle (Paid before the page reloads, You were buying traffic anyway, Watch first spend never, No back office, Two buyers open level two), each with a caption and the matched angle link, and at Circuit the Video Maker renders them with the member's own end card and QR; a Toolkit tab showing the badge ladder and the AI Copy Engine. Every piece carries the member's invite link; angle links add ?v=instant|adspend|free|ledger. Members who want copy in their own voice can use mybrandedvoice.com. The Games tab (2026-10-31) also carries the EnjoyBestGames arcade kit: enjoybestgames.com is an engagement site with hundreds of free HTML5 games; the featured row Games that pay Polygon is the network's own games and the only ones that pay; the member link enjoybestgames.com/?r=username sets a 30-day cookie so every featured game and the site strip credit that member on InstantAdPay; share image, 4 posts and the 11 banner sizes are in the kit. The Network sites tab (2026-11-14) shows the Downline Banners and Viral Banner Blitz promo kits, read live from each site: the member's links (their InstantAdPay username is their sponsor link there too, even if they never visited), creatives in 7 sizes per angle, 5 lines, 3 headlines, an email and 2 posts; the same kits are on downlinebanners.com/promote and viralbannerblitz.com/promote. Viral Banner Blitz: a shared loop of 125x125 banners, one free post credit a day for InstantAdPay/LinkSpin members, verified visitors move the loop, a banner that cycles earns network ad views (advertising, not cash), weekly leaderboards with a POL prize pot.
- INVITE PAGES: a member's link instantadpay.com/join/<username> opens a lead-capture page (email first, wallet later); add ?v=instant|adspend|free|ledger|two|wide|play for an angle-matched headline (?v=wide: 'Width unlocks depth.', opens on the Build Wide video, vertical on phones). New free members get a short getting-started email series over the first week (unsubscribe link in every email; the admin edits the sequence in /admin > Settings).
- WALLET DRAIN WARNING: Trust Wallet hard-blocks any purchase that spends most of the wallet's POL ("this transaction will drain your wallet", only "Stop and go back"). It is a balance-proportion heuristic, not a contract issue (there are no token approvals; a buy is one native-POL payable call). Advice: smaller package first, or add POL so the buy is well under half the balance, or use MetaMask/Phantom/SafePal (no hard block). The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again.
- WALLET DRAIN WARNING: Trust Wallet hard-blocks any purchase that spends most of the wallet's POL ("this transaction will drain your wallet", only "Stop and go back"). It is a balance-proportion heuristic, not a contract issue (there are no token approvals; a buy is one native-POL payable call). Advice: smaller package first, or add POL so the buy is well under half the balance, or use SafePal or another wallet without the hard block. The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again.
- WALL OWNERSHIP LADDER: the public wall has 3 positions. Position 1 = the member's line banner. Positions 2 and 3 show upline banners (then house ads) UNTIL the member earns them: 2 qualifying buyers ($20+) unlock position 2, 5 unlock position 3; a fully qualified member's wall is 100% their own links/offers (set in Profile > Your wall: label, https link, optional banner image). Empty unlocked slots fall back to upline banners, then house ads.
- LINE BANNER (free, set in Profile): every member can set a destination URL (must allow framing) plus an optional banner image. It is shown to their next THREE levels of new members during welcome tours (position 1 for directs, 2, 3 below), and on their public BANNER WALL at /wall/<username> — a shareable page showing their line ladder with their join link. Free viral traffic that compounds as the team grows; no credits spent.
- Ad packages: Micro $5/500 credits, Starter $10/1,000, Activation $20/2,000, Builder $50/5,500, Growth $100/12,000, Leader $250/32,500, Elite $500/70,000. Dollar-priced, settled in POL (Polygon) at the live Chainlink rate. 1 credit = 1 cent of ad delivery.
- Live formats: display banners (per impression), text ads (per impression), full-screen LOGIN ADS (per day: right after a member signs in they land on a sponsor interstitial — they click "Open Ad", the advertiser's page opens in a NEW tab, a countdown runs on the interstitial, and at zero a "Go to dashboard" button appears. Just a CTA link is enough; an optional banner image can be the clickable creative. No framing requirement since it opens in its own tab), WATCH-TO-EARN VIDEO ADS (advertiser uploads an MP4/WebM or gives a direct https .mp4/.webm link and picks a required watch length — 10s/30s/60s — which sets the per-view price; viewers watch in an escape-proof player under Earn credits > Watch videos, the watch time is enforced on the server clock, and they earn credits per completed watch; you never see your own videos), and solo ads. Banner ads also require a size (standard IAB sizes like 728x90, 300x250). Video watching is capped at 8 a day per member and pays 1, 2 or 4 credits for a 10, 30 or 60 second watch. FEATURED LINKS (live): a headline + link in the Featured strip at the top of every member's Overview, booked for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead, at most 10 links sharing any day; flat buy paid when booked; the row shows days left and 'runs through <date>', counts views (one per viewer per hour) and clicks, and offers Extend run. VERIFIED-VISIT PACKS (live): 3 credits per visit, minimum 20 visits, paid up front; each visit is a distinct member who opens the site in a new tab, stays 8 seconds and passes a check, at most 20 visits per member per day; the row shows 'N of M visits delivered' and Buy more visits adds to the pack; the visitor earns 1 credit.
- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): preferred MetaMask (recommended; extra accounts for Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase.
- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): say "SafePal or any other crypto wallet" and never recommend MetaMask by name (Marty 2026-11-13; a wallet app with several accounts serves Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase.
- PROHIBITED CONTENT (2026-10-30, Terms section 8, /terms#prohibited): gambling, casinos, betting, lotteries, sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing, counterfeit goods; misleading financial promises. Refused at save time in bios, social links, line banners, wall offers and every campaign field. A bio may not contain a URL or a domain (links go in the social fields). Profile text, avatar and social links appear on the public wall ONLY for members who have bought a package; a free account's wall shows the name, the line's ads and the join button. Link-farm accounts (created to plant links in profile fields) are removed without notice with their profile text.
- INTRO VIDEO ON THE WALL: Profile > social links has an "Intro video" field (YouTube, Vimeo or direct .mp4 link). It embeds on the member's public wall page (/wall/<username>) right under their bio, above the three-level line and the join button.
- BTC4HITS (2026-11-11): members of the closed BTC4Hits rotator site with a deliverable email were imported as waiting accounts (no wallet, no password, nothing mailed), with their BTC4Hits sponsor when that sponsor was also imported or already a member; the rest join the holding tank when they first sign in. They sign in here with the same email (code sign-in), or on LinkSpin at linkspin.app/from/btc4hits, where their active rotators became spin links. Pro status and old BTC4Hits commissions do not carry over.
- HOLDING TANK BATCHES (COMING SOON, NOT LIVE, approved in principle 2026-11-15; Marty switches it on after reviewing a preview): active members (signed in within 7 days) who bought their own $20+ package on InstantAdPay or $25+ on LinkSpin would receive a batch from the holding tank every 2 days: 10 at a time; 20 with a counted refuel streak or a higher package ($50+); 25 with both engines refueled this cycle or the top package; +5 per further consecutive refuel month, up to 50. People not contacted within 7 days go back to the tank. It is separate from the 5xYourTeam draft (its own cap) and from the hand adoptions (still max 10 held). NEVER say it is live; say it is coming soon. Leads to sponsor, never income.
- HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; new sign-ups cannot be adopted by hand for 24 hours from sign-up (they show an Opens in badge and no Adopt button); a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 10 held at one time, counting those not yet switched on payouts, 7-day window; if the person never links a wallet or buys, they fall back into the tank; a person can be adopted twice at most). Adopting sets the sponsor, opens a chat and emails the member; their first purchase then binds to the adopter on-chain. Members can also "Release to tank" one of their own free referrals (pay it forward), but NOT someone they adopted less than 3 days ago: an adoption is a commitment, and a dropped adoption still counts toward that person's two-adoption lifetime limit. Releases are posted to the feed and Telegram like pickups. Admin sees the tank under Members.
- WHO INVITED YOU (2026-11-07, Marty approved): a member with no sponsor and no member number sees a Who invited you? card on their Overview. They type a username, confirm in an in-page box, and that member becomes their sponsor (it follows to LinkSpin, lifts the activation hold, and the sponsor gets a new-referral email and notice). Refused: themselves, a username that does not exist, someone in their own line, a member who cannot take new members, a member with no payouts on and nobody above them on the contract, and anyone who already has a sponsor or a member number. Nobody invited me hides the card (a small Overview link brings it back while they are in the tank) and changes nothing else. It never blocks the site. It is not an adoption: no 7-day window and it does not count toward the two.
- SIGN-UP GRACE (2026-11-07): for 24 hours from sign-up nobody can adopt a member by hand. The 24-hour auto-assign is unchanged and runs from the wallet link, so a member who links a wallet in their first hour is matched about 24 hours after linking, with at most a short hand-adoption window first. Members back in the tank later have no grace.
@@ -453,12 +470,12 @@ ${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${w
PAGES (the ONLY addresses that exist; never invent others): home https://instantadpay.com, member dashboard https://instantadpay.com/my with tabs as hashes: /my#overview, /my#line (My line, holding tank, prospects), /my#pipeline, /my#buy (Buy packages, Qualified Start, Buy POL with a card), /my#campaigns (New campaign, campaign rows, Credit activity), /my#earn (Watch ads, Watch videos, Verified visits, Inbox), /my#earnings (Trace a payment, payouts, referrals, purchases), /my#promo (Your links, Social posts, Text a friend, Email swipes, Banners, Wall, Objections, Videos, Toolkit), /my#training, /my#games (PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Spooky Doors in season), /games (public list of every game), /my#wallet, /my#profile, /my#help (Help: support tickets). Public: /support (contact form for anyone signed out or locked out; support@instantadpay.com also works), /join/<username> (invite page, ?v=angle), /wall/<username>, /b/<username>/<badge>, /handout/<username>, /ledger, /tx/<hash>, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix.
RULES:
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page, and only URLs from the PAGES list above.
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page, and only URLs from the PAGES list above or a network site's link from the KNOWLEDGE BASE.
- Never send someone to a warning, notice, guide, document or page section that is not named above. Saying "read the full warning on your training page" invents something that does not exist and the member will go looking for it. If the answer is not on a page in the PAGES list, give the answer here or say you are not sure and point to /contract, the ledger, or their sponsor.
- Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes.
- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen.
- No em dashes. If you do not know, say so and point to /contract or the ledger.
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : '');
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.${networkBlock()}` + (kbBlock ? '\n\n' + kbBlock : '');
}
// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai
@@ -512,7 +529,13 @@ async function answerRaw(message, historyText) {
if (!msg) return { error: 'Say something first.' };
// fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down
let hit = null, kbOk = true;
try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); }
try {
await kb.load();
// another network site named (and this one not): this site's instant answers stand aside, except a hand-off (2026-11-15)
const other = /instant ?ad ?pay|\biap\b/i.test(msg) ? [] : kb.namesOther(msg, process.env.HUB_SITE || 'iap');
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 && hit.id === 'refuel' && !REFUEL_ON()) return { reply: REFUEL_OFF_ANSWER, canned: true, kb: hit.id };
if (hit && (hit.id === 'polminer' || hit.id === 'c-polminer') && !pmLive()) return { reply: POLMINER_SOON_ANSWER, canned: true, kb: hit.id };
if (hit && (hit.id === 'turkeydrop' || hit.id === 'c-turkeydrop') && !tdLive()) return { reply: tdAnswer(), canned: true, kb: hit.id };
+2 -1
View File
@@ -188,4 +188,5 @@ async function claim(key) {
// 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 };
const names = () => [...cache.keys()]; // every document name (the member erase walks them all, 2026-11-15)
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim, names };
+5 -2
View File
@@ -19,7 +19,7 @@
// and someone on this contract in their line (tank.partnerEligibility); free members cannot adopt
// - the pool = tank.waiting() (rule 3 already applied: nobody the hub reports locked on any contract or sponsored, nobody adopted
// on LinkSpin) minus spam / suspended / flagged, throwaway or mistyped email domains, and anyone adopted twice already
// - max 10 open picks a coach (and the tank's people-held-at-once cap); max 2 adoptions per person (every pick counts, both sites)
// - max 10 open picks a coach (site setting fiveXDraftCap, its own cap since 2026-11-15, not the tank's); max 2 adoptions per person (every pick counts, both sites)
// - a pick that has not STARTED (payouts on or a first purchase) in 3 days goes back to the pool; a coach cannot release one in its
// first 48 hours; a person who has had their 2 adoptions stays with the coach (the tank sweep rule); started picks stay
// - never anyone locked on a network contract: asked fresh at adopt and at every return; a hub that does not answer refuses / waits
@@ -109,7 +109,10 @@ async function ensureTables() {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // every partner call, with its reason
}
async function init(opts) { R = opts; if (R.tank && R.tank.GRACE_MS) RULES.graceMs = R.tank.GRACE_MS; await ensureTables(); }
// the draft's own cap (Marty 2026-11-15: "5x your team's draft is a different thing altogether"): site setting fiveXDraftCap (default 10),
// counted over open draft picks only; the member's own tank adoptions and holding tank batches never share it (tank.partnerEligibility)
const capOf = () => { const n = Math.round(Number(R && R.maxOpen ? R.maxOpen() : 10)); return n >= 1 && n <= 100 ? n : 10; };
async function init(opts) { R = opts; if (R.tank && R.tank.GRACE_MS) RULES.graceMs = R.tank.GRACE_MS; Object.defineProperty(RULES, 'maxOpen', { get: capOf, enumerable: true, configurable: true }); await ensureTables(); }
// ---- signature ----
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('draft.v1.' + ts + '\n' + raw).digest('hex'); }
+199
View File
@@ -0,0 +1,199 @@
// Member erase (Marty 2026-11-15, ticket LS-1021: "I want delete my account data from all your sites"). One named admin action
// that takes a person out of InstantAdPay from INSIDE the running app, so the documents the modules keep in memory and the MySQL
// rows stay consistent (an edit straight in the database would be written back over by the next save).
// POST /api/admin/erase {email, dryRun (default true), force} (admin) and the hub's member.erased event (hubsync.js)
// Refused unless force: a linked main wallet, an on-chain member number, linked positions, anyone sponsored under them here,
// an ad still running or queued (stop it first: skill iap-kill-ad). What goes:
// - the account, sessions, signals, credits (unspent ad credits simply go away), credit log, views, visits, drips, nudges,
// digests, adoptions (as adoptee or adopter), marks, promo redemptions, prospects and pipeline notes, their ads with every
// row that hangs off them (hours, countries, clicks, inbox deliveries, visits, reports);
// - messages: everything they sent; notices and broadcasts to them; a CHAT message another member sent them stays for that
// member, its recipient replaced by a tombstone address;
// - help desk tickets stay as closed history: requester replaced by the tombstone, their own messages blanked;
// - every data document (docs table) that mentions them: their keys, list items and records (scrub.js), through the owning
// module's live state when a module keeps one in memory, else read and written through docstore.
// A tombstone (SHA-256 of the email, kept 30 days in erase.json) stops the LinkSpin and hub syncs from bringing them back while
// the other sites catch up. The log keeps hashes and counts, never the email. Dry run = the same counts, nothing changed.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const db = require('./db');
const { scrubDeep, scrubText, mentions } = require('./scrub');
let R = null; // { dataDir, accounts, docstore, owners: {doc: {state, save}}, reload: {doc: fn}, forget: [fn(email)] }
const TOMB_MS = 30 * 86400000;
const REMOVED = '[removed: this member asked for their data to be erased]';
const norm = v => String(v || '').trim().toLowerCase();
const hashOf = email => crypto.createHash('sha256').update(norm(email)).digest('hex');
const tombAddr = hash => 'erased-' + hash.slice(0, 12) + '@erased.invalid';
const FILE = () => path.join(R.dataDir, 'erase.json');
let st = null;
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.v = 1; st.tomb = st.tomb || {}; st.log = st.log || [];
return st;
}
function save() { try { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('erase save', e.message); } }
function init(deps) { R = deps; st = null; load(); }
function isErased(email) {
const s = load(); const h = hashOf(email); const t = s.tomb[h];
if (!t) return false;
if (Date.now() - t > TOMB_MS) { delete s.tomb[h]; save(); return false; }
return true;
}
const like = t => '%' + String(t).replace(/[\\%_]/g, m => '\\' + m) + '%';
async function tables() { return new Set((await db.q('SELECT table_name t FROM information_schema.tables WHERE table_schema = DATABASE()')).map(r => r.t || r.TABLE_NAME)); }
// the SQL work, in order: deletes and the two updates that keep other members' side of a conversation / the desk history
function steps(E, h, campIds, ticketIds, memberMsgIds) {
const S = []; const tomb = tombAddr(h);
const del = (t, where, args) => S.push({ t, where, args, op: 'delete' });
const upd = (t, set, setArgs, where, args) => S.push({ t, where, args, op: 'update', set, setArgs });
del('accounts', 'email=?', [E]); del('sessions', 'email=?', [E]); // first: nothing can sign in or be synced as them while the rest runs
if (campIds.length) for (const t of ['camp_hours', 'camp_geo', 'click_sources', 'solo_inbox', 'visit_seen', 'visit_repeat', 'video_seen', 'ad_reports', 'ad_clicks']) del(t, 'campaign_id IN (?)', [campIds]);
del('campaigns', 'owner_email=?', [E]); del('ad_clicks', 'owner_email=?', [E]);
for (const t of ['account_signals', 'daily_views', 'digests', 'drips', 'earned_credits', 'nudges', 'solo_inbox', 'visit_seen', 'visit_repeat', 'video_seen', 'credit_log', 'promo_redemptions', 'positions']) del(t, 'email=?', [E]);
del('prospects', 'owner_email=?', [E]); del('pipeline_notes', 'owner_email=? OR person=?', [E, E]); del('lead_marks', '`lead`=? OR sponsor=?', [E, E]);
upd('ad_reports', "reporter=''", [], 'reporter=?', [E]); upd('promo_codes', 'funder=NULL', [], 'funder=?', [E]);
del('adoptions', 'adoptee=? OR adopter=?', [E, E]); del('tank_batch_picks', 'adoptee=? OR sponsor=?', [E, E]); // holding tank batches (2026-11-15)
del('event_marks', 'k LIKE ?', [like(E)]); del('doc_claims', 'k LIKE ?', [like(E)]);
del('sponsor_messages', 'from_email=?', [E]);
upd('sponsor_messages', 'to_email=?', [tomb], "to_email=? AND kind='chat'", [E]); // the other member's own words stay theirs
del('sponsor_messages', "to_email=? AND kind<>'chat'", [E]); // notices, alerts, broadcasts: copies made for them alone
if (memberMsgIds.length) del('ticket_translations', 'message_id IN (?)', [memberMsgIds]);
if (ticketIds.length) upd('ticket_messages', 'body=?, attachments=NULL, email_message_id=NULL', [REMOVED], "ticket_id IN (?) AND author='member'", [ticketIds]);
upd('tickets', 'email=?, name=NULL, username=NULL', [tomb], 'email=?', [E]);
return S;
}
// what still mentions them anywhere in the database (every text column of every table but docs); [] = clean
async function residue(E, exact) {
if (!db.enabled()) return [];
const cols = await db.q("SELECT table_name t, column_name c FROM information_schema.columns WHERE table_schema = DATABASE() AND data_type IN ('char','varchar','text','mediumtext','longtext','json') AND table_name NOT IN ('docs','docs_writer')");
const out = [];
for (const r of cols) {
const t = r.t || r.TABLE_NAME, c = r.c || r.COLUMN_NAME; const ex = exact.filter(Boolean); const words = ex.filter(x => x.length >= 5); // a long username inside text too
const where = '`' + c + '` LIKE ?' + ex.map(() => ' OR `' + c + '` = ?').join('') + words.map(() => ' OR `' + c + '` REGEXP ?').join('');
const wordRe = w => '(^|[^a-z0-9_])' + w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([^a-z0-9_]|$)'; // the whole word, not a longer name
try { const [x] = await db.q('SELECT COUNT(*) n FROM `' + t + '` WHERE ' + where, [like(E)].concat(ex, words.map(wordRe))); if (Number(x.n)) out.push({ table: t, column: c, n: Number(x.n) }); } catch (e) {}
}
return out;
}
function docNames() {
if (R.docstore && R.docstore.isOn && R.docstore.isOn()) return R.docstore.names();
const out = []; const walk = (d, pre) => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) {} for (const x of ents) { const p = path.join(d, x.name); if (x.isDirectory()) walk(p, pre + x.name + '/'); else if (/\.jsonl?$/i.test(x.name)) out.push(pre + x.name); } };
walk(R.dataDir, ''); return out;
}
// every data document that mentions them: counted (dry run) or scrubbed, through the module that holds it in memory if any
function docs(needles, dryRun) {
const out = {};
for (const name of docNames()) {
if (name === 'erase.json') continue; // hashes only
const file = path.join(R.dataDir, name); let body;
try { body = fs.readFileSync(file, 'utf8'); } catch (e) { continue; }
if (!mentions(body, needles)) continue;
const own = R.owners[name];
try {
if (own) {
const live = own.state(); const n = scrubDeep(dryRun ? JSON.parse(JSON.stringify(live)) : live, needles);
if (!dryRun && n) own.save(); out[name] = n;
} else {
const r = scrubText(body, needles, /\.jsonl$/i.test(name));
if (!dryRun && r.removed) { fs.writeFileSync(file, r.body); if (R.reload && R.reload[name]) R.reload[name](); }
out[name] = r.removed;
}
} catch (e) { out[name] = 'error: ' + String(e.message).slice(0, 80); }
}
return out;
}
function docResidue(needles) { return docNames().filter(n => n !== 'erase.json').filter(n => { try { return mentions(fs.readFileSync(path.join(R.dataDir, n), 'utf8'), needles); } catch (e) { return false; } }); }
async function blockersOf(acct, E) {
const out = [];
if (acct.address) out.push('main wallet linked');
if (Number(acct.memberId) > 0) out.push('on-chain member #' + acct.memberId);
try { const pos = await R.accounts.positions(E); if (pos && pos.length) out.push('linked positions: ' + pos.length); } catch (e) {}
const refs = [acct.username, acct.code].filter(Boolean).map(norm);
if (refs.length) { const team = (await R.accounts.listByReferrer(refs)).filter(a => norm(a.email) !== E); if (team.length) out.push('sponsored under them here: ' + team.length); }
if (db.enabled()) { const [r] = await db.q("SELECT COUNT(*) n FROM campaigns WHERE owner_email=? AND status IN ('active','queued','paused')", [E]); if (Number(r.n)) out.push('ads still running or queued: ' + r.n + ' (stop them first, skill iap-kill-ad)'); }
return out;
}
// email -> {ok, dryRun, emailHash, found, blockers, sql: {table: rows}, docs: {doc: removed}, residue, docResidue}
async function erase(email, opts) {
const o = Object.assign({ dryRun: true, force: false, by: 'admin', sweep: true }, opts || {});
const E = norm(email); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)) return { error: 'A valid email is required.' };
const h = hashOf(E); const acct = await R.accounts.byEmail(E);
// names: usernames of an account already erased (a second pass after the code learned something new), e.g. ['oldname']
const names = (Array.isArray(o.names) ? o.names : []).map(norm).filter(x => /^[a-z0-9_.-]{5,30}$/.test(x));
const exact = (acct ? [acct.username, acct.code].filter(Boolean).map(norm) : []).concat(names);
const needles = { emails: [E], exact };
const blockers = acct ? await blockersOf(acct, E) : [];
const res = { dryRun: !!o.dryRun, emailHash: h, found: !!acct, blockers, forced: !!o.force && blockers.length > 0, sql: {}, docs: {} };
if (blockers.length && !o.force && !o.dryRun) return Object.assign(res, { error: 'Not erased: ' + blockers.join('; ') + '. Send force: true to erase anyway.' });
let campIds = [], ticketIds = [], memberMsgIds = [], have = new Set();
if (db.enabled()) {
have = await tables();
campIds = (await db.q('SELECT id FROM campaigns WHERE owner_email=?', [E])).map(r => r.id);
ticketIds = have.has('tickets') ? (await db.q('SELECT id FROM tickets WHERE email=?', [E])).map(r => r.id) : [];
memberMsgIds = ticketIds.length ? (await db.q("SELECT id FROM ticket_messages WHERE ticket_id IN (?) AND author='member'", [ticketIds])).map(r => r.id) : [];
}
if (!o.dryRun) { load().tomb[h] = Date.now(); save(); } // before anything goes: the syncs refuse them from here on
if (db.enabled()) {
for (const s of steps(E, h, campIds, ticketIds, memberMsgIds)) {
if (!have.has(s.t)) continue;
const key = s.t + (s.op === 'update' ? ' (kept, scrubbed)' : '');
if (o.dryRun) { const [r] = await db.q('SELECT COUNT(*) n FROM `' + s.t + '` WHERE ' + s.where, s.args); res.sql[key] = (res.sql[key] || 0) + Number(r.n); continue; }
const r = s.op === 'delete' ? await db.q('DELETE FROM `' + s.t + '` WHERE ' + s.where, s.args) : await db.q('UPDATE `' + s.t + '` SET ' + s.set + ' WHERE ' + s.where, s.setArgs.concat(s.args));
res.sql[key] = (res.sql[key] || 0) + Number(r.affectedRows || 0);
}
// other members' chat mute lists that name them
const mutes = await db.q('SELECT email, chat_mutes FROM accounts WHERE chat_mutes LIKE ?', [like(E)]);
let mu = 0; for (const m of mutes) { let list = []; try { list = JSON.parse(m.chat_mutes || '[]'); } catch (e) {} const keep = list.filter(x => norm(x) !== E); if (keep.length !== list.length) { mu++; if (!o.dryRun) await db.q('UPDATE accounts SET chat_mutes=? WHERE email=?', [JSON.stringify(keep), m.email]); } }
if (mu) res.sql['accounts.chat_mutes (others, scrubbed)'] = mu;
// their username inside messages that stay (another member's chat to them, a notice to their sponsor about them): the name
// goes, the message stays. Whole words only, usernames of 5+ characters (a short one could be an ordinary word).
let rd = 0;
for (const u of exact.filter(x => x.length >= 5 && ((acct && norm(acct.username) === x) || names.includes(x)))) {
const re = new RegExp('(^|[^a-z0-9_])@?' + u.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![a-z0-9_])', 'gi');
for (const m of await db.q('SELECT id, subject, body FROM sponsor_messages WHERE subject LIKE ? OR body LIKE ?', [like(u), like(u)])) {
const sub = String(m.subject || '').replace(re, '$1[erased member]'), body = m.body == null ? null : String(m.body).replace(re, '$1[erased member]');
if (sub === m.subject && body === m.body) continue;
rd++; if (!o.dryRun) await db.q('UPDATE sponsor_messages SET subject=?, body=? WHERE id=?', [sub, body, m.id]);
}
}
if (rd) res.sql['sponsor_messages (others, name removed)'] = rd;
} else if (acct && !o.dryRun) { const r = await R.accounts.removeAccount(E); res.sql.accounts = r && r.ok ? 1 : 0; }
else if (acct) res.sql.accounts = 1;
res.docs = docs(needles, o.dryRun);
if (!o.dryRun) for (const f of R.forget || []) { try { f(E); } catch (e) {} } // caches that are not documents (hub lookups, pending pushes)
for (const k of Object.keys(res.sql)) if (!res.sql[k]) delete res.sql[k];
for (const k of Object.keys(res.docs)) if (!res.docs[k]) delete res.docs[k];
if (o.sweep) { res.residue = await residue(E, exact); res.docResidue = o.dryRun ? [] : docResidue(needles); }
if (!o.dryRun) {
const s = load(); s.log.push({ at: Date.now(), by: String(o.by).slice(0, 20), hash: h.slice(0, 16), forced: res.forced, found: res.found,
sql: Object.values(res.sql).reduce((a, b) => a + b, 0), docs: Object.keys(res.docs).length, residue: (res.residue || []).length });
if (s.log.length > 500) s.log = s.log.slice(-500); save();
console.log('member erase', h.slice(0, 16), 'by', o.by, 'sql rows', JSON.stringify(res.sql), 'docs', JSON.stringify(res.docs));
}
res.ok = true; return res;
}
// the hub's member.erased event carries only the SHA-256 of the email: find who here has it (accounts, then the help desk)
async function byHash(hash, by) {
const h = norm(hash); if (!/^[0-9a-f]{64}$/.test(h)) return { result: 'bad-hash' };
let email = null;
for (const a of await R.accounts.identities()) if (hashOf(a.email) === h) { email = norm(a.email); break; }
if (!email && db.enabled()) { try { for (const r of await db.q('SELECT DISTINCT email FROM tickets')) if (hashOf(r.email) === h) { email = norm(r.email); break; } } catch (e) {} }
if (!email) { const s = load(); s.tomb[h] = Date.now(); save(); return { result: 'not-here' }; }
const r = await erase(email, { dryRun: false, by: by || 'hub', sweep: false });
return { result: r.error ? 'refused' : 'erased', error: r.error || null, sql: r.sql, docs: r.docs };
}
function view() { const s = load(); return { tombstones: Object.keys(s.tomb).length, recent: s.log.slice(-20).reverse() }; }
module.exports = { init, erase, byHash, isErased, hashOf, view, _reset: () => { st = null; } };
+13 -1
View File
@@ -16,6 +16,8 @@
// Rule 2 (2026-11-14): the sponsor written for an arrival is person.locks.iap's sponsor when that lock exists, never the
// plain network sponsor. QUIET: nothing on this path sends mail, a notice or a post, and lssync.js never
// pushes a hub waiting account to LinkSpin (qa/hubsync.test.cjs, mail audit).
// member.erased (2026-11-15) the hub erased someone: erase.js finds them by the SHA-256 of the email and takes them out
// here too; refused (wallet, member number, team) = a log note, never retried.
// anything else ignored.
// Each seq is applied once (done map). A failing event answers 503 so the hub retries it; after 5 tries it is set aside
// in the log so one bad row cannot hold every later event back.
@@ -130,9 +132,19 @@ async function walletConnected(ev) {
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
return 'applied';
}
// member.erased (2026-11-15): the hub erased someone; erase.js takes them out here too, found by the SHA-256 of the email
// (the event carries nothing else). Refused here (a wallet, a member number, a team) = noted for Marty, never retried.
async function memberErased(ev) {
if (!R.erase) return 'ignored';
const r = await R.erase.byHash(ev.data && ev.data.emailHash, 'hub');
if (r.result === 'refused') note({ type: 'erase-refused', hash: String(ev.data.emailHash).slice(0, 16), error: String(r.error || '').slice(0, 200) });
else note({ type: 'erased', hash: String((ev.data && ev.data.emailHash) || '').slice(0, 16), result: r.result });
return r.result === 'erased' ? 'applied' : 'ignored';
}
async function apply(ev) {
if (ev.type === 'member.joined') return memberJoined(ev);
if (ev.type === 'wallet.connected') return walletConnected(ev);
if (ev.type === 'member.erased') return memberErased(ev);
// sponsor.changed is IGNORED here on purpose (checked 2026-11-14 for the switch-on): it would need the deliberate-change
// record (at / by / previous sponsor) to go through sponsorfollow's rule, and a member locked on the InstantAdPay contract
// must never move anyway (the contract pays whoever it holds). qa/hubsync.test.cjs proves a locked member stays put.
@@ -359,4 +371,4 @@ function adminView() {
return Object.assign({ enabled: enabled(), on: on(), site: SITE(), url: URL_(), since: s.since, outbox: s.outbox.length, retrying: Object.keys(s.tries).length,
disagree: Object.keys(s.disagree).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() });
}
module.exports = { _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
module.exports = { _state: load, _save: save, _forgetHeld: email => held.delete(norm(email)), _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
+1 -1
View File
@@ -59,7 +59,7 @@ const FAQ = [
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
tags: ['wallet', 'position', 'qualified start', 'metamask'],
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.' },
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside your wallet app, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.' },
{ id: 'f-exchange-withdraw', title: 'Sending POL from an exchange', source: 'faq',
questions: ['How do I send POL from Binance or Kraken?', 'Which network do I pick when withdrawing from an exchange?', 'I sent POL on the wrong network'],
tags: ['exchange', 'withdraw', 'network', 'polygon', 'binance', 'kraken'],
+52 -11
View File
@@ -9,6 +9,12 @@
// path serves the new text.
// source canned | faq | ticket | admin
//
// 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 (NAMED_BOOST) and
// skips this site's instant answers (namesOther, chatbot.js). Other sites' entries never take the fast path; they 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. The same
// merge code is in InstantAdPay, LinkSpin and the rebuilt sites' kb.js.
//
// 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).
@@ -22,10 +28,11 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
let netkb = null; try { netkb = require('./netkb'); } catch (e) {}
const db = require('./db');
let DATA_DIR = null, SEEDS = [], ready = null;
let cache = null, cacheAt = 0, index = null;
let cache = null, cacheAt = 0, index = null, netVer = '';
const TTL = 30000; // two app copies run during a deploy, and MySQL is shared: re-read now and then
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
@@ -82,10 +89,38 @@ function buildIndex(entries) {
}
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.
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;
@@ -97,6 +132,8 @@ function rank(idx, query, k) {
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);
@@ -188,9 +225,10 @@ function init(opts) {
}
async function load(force) {
if (ready) await ready;
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
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(); index = buildIndex(cache); rx.clear();
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();
@@ -208,13 +246,16 @@ async function fastPath(msg) {
}
async function search(query, k) { await load(); return rank(index, query, k || 5); }
async function context(query, k) { return relevant(await search(query, k || 5)); }
// this site's own entries, for netkb.publish
async function own() { await load(); return cache.slice(); }
const label = e => e.site ? ' (about ' + e.siteName + ', another network site; send people to ' + e.go + ')' : '';
const HELP = 'Help (https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out)';
function promptBlock(hits) {
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
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 + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\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
@@ -235,7 +276,7 @@ function validate(o, cur) {
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).map(h => Object.assign({ score: h.score }, h.entry));
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);
@@ -246,19 +287,19 @@ async function create(o) {
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);
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);
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);
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
@@ -273,8 +314,8 @@ async function stamp() {
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, title: h.entry.title, score: h.score, used: used.has(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, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };
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 } };
+1 -1
View File
@@ -142,7 +142,7 @@ async function renderPage() {
const w = winners();
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
h += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
h += '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
h += '</div><script src="/assets/common.js?v=20261115nr"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
return h;
}
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
+76
View File
@@ -0,0 +1,76 @@
// Login-ad clock (Marty 2026-11-15): "I definitely don't want somebody to not look at a login ad for 7 days... if login ads are
// available on those sites, they need to be seen several times a day." The SAME file ships in InstantAdPay and LinkSpin.
//
// A member sees the login ad on their next member-area page load whenever their last finished login-ad view on THIS site is more
// than loginAdEveryHours old (site setting, default 3), whether or not they just signed in. One row per member in MySQL
// (table login_ad_views: k = lowercased email, or 'w:' + wallet for a wallet-only session; seen_at; served_at).
// due(k) true when the member should get the login ad now (no row, or seen_at older than the setting)
// served(k) the login ad was handed to this member (the countdown starts on their screen)
// seen(k, s) the countdown ended: counts only when a serve to this member happened at least s - 2 seconds ago and within the
// last 30 minutes, so reloading during the countdown never skips the ad
// forget(k) member erase
// No database (local QA): the same rules in memory. A failed database read answers "due": when in doubt the ad shows.
'use strict';
let pool = null, tableReady = null, hours = () => 3;
const mem = new Map(); // k -> { seen, served }
const SERVE_WINDOW = 30 * 60 * 1000;
const keyOf = s => {
if (!s) return '';
const e = String(s.email || '').trim().toLowerCase();
if (e) return e.slice(0, 190);
const a = String(s.address || '').trim().toLowerCase();
return /^0x[0-9a-f]{40}$/.test(a) ? 'w:' + a : '';
};
const everyMs = () => { const h = Number(hours()); return (Number.isFinite(h) && h > 0 ? Math.min(h, 24 * 30) : 3) * 3600 * 1000; };
function init(opts) {
const o = opts || {};
if (typeof o.hours === 'function') hours = o.hours;
const url = String(o.url || '').trim();
pool = null; tableReady = null; mem.clear();
if (url) { const mysql = require('mysql2/promise'); pool = mysql.createPool({ uri: url, connectionLimit: 3, charset: 'utf8mb4' }); }
}
async function table() {
if (!tableReady) tableReady = pool.query('CREATE TABLE IF NOT EXISTS login_ad_views (k VARCHAR(200) PRIMARY KEY, seen_at BIGINT NOT NULL DEFAULT 0, served_at BIGINT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').catch(e => { tableReady = null; throw e; });
return tableReady;
}
async function row(k) {
if (!pool) return mem.get(k) || null;
await table();
const [r] = await pool.query('SELECT seen_at, served_at FROM login_ad_views WHERE k = ?', [k]);
return r[0] ? { seen: Number(r[0].seen_at) || 0, served: Number(r[0].served_at) || 0 } : null;
}
async function due(k, now) {
if (!k) return false;
const t = now || Date.now();
try { const r = await row(k); return !r || !r.seen || t - r.seen >= everyMs(); } catch (e) { console.error('login-ad clock read', e.message); return true; }
}
async function served(k, now) {
if (!k) return;
const t = now || Date.now();
if (!pool) { const r = mem.get(k) || { seen: 0, served: 0 }; r.served = t; mem.set(k, r); return; }
try { await table(); await pool.query('INSERT INTO login_ad_views (k, served_at) VALUES (?, ?) ON DUPLICATE KEY UPDATE served_at = VALUES(served_at)', [k, t]); }
catch (e) { console.error('login-ad clock serve', e.message); }
}
// -> { ok: true } or { ok: false, reason }
async function seen(k, dwellSec, now) {
if (!k) return { ok: false, reason: 'signed out' };
const t = now || Date.now();
const need = Math.max(0, (Number(dwellSec) || 10) - 2) * 1000;
let r = null; try { r = await row(k); } catch (e) { console.error('login-ad clock read', e.message); return { ok: false, reason: 'store' }; }
if (!r || !r.served || t - r.served > SERVE_WINDOW) return { ok: false, reason: 'not served' };
if (t - r.served < need) return { ok: false, reason: 'too soon' };
if (!pool) { r.seen = t; mem.set(k, r); return { ok: true }; }
try { await pool.query('UPDATE login_ad_views SET seen_at = ? WHERE k = ?', [t, k]); return { ok: true }; }
catch (e) { console.error('login-ad clock seen', e.message); return { ok: false, reason: 'store' }; }
}
async function forget(k) {
if (!k) return;
mem.delete(k);
if (pool) { try { await table(); await pool.query('DELETE FROM login_ad_views WHERE k = ?', [k]); } catch (e) { console.error('login-ad clock forget', e.message); } }
}
module.exports = { init, keyOf, due, served, seen, forget, everyMs };
+2 -2
View File
@@ -160,7 +160,7 @@ async function handle(rows, opts) {
const s = load(); s.stats.batches++;
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
const ctx = { sum, done: new Set(), via: opts && opts.via, refOf: opts && opts.refOf }; const batch = [];
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
for (const x of rows || []) { const r = clean(x); if (!r) continue; if (R.erased && R.erased(r.email)) { sum.erased = (sum.erased || 0) + 1; continue; } sum.rows++; s.rows[r.email] = r; batch.push(r); } // erased here (erase.js): never brought back by a sync
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
try {
for (const r of batch) {
@@ -192,4 +192,4 @@ function networkSponsor(email, address) {
if (/^0x[0-9a-f]{40}$/.test(w)) for (const x of Object.values(s.rows)) if (x.wallet === w && x.sponsorEmail && x.sponsorEmail !== e && x.email !== e) return { sponsorEmail: x.sponsorEmail, via: 'same wallet' };
return null;
}
module.exports = { init, receive, adminView, networkSponsor };
module.exports = { init, receive, adminView, networkSponsor, _state: load, _save: save }; // _state/_save: the member erase (erase.js)
+1 -1
View File
@@ -120,4 +120,4 @@ async function release(email, sent) {
// does LinkSpin know this email? (its row was pushed and recorded) - used by the link-farm admin list, never for a cascade
function knows(email) { const st = load(); return Object.prototype.hasOwnProperty.call(st.hashes || {}, String(email || '').toLowerCase()); }
function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, last: st.last, errors: st.errors, pendingTouches: pending.size }; }
module.exports = { init, touch, tick, adminView, on, mute, release, knows };
module.exports = { _state: load, _save: save, _forget: e => { pending.delete(String(e || '').toLowerCase()); muted.delete(String(e || '').toLowerCase()); }, init, touch, tick, adminView, on, mute, release, knows };
+106
View File
@@ -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 };
+1 -1
View File
@@ -36,7 +36,7 @@ function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list;
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
// 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', stackpol: 'nwsp', earnerscorner: 'nwec' };
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) {
+5 -4
View File
@@ -3,7 +3,7 @@
//
// 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, 30 minutes) and sends the browser to P.
// 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.
@@ -14,7 +14,7 @@
// 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 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
// 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.
@@ -36,10 +36,10 @@ const SKEW = 30 * 1000; // clock skew allowed between the two ser
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 = 1800; // seconds: one silent check per browser per 30 minutes
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' }; // 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)
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}$/;
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
@@ -177,6 +177,7 @@ async function handle(req, res, u) {
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);
+2 -2
View File
@@ -652,8 +652,8 @@
</div>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261112txt"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-kits.js?v=20261101th"></script>
<script src="/assets/admin.js?v=20261115la"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-kits.js?v=20261101th"></script>
</body>
</html>
+1 -1
View File
@@ -1202,7 +1202,7 @@
}));
// site settings: key / value rows; booleans as checkboxes, numbers stay numbers
const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Targets for milestones + daily snapshot: feed = main group, support = IAP support topic, echo = shared payments topic (comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramSupportChatId: 'Telegram support topic: chat id (milestones + daily snapshot)', telegramSupportTopicId: 'Telegram support topic: topic id', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)' };
const SITE_META = { loginAdEveryHours: 'Login ad: show again on the next member page once the last finished view is this many hours old (default 3)', noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Targets for milestones + daily snapshot: feed = main group, support = IAP support topic, echo = shared payments topic (comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramSupportChatId: 'Telegram support topic: chat id (milestones + daily snapshot)', telegramSupportTopicId: 'Telegram support topic: topic id', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)' };
function drawSite() {
const wrap = $('siteForm');
wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '<div class="kv-row"><span class="k" title="' + esc(k) + '">' + esc(SITE_META[k] || humanize(k)) + '</span>'
+21 -4
View File
@@ -70,19 +70,36 @@ window.IAP = (function () {
if (!netList) netList = fetch('/api/network-sites').then(r => r.json()).then(l => (Array.isArray(l) && l.length ? l : NET_FALLBACK)).catch(() => NET_FALLBACK);
return netList;
}
// the footer links carry a referral username (Marty 2026-11-15): the signed-in member's own, else the sponsor this visitor came in on
// (iap.sponsor cookie, usernames only, never a member number or wallet). Tracked links get it as s1 (LinkSpin sends it on as ?ref=),
// plain links as ?ref=. Earners Corner takes none.
const REF_RE = /^[A-Za-z0-9_.-]{1,40}$/;
const okRef = v => REF_RE.test(v) && !/^\d+$/.test(v) && !/^0x[0-9a-f]{40}$/i.test(v) && v !== 'company' && v !== 'top';
const refCookie = () => { const m = document.cookie.match(/(?:^|;\s*)iap\.sponsor=([^;]*)/); try { const v = m ? decodeURIComponent(m[1]) : ''; return okRef(v) ? v : ''; } catch (e) { return ''; } };
let netRef = null;
function networkRef() {
if (!netRef) netRef = fetch('/api/me', { credentials: 'same-origin' }).then(r => r.json()).then(m => (m && m.signedIn && m.username && okRef(m.username) ? m.username : refCookie())).catch(() => refCookie());
return netRef;
}
function withRef(s, ref) {
const href = s.go || s.url; if (!ref || s.id === 'earnerscorner') return href;
try { const u = new URL(href); u.searchParams.set(s.go ? 's1' : 'ref', ref); return u.toString(); } catch (e) { return href; }
}
function renderNetworkLine(host) {
if (!host || host.querySelector('.netline')) return;
const d = document.createElement('div'); d.className = 'netline';
d.style.cssText = 'margin-top:10px;display:flex;gap:6px 14px;justify-content:center;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
host.appendChild(d);
const esc = s => String(s).replace(/[&<>"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[ch]);
const paint = list => {
let list = NET_FALLBACK, ref = refCookie();
const paint = () => {
d.innerHTML = '<b>Part of the network</b><span>One account across the network:</span>' + list.map(s => (s.id === 'iap' || /instantadpay\.com/.test(s.url))
? '<span aria-current="page" style="font-weight:700;color:var(--ink)">' + esc(s.name) + ' (you are here)</span>'
: '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>').join('');
: '<a href="' + esc(withRef(s, ref)) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>').join('');
};
paint(NET_FALLBACK);
networkSites().then(paint);
paint();
networkSites().then(l => { list = l; paint(); });
networkRef().then(r => { if (r !== ref) { ref = r; paint(); } });
}
// pages with their own footer (the members area) get the network line too
function decorateFooters() { document.querySelectorAll('footer.bo-pagefoot').forEach(f => { const w = document.createElement('div'); w.style.width = '100%'; f.appendChild(w); renderNetworkLine(w); }); }
+17 -6
View File
@@ -1009,9 +1009,11 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
render.welcomed = true;
history.replaceState(null, '', '/my' + (location.hash || ''));
(async () => {
try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {}
try { if (await showGauntlet()) showLoginAd.asked = true; else await showLoginAd(); } catch (e) {}
await render();
})();
} else if (!showLoginAd.asked) { // login ad on the member's clock (Marty 2026-11-15): any page load, signed in just now or not; the server says when it is due
(async () => { try { await showLoginAd(); } catch (e) {} if (me.nssoBack && me.username) location.href = '/sso/resume'; })();
}
starterBanner(me).catch(() => {});
setPane(location.hash.slice(1) || 'overview');
@@ -3381,9 +3383,10 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
$('mcVerifyBtn').addEventListener('click', busy($('mcVerifyBtn'), async () => {
const r = await api('/api/auth/email/verify', { email: $('mcEmail').value, code: $('mcCode').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) });
IAP.status('You are in.', 'ok');
if (r.next === '/sso/resume' && !r.created) { try { await showLoginAd(); } catch (e) {} location.href = r.next; return; } // another network site asked: login ad if due, then straight back there (2026-11-15)
if (r.next && !r.created) { location.href = r.next; return; } // came from Drip Runner: straight back into the game
if (r.created && !(r.account && r.account.username)) await showOnboard(); // pick a username first
if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad
if (await showGauntlet()) showLoginAd.asked = true; else await showLoginAd(); // welcome tour outranks the login ad
await render();
}));
})();
@@ -3424,7 +3427,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
$('loginBtn').addEventListener('click', busy($('loginBtn'), async () => {
await api('/api/login', { email: $('liEmail').value, password: $('liPass').value });
IAP.status('Logged in.', 'ok');
if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad
if (await showGauntlet()) showLoginAd.asked = true; else await showLoginAd(); // welcome tour outranks the login ad
await render();
}));
$('linkBtn').addEventListener('click', busy($('linkBtn'), async () => {
@@ -3649,10 +3652,15 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
// out sit on the ad itself (Brian Holland, 2026-10-09: "no timer, no X").
// Sites that refuse framing open in a new tab instead, with the bar saying
// so; the timer is not paused, the member is expected to be on the ad.
// 2026-11-15: shown on the member's clock (loginadclock.js, site setting loginAdEveryHours), asked once per page load; the end of
// the countdown tells the server (POST /api/ads/login/seen). back = a network sign-in hop waiting (another site asked): the
// finish button continues it, back to the site and page it came from, never the dashboard (Marty was stranded here from 5xYourTeam).
async function showLoginAd() {
if (showLoginAd.asked) return; showLoginAd.asked = true;
try {
const { ad } = await (await fetch('/api/ads/slot?type=login')).json();
const { ad, back } = await (await fetch('/api/ads/slot?type=login')).json();
if (!ad || !ad.targetUrl) return;
$('lgContinue').textContent = back ? 'Continue' : 'Go to dashboard';
const gate = $('loginGate');
const openBtn = $('lgOpen');
const goBtn = $('lgContinue');
@@ -3675,6 +3683,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
if (frame) { frame.hidden = true; frame.src = 'about:blank'; }
if (body) body.hidden = false;
openBtn.disabled = false;
const pop = document.querySelector('.iap-welcome'); if (pop) pop.style.display = 'none'; // the session pop-up waits until the login ad is done (welcome.js holds new ones back too)
gate.hidden = false;
await new Promise(done => {
openBtn.onclick = () => {
@@ -3698,13 +3707,15 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
clearInterval(t);
timer.textContent = 'Time is up';
timer.classList.add('done');
$('lgStatus').textContent = 'Thanks for the look. Your dashboard is ready.';
fetch('/api/ads/login/seen', { method: 'POST' }).catch(() => {});
$('lgStatus').textContent = back ? 'Thanks for the look. Continue to finish signing in where you came from.' : 'Thanks for the look. Your dashboard is ready.';
goBtn.hidden = false;
}, 1000);
goBtn.onclick = () => done();
goBtn.onclick = () => { if (back) { goBtn.disabled = true; location.href = back; return; } done(); };
};
});
gate.hidden = true;
if (pop) pop.style.display = '';
if (frame) { frame.src = 'about:blank'; frame.hidden = true; }
if (body) body.hidden = false;
$('lgTimer').classList.remove('done');
+5 -2
View File
@@ -1,11 +1,14 @@
// Promo tools > Network sites (Marty 2026-11-14): the promo kits of the other network sites, read live from each site's own public
// feed (GET <site>/api/promo-kit?u=<username>), so a creative or line changed on Downline Banners or Viral Banner Blitz shows here
// feed (GET <site>/api/promo-kit?u=<username>), so a creative or line changed on any of those sites shows here (ViralAdBlitz, DownlineHydra and 5xYourTeam added 2026-11-15)
// at once. Usernames are network-wide: the member's InstantAdPay username is their sponsor link on those sites even if they never
// visited them. Nothing is stored here.
window.IAPNetKits = (function () {
const SITES = [
{ key: 'dlb', name: 'Downline Banners', feed: 'https://downlinebanners.com/api/promo-kit', blurb: 'One global line of $5 banner spots on Polygon. A spot buys 300 guaranteed views on the board and a place in the line; every sale is split on-chain in the same transaction. Nothing is promised: a spot is paid only when spots sell after it.' },
{ key: 'vbb', name: 'Viral Banner Blitz', feed: 'https://viralbannerblitz.com/api/promo-kit', blurb: 'One shared loop of 125x125 banners. Network members post free once a day, real visitors push the loop, and a banner that rides out earns network ad views. Weekly leaderboards for visitors sent. Advertising, not income.' }
{ key: 'vbb', name: 'Viral Banner Blitz', feed: 'https://viralbannerblitz.com/api/promo-kit', blurb: 'One shared loop of 125x125 banners. Network members post free once a day, real visitors push the loop, and a banner that rides out earns network ad views. Weekly leaderboards for visitors sent. Advertising, not income.' },
{ key: 'vab', name: 'ViralAdBlitz', feed: 'https://viraladblitz.com/api/promo-kit', blurb: 'Your free text ad shows on your whole team\'s pages, five levels deep. A $5 Boost adds 500 views; every Boost is split on-chain in the same transaction. Nothing is promised.' },
{ key: 'dh', name: 'DownlineHydra', feed: 'https://downlinehydra.com/api/promo-kit', blurb: 'One join, many heads: one free account and one sponsor line across the network, plus the downline builder for the programs you promote. Pro is $30 one time, never a subscription, split on-chain. Nothing is promised.' },
{ key: 'fivex', name: '5xYourTeam', feed: 'https://5xyourteam.com/api/promo-kit', blurb: 'The weekly draft for people who need a sponsor. A $10 position lets you draft people waiting in the holding tank and coach them. Nothing is promised.' }
];
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const $ = id => document.getElementById(id);
+14 -4
View File
@@ -4,6 +4,14 @@
var me = (document.currentScript && document.currentScript.getAttribute('data-site')) || 'iap';
var FALLBACK = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(function (a) { return { id: a[0], name: a[1], url: a[2] }; });
// the links carry a referral username (Marty 2026-11-15): the signed-in member's own, else the sponsor this visitor came in on
// (iap.sponsor cookie, usernames only). Tracked links get it as s1 (LinkSpin sends it on as ?ref=), plain links as ?ref=; Earners Corner none.
function okRef(v) { return /^[A-Za-z0-9_.-]{1,40}$/.test(v) && !/^\d+$/.test(v) && !/^0x[0-9a-f]{40}$/i.test(v) && v !== 'company' && v !== 'top'; }
function refCookie() { var m = document.cookie.match(/(?:^|;\s*)iap\.sponsor=([^;]*)/); try { var v = m ? decodeURIComponent(m[1]) : ''; return okRef(v) ? v : ''; } catch (e) { return ''; } }
function withRef(s, ref) {
var href = s.go || s.url; if (!ref || s.id === 'earnerscorner') return href;
try { var u = new URL(href); u.searchParams.set(s.go ? 's1' : 'ref', ref); return u.toString(); } catch (e) { return href; }
}
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); }
function run() {
var f = document.querySelector('footer'); if (!f || f.querySelector('.netline')) return;
@@ -12,13 +20,15 @@
var box = document.createElement('div'); box.className = 'netline';
box.style.cssText = 'flex-basis:100%;width:100%;margin-top:10px;display:flex;gap:6px 14px;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
host.appendChild(box);
var paint = function (list) {
var list = FALLBACK, ref = refCookie();
var paint = function () {
box.innerHTML = (hasLegal ? '' : '<span style="flex-basis:100%"><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="/support">Support</a></span>') + '<span style="flex-basis:100%">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</span><b>Part of the network</b><span>One account across the network:</span>' + list.map(function (s) {
return s.id === me ? '<span aria-current="page" style="font-weight:700">' + esc(s.name) + ' (you are here)</span>' : '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>';
return s.id === me ? '<span aria-current="page" style="font-weight:700">' + esc(s.name) + ' (you are here)</span>' : '<a href="' + esc(withRef(s, ref)) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>';
}).join('');
};
paint(FALLBACK);
fetch('/api/network-sites').then(function (r) { return r.json(); }).then(function (l) { if (Array.isArray(l) && l.length) paint(l); }).catch(function () {});
paint();
fetch('/api/network-sites').then(function (r) { return r.json(); }).then(function (l) { if (Array.isArray(l) && l.length) { list = l; paint(); } }).catch(function () {});
fetch('/api/me', { credentials: 'same-origin' }).then(function (r) { return r.json(); }).then(function (m) { if (m && m.signedIn && m.username && okRef(m.username)) { ref = m.username; paint(); } }).catch(function () {});
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
})();
+8
View File
@@ -148,6 +148,14 @@ window.IAPSupport = (function () {
+ '<div id="supCheck" hidden style="margin-top:12px"></div>'
+ '<div class="sup-actions"><button class="btn" type="submit" id="supSend">Send to support</button><span class="small muted" id="supMsg"></span></div>'
+ '</form></div>';
// hand-off from a network site's chat assistant (2026-11-15): ?from=<site id>&subject=<question> prefills the subject and names
// the site in the message, so the ticket says where it came from. Plain text only (value / textContent), never HTML.
try {
const qs = new URLSearchParams(location.search); const SITES = { viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', fivex: '5xYourTeam', vbb: 'Viral Banner Blitz', bannerline: 'Downline Banners', stackpol: 'Stack POL' };
const from = SITES[String(qs.get('from') || '').toLowerCase()]; const subj = String(qs.get('subject') || '').replace(/[\u0000-\u001f<>]/g, ' ').trim().slice(0, 140);
if (subj) document.getElementById('supSubject').value = subj;
if (from) document.getElementById('supBody').value = 'About ' + from + ': ';
} catch (e) {}
const f = document.getElementById('supForm');
f.addEventListener('submit', async e => {
e.preventDefault();
+39
View File
@@ -0,0 +1,39 @@
// "How to get fed leads" (holding tank batches, Marty 2026-11-15): the ladder and the member's own level and next step, on the
// Overview. Hidden while the tankBatches switch is off (/api/my/tank/feed answers { on:false }). Leads you can sponsor, never money.
(function () {
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const day = t => t ? new Date(t).toLocaleString('en-US', { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'America/Chicago' }) + ' CT' : '';
function mount() {
let el = document.getElementById('tankFeedCard'); if (el) return el;
el = document.createElement('div'); el.className = 'card'; el.id = 'tankFeedCard'; el.hidden = true; el.setAttribute('data-jump', 'How to get fed leads');
const notice = document.getElementById('tankNotice'); const host = notice && notice.closest('.card');
const tankCard = document.getElementById('tankCard');
if (host && host.parentNode) host.parentNode.insertBefore(el, host.nextSibling);
else if (tankCard && tankCard.parentNode) tankCard.parentNode.insertBefore(el, tankCard);
else return null;
return el;
}
function html(v) {
const me = v.me || {};
const rows = (v.ladder || []).map(r => '<li><b>' + esc(r.level) + '</b>: ' + (r.level === 'Streak' ? 'up to ' : '') + r.size + ' people at a time, with ' + esc(r.how) + '</li>').join('');
const mine = me.level
? '<p>Your level: <b>' + esc(me.label || me.level) + '</b>, ' + me.size + ' people at a time' + (me.active ? '' : ' (sign in at least once a week to receive them)') + '.'
+ (me.open ? ' You are helping ' + me.open + ' from your batches right now.' : '') + (me.nextBatchAt ? ' Next batch from ' + esc(day(me.nextBatchAt)) + '.' : '') + '</p>'
: '<p>You are not on the ladder yet.</p>';
return '<div class="card-head"><h3>How to get fed leads</h3><span class="sub">people from the holding tank you can sponsor</span></div>'
+ '<p class="small">Members who joined with no sponsor wait in the holding tank. Active members who bought their own package receive a batch of them every ' + esc(v.everyDays) + ' days, and they become your referrals to welcome and help. These are leads you can sponsor: what happens next depends on your follow-up, and nothing here is a promise of income.</p>'
+ '<ul class="small" style="margin:6px 0 8px 18px;padding:0">' + rows + '</ul>' + mine
+ (me.next ? '<p class="small"><b>Next step:</b> ' + esc(me.next) + '</p>' : '')
+ '<p class="muted small">Say hello to each new person within ' + esc(v.followDays) + ' days (a chat, or Contacted them on their row in My line). Anyone you have not contacted by then goes back to the tank for another member.</p>';
}
async function load() {
try {
const v = await (await fetch('/api/my/tank/feed', { cache: 'no-store' })).json();
const el = mount(); if (!el) return;
if (!v || !v.on) { el.hidden = true; return; }
el.innerHTML = html(v); el.hidden = false;
} catch (e) {}
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', load); else load();
setInterval(load, 600000);
})();
+2
View File
@@ -33,6 +33,8 @@
function show(f) {
if (document.querySelector('.iap-welcome')) return;
// the login ad has the screen (2026-11-15: it now shows on any dashboard load): wait until it closes, never on top of it
var lg = document.getElementById('loginGate'); if (lg && !lg.hidden) { setTimeout(function () { show(f); }, 1000); return; }
var fri = fridayLine(f);
var back = document.createElement('div');
+1 -1
View File
@@ -165,7 +165,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script>
<script src="/assets/common.js?v=20261115nr"></script>
<script src="/assets/bixpay-guide.js?v=20261029bz"></script>
</body>
</html>
+1 -1
View File
@@ -143,7 +143,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/contract.js?v=20260908p"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
+2 -2
View File
@@ -265,8 +265,8 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script>
<script src="/assets/common.js?v=20261115nr"></script>
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
</body>
</html>
+1 -1
View File
@@ -27,7 +27,7 @@
<p class="muted small">You decide whether, and how much, to spend. Never spend more than you can afford to lose.</p>
</div>
</div></section>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/legal.js?v=20260908a"></script>
</body>
</html>
+2 -2
View File
@@ -97,7 +97,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
</body>
</html>
+1 -1
View File
@@ -127,7 +127,7 @@
</ul>
</div>
</div></section>
<script src="/assets/common.js?v=20261114ns"></script>
<script src="/assets/common.js?v=20261115nr"></script>
<script src="/assets/legal.js?v=20260908a"></script>
</body>
</html>
+2 -2
View File
@@ -72,7 +72,7 @@
</footer>
</div>
<script src="/assets/friday.js?v=20260925a"></script>
<script src="/assets/common.js?v=20261114ns"></script>
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
<script src="/assets/common.js?v=20261115nr"></script>
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
</body>
</html>
+2 -2
View File
@@ -79,7 +79,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/games-page.js?v=20261012b"></script>
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/games-page.js?v=20261012b"></script>
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
</body>
</html>
+1 -1
View File
@@ -506,7 +506,7 @@
</div>
</section>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/wallet.js?v=20260909c"></script>
<script src="/assets/home.js?v=20261027tb"></script>
<script src="/assets/chat.js?v=20261016n"></script>
+1 -1
View File
@@ -158,7 +158,7 @@
InstantAdPay · <a href="/contract">Contract</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a> · <a href="/disclaimer">Disclaimer</a>
</div>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/join.js?v=20261107nc"></script>
</body>
</html>
+1 -1
View File
@@ -106,7 +106,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/launch.js?v=20260915b"></script>
</body>
</html>
+1 -1
View File
@@ -41,7 +41,7 @@
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/ledger.js?v=20260906m"></script>
<script src="https://polhunter.com/embed.js" data-slots="1" async></script>
<script src="/assets/chat.js?v=20261016n"></script>
+5 -5
View File
@@ -1306,13 +1306,13 @@
</div>
</div>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/wallet.js?v=20260911a"></script>
<script src="/assets/promo.js?v=20261103gp"></script>
<script src="/assets/support.js?v=20261101th"></script>
<script src="/assets/netkits.js?v=20261114ns"></script>
<script src="/assets/my.js?v=20261114kes"></script>
<script src="/assets/fuel.js?v=20261113sso"></script>
<script src="/assets/support.js?v=20261115cb"></script>
<script src="/assets/netkits.js?v=20261115nk"></script>
<script src="/assets/my.js?v=20261115la"></script>
<script src="/assets/fuel.js?v=20261113sso"></script><script src="/assets/tankfeed.js?v=20261115tb"></script>
<script src="/assets/engine-room.js?v=20261113sso"></script>
<script src="/assets/netsso.js?v=20261113sso"></script>
<script src="/assets/chat.js?v=20261016n"></script>
+2 -2
View File
@@ -131,8 +131,8 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/partners.js?v=20260914a"></script>
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
</body>
</html>
+1 -1
View File
@@ -194,7 +194,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/plays.js?v=20260910b"></script>
</body>
</html>
+1 -1
View File
@@ -87,6 +87,6 @@
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/presentation.js?v=20261015b"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/presentation.js?v=20261015b"></script>
</body>
</html>
+1 -1
View File
@@ -32,7 +32,7 @@
<p class="muted small">We use reasonable safeguards, but no system is perfectly secure. Protect your email and your wallet.</p>
</div>
</div></section>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/legal.js?v=20260908a"></script>
</body>
</html>
+1 -1
View File
@@ -261,6 +261,6 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script>
<script src="/assets/common.js?v=20261115nr"></script>
</body>
</html>
+2 -2
View File
@@ -20,9 +20,9 @@
<div id="supMain"><div class="card"><p class="muted small">Loading…</p></div></div>
<p class="small muted">We will never ask for your recovery phrase or private key, and nobody from InstantAdPay will message you first asking for money or wallet access.</p>
</div></section>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/legal.js?v=20260908a"></script>
<script src="/assets/support.js?v=20261101th"></script>
<script src="/assets/support.js?v=20261115cb"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
</html>
+1 -1
View File
@@ -42,7 +42,7 @@
<p class="muted small" style="margin-top:18px">See also the <a href="/disclaimer">Disclaimer</a> and <a href="/privacy">Privacy Policy</a>. Questions: the <a href="/support">support page</a> or <a href="mailto:support@instantadpay.com">support@instantadpay.com</a>.</p>
</div>
</div></section>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/legal.js?v=20260908a"></script>
</body>
</html>
+1 -1
View File
@@ -35,7 +35,7 @@
<p><a href="/ledger">← Back to the live ledger</a> · <a href="/contract">Read the contract review</a></p>
</div>
</section>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/tx.js?v=20260906m"></script>
</body>
</html>
+1 -1
View File
@@ -48,7 +48,7 @@
</div>
</div>
</section>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/wall.js?v=20261030pp"></script>
</body>
</html>
+1 -1
View File
@@ -123,7 +123,7 @@
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never share your recovery phrase.</div>
</footer>
</div>
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
<script src="/assets/wallets.js?v=20260911b"></script>
</body>
</html>
+2 -2
View File
@@ -65,7 +65,7 @@
</footer>
</div>
<script src="/assets/wednesday.js?v=20260929c"></script>
<script src="/assets/common.js?v=20261114ns"></script>
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
<script src="/assets/common.js?v=20261115nr"></script>
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
</body>
</html>
+77
View File
@@ -0,0 +1,77 @@
// Member erase (erase.js) against a REAL, disposable MySQL: the SQL half (deletes, the chat message another member keeps,
// the help-desk ticket kept as scrubbed history, other members' mute lists, the residue sweep). Skipped without
// TEST_DATABASE_URL. Synthetic members only; NEVER point it at a live database (it creates and fills tables).
// TEST_DATABASE_URL=mysql://root:pw@127.0.0.1:3306/scratch node qa/erase.mysql.test.cjs
'use strict';
const fs = require('fs'); const os = require('os'); const path = require('path'); const assert = require('assert');
const ROOT = path.join(__dirname, '..');
const URL_ = process.env.TEST_DATABASE_URL;
if (!URL_) { console.log('erase mysql: TEST_DATABASE_URL not set, skipped'); process.exit(0); }
process.env.DATABASE_URL = URL_; delete process.env.DOCSTORE_URL;
const db = require(path.join(ROOT, 'db.js')); const accounts = require(path.join(ROOT, 'accounts.js')); const erase = require(path.join(ROOT, 'erase.js'));
const E = 'gone9@example.test', O = 'other9@example.test';
(async () => {
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'erase-sql-'));
{ // db.js alters promo_codes and visit_seen before it creates them (fine on the live database, not on an empty one)
const c0 = await require('mysql2/promise').createConnection(URL_);
await c0.query(`CREATE TABLE IF NOT EXISTS promo_codes (code VARCHAR(24) NOT NULL PRIMARY KEY, credits INT NOT NULL, partner VARCHAR(80) NULL, note VARCHAR(200) NULL,
max_uses INT NOT NULL DEFAULT 0, expires BIGINT NOT NULL DEFAULT 0, active TINYINT NOT NULL DEFAULT 1, created BIGINT NOT NULL)`);
await c0.query('CREATE TABLE IF NOT EXISTS visit_seen (campaign_id INT NOT NULL, email VARCHAR(190) NOT NULL, day CHAR(10) NOT NULL, ts BIGINT NOT NULL, UNIQUE KEY uq_visit (campaign_id, email), INDEX (email, day))');
await c0.end();
}
await db.init({ dataDir: DIR }); accounts.init({ dataDir: DIR });
const q = db.q;
await q('CREATE TABLE IF NOT EXISTS account_signals (email VARCHAR(190) PRIMARY KEY, signup_ip VARCHAR(45) NULL)');
await q('CREATE TABLE IF NOT EXISTS ad_clicks (id VARCHAR(16) PRIMARY KEY, campaign_id INT NOT NULL, owner_email VARCHAR(190) NOT NULL, ts BIGINT NOT NULL)');
await q('CREATE TABLE IF NOT EXISTS event_marks (k VARCHAR(160) PRIMARY KEY, ts BIGINT NOT NULL)');
const now = Date.now();
await q("INSERT INTO accounts (email, sponsor_ref, code, created, username) VALUES (?, 'akuwhite', 'gonec01', ?, 'goneuser9'), (?, '', 'othc01', ?, 'other9')", [E, now, O, now]);
await q('UPDATE accounts SET chat_mutes=? WHERE email=?', [JSON.stringify([E, 'x@example.test']), O]);
await q("INSERT INTO sessions (token, email, member_id, expires) VALUES ('t1', ?, 0, ?)", [E, now + 1e6]);
const c = await q("INSERT INTO campaigns (owner_email, member_id, type, name, target_url, budget, status, created) VALUES (?, 0, 'visits', 'x', 'https://x.test', 60, 'out', ?)", [E, now]);
const cid = c.insertId;
await q("INSERT INTO camp_hours (campaign_id, day, hour, n) VALUES (?, '2026-11-01', 1, 3)", [cid]);
await q("INSERT INTO visit_seen (campaign_id, email, day, ts) VALUES (?, ?, '2026-11-01', 1)", [cid, O]); // another member's visit to THEIR ad
await q("INSERT INTO visit_seen (campaign_id, email, day, ts) VALUES (999, ?, '2026-11-01', 1)", [E]);
await q("INSERT INTO ad_clicks (id, campaign_id, owner_email, ts) VALUES ('c1', ?, ?, 1)", [cid, E]);
await q('INSERT INTO earned_credits (email, balance, updated) VALUES (?, 551, 1), (?, 10, 1)', [E, O]);
await q("INSERT INTO credit_log (email, ts, day, delta, kind, note) VALUES (?, 1, '2026-11-01', 5, 'x', 'n')", [E]);
await q("INSERT INTO account_signals (email, signup_ip) VALUES (?, '1.2.3.4')", [E]);
await q("INSERT INTO adoptions (adoptee, adopter, ts, expires) VALUES (?, ?, 1, 2)", [E, O]);
await q("INSERT INTO event_marks (k, ts) VALUES (?, 1), ('keep:other', 1)", ['tankpay1:' + E + ':17']);
await q("INSERT INTO sponsor_messages (from_member, from_email, to_email, subject, body, sent, kind) VALUES (0, ?, ?, '', 'their words', 1, 'chat'), (0, ?, ?, '', 'my words', 2, 'chat'), (1, 'admin@example.test', ?, 'Your ad', 'n', 3, 'notice'), (1, 'admin@example.test', ?, '@goneuser9 has not switched on payouts', '<p>@goneuser9 needs a nudge; goneuser99 is someone else</p>', 4, 'notice')", [E, O, O, E, E, O]);
const tk = await q("INSERT INTO tickets (ref, platform, email, name, username, subject, category, created, updated) VALUES ('LS-9001', 'linkspin', ?, 'Gone Person', 'goneuser9', 'delete me', 'account', 1, 1)", [E]);
await q("INSERT INTO ticket_messages (ticket_id, author, body, created) VALUES (?, 'member', 'please delete gone9@example.test', 1), (?, 'admin', 'Done.', 2)", [tk.insertId, tk.insertId]);
let fails = 0;
const t = async (name, fn) => { try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.stack.split('\n').slice(0, 3).join(' | ')); } };
erase.init({ dataDir: DIR, accounts, docstore: null, owners: {}, reload: {}, forget: [] });
await t('dry run counts every table and changes nothing', async () => {
const r = await erase.erase(E);
assert.strictEqual(r.sql.accounts, 1); assert.strictEqual(r.sql.campaigns, 1); assert.strictEqual(r.sql.camp_hours, 1); assert.strictEqual(r.sql.visit_seen, 2);
assert.strictEqual(r.sql.sponsor_messages, 2, 'sent by them + the notice to them'); assert.strictEqual(r.sql['sponsor_messages (kept, scrubbed)'], 1);
assert.strictEqual(r.sql['tickets (kept, scrubbed)'], 1); assert.strictEqual(r.sql['ticket_messages (kept, scrubbed)'], 1);
assert.strictEqual(r.sql['accounts.chat_mutes (others, scrubbed)'], 1);
assert.ok(r.residue.length > 0); assert.strictEqual((await q('SELECT COUNT(*) n FROM accounts WHERE email=?', [E]))[0].n, 1);
});
await t('erase: rows gone, the other member keeps their message (recipient tombstoned), the ticket stays scrubbed, residue empty', async () => {
const r = await erase.erase(E, { dryRun: false });
assert.strictEqual(r.ok, true); assert.deepStrictEqual(r.residue, [], JSON.stringify(r.residue));
const one = async (sql, a) => Number((await q(sql, a))[0].n);
assert.strictEqual(await one('SELECT COUNT(*) n FROM accounts WHERE email=?', [E]), 0); assert.strictEqual(await one('SELECT COUNT(*) n FROM accounts WHERE email=?', [O]), 1);
assert.strictEqual(await one('SELECT COUNT(*) n FROM campaigns WHERE id=?', [cid]), 0); assert.strictEqual(await one('SELECT COUNT(*) n FROM visit_seen WHERE campaign_id=?', [cid]), 0);
assert.strictEqual(await one('SELECT COUNT(*) n FROM earned_credits WHERE email=?', [O]), 1); assert.strictEqual(await one("SELECT COUNT(*) n FROM event_marks WHERE k='keep:other'"), 1);
const msgs = await q('SELECT from_email, to_email, subject, body FROM sponsor_messages ORDER BY sent');
assert.deepStrictEqual(msgs.map(m => [m.from_email, m.body]), [[O, 'my words'], ['admin@example.test', '<p>[erased member] needs a nudge; goneuser99 is someone else</p>']]); assert.ok(/^erased-[0-9a-f]{12}@erased\.invalid$/.test(msgs[0].to_email));
assert.strictEqual(msgs[1].subject, '[erased member] has not switched on payouts', 'a notice to someone else about them keeps its text, not their name'); assert.strictEqual(r.sql['sponsor_messages (others, name removed)'], 1);
const [tkt] = await q("SELECT email, name, username FROM tickets WHERE ref='LS-9001'"); assert.ok(/@erased\.invalid$/.test(tkt.email)); assert.strictEqual(tkt.name, null);
const tm = await q('SELECT author, body FROM ticket_messages ORDER BY id'); assert.ok(/removed/.test(tm[0].body)); assert.strictEqual(tm[1].body, 'Done.');
assert.deepStrictEqual(JSON.parse((await q('SELECT chat_mutes FROM accounts WHERE email=?', [O]))[0].chat_mutes), ['x@example.test']);
});
await t('a second pass with names cleans a username left in a kept message after the account is gone', async () => {
await q("INSERT INTO sponsor_messages (from_member, from_email, to_email, subject, body, sent, kind) VALUES (0, ?, ?, '', 'Hey goneuser9, welcome', 9, 'chat')", [O, 'x@example.test']);
const r = await erase.erase(E, { dryRun: false, names: ['goneuser9'] });
assert.strictEqual(r.found, false); assert.strictEqual(r.sql['sponsor_messages (others, name removed)'], 1); assert.deepStrictEqual(r.residue, []);
assert.strictEqual((await q('SELECT body FROM sponsor_messages WHERE sent=9'))[0].body, 'Hey [erased member], welcome');
});
console.log(fails ? fails + ' FAILED' : 'erase mysql: all passed'); process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });
+105
View File
@@ -0,0 +1,105 @@
// Member erase (erase.js + scrub.js, 2026-11-15, ticket LS-1021) in JSON mode on a throwaway DATA_DIR, synthetic members only:
// scrub rules, dry run changes nothing, a module's live copy is scrubbed and saved (not overwritten later), plain documents
// and JSON Lines through the fs layer, a reload hook, the tombstone, blockers + force, the hub's member.erased event through
// hubsync.receive, and scrub.js being the same file in the sibling LinkSpin / InstantAdPay checkout.
// node qa/erase.test.cjs
'use strict';
const fs = require('fs'); const os = require('os'); const path = require('path'); const crypto = require('crypto'); const assert = require('assert');
const ROOT = path.join(__dirname, '..');
let fails = 0, n = 0;
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e && e.stack ? e.stack.split('\n').slice(0, 3).join(' | ') : e); } }
delete process.env.DATABASE_URL; delete process.env.DOCSTORE_URL;
const { scrubDeep, scrubText, mentions } = require(path.join(ROOT, 'scrub.js'));
const E = 'gone.person9@example.test', OTHER = 'stay@example.test';
const needles = { emails: [E], exact: ['goneuser', 'abc1234'] };
(async () => {
await t('scrub: keys, list items, records and map values go; other people and look-alikes stay', () => {
const doc = { byEmail: { [E]: { u: 'goneuser' }, [OTHER]: { u: 'stay', sponsorEmail: 'x@example.test' } }, byCode: { abc1234: E, zzz9999: OTHER },
sends: [{ subject: 'Hi', recipients: [OTHER, E, 'xgone.person9@example.test'], delivered: [E] }],
log: [{ ts: 1, email: E, action: 'adopt' }, { ts: 2, email: OTHER }, { ts: 3, note: 'tankpay1:' + E + ':17' }],
clicks: { a1: { owner: E, n: 3 }, a2: { owner: OTHER, n: 1 } }, own: { 's:1': { [E]: 5, [OTHER]: 6 } }, nums: [1, 2, 3],
names: ['goneuserx', 'goneuser'], text: 'goneuser is a word here, kept',
prov: { [OTHER]: { sponsorEmail: E, at: 1 } }, team: [{ email: OTHER, sponsorEmail: E, ts: 4 }] };
const removed = scrubDeep(doc, needles);
assert.ok(removed >= 9, 'removed ' + removed);
assert.deepStrictEqual(Object.keys(doc.byEmail), [OTHER]); assert.deepStrictEqual(doc.byCode, { zzz9999: OTHER });
assert.deepStrictEqual(doc.sends[0].recipients, [OTHER, 'xgone.person9@example.test'], 'a longer address that contains it is someone else');
assert.deepStrictEqual(doc.sends[0].delivered, []); assert.deepStrictEqual(doc.log.map(x => x.ts), [2]);
assert.deepStrictEqual(Object.keys(doc.clicks), ['a2']); assert.deepStrictEqual(doc.own, { 's:1': { [OTHER]: 6 } });
assert.deepStrictEqual(doc.names, ['goneuserx'], 'a username only matches a whole string'); assert.strictEqual(doc.text, 'goneuser is a word here, kept');
assert.deepStrictEqual(doc.nums, [1, 2, 3]);
assert.deepStrictEqual(doc.prov, { [OTHER]: { sponsorEmail: null, at: 1 } }, "another member's record only loses the pointer");
assert.deepStrictEqual(doc.team, [{ email: OTHER, sponsorEmail: null, ts: 4 }]);
const lines = [JSON.stringify({ e: OTHER }), JSON.stringify({ e: E }), JSON.stringify({ u: 'goneuser' })].join('\n');
const r = scrubText(lines, needles, true); assert.strictEqual(r.removed, 2); assert.strictEqual(r.body, JSON.stringify({ e: OTHER }));
assert.strictEqual(mentions('{"a":"' + OTHER + '"}', needles), false);
});
// ---- erase.js on a throwaway data dir ----
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'erase-iap-'));
const W = (f, o) => fs.writeFileSync(path.join(DIR, f), typeof o === 'string' ? o : JSON.stringify(o));
const Rd = f => JSON.parse(fs.readFileSync(path.join(DIR, f), 'utf8'));
W('updates-log.json', { sends: [{ subject: 'S', recipients: [OTHER, E], delivered: [E] }] });
W('legacy.json', { [E]: { b: 'faucetwave', s: 'e' }, [OTHER]: { b: 'tier1ads', s: 'a' } });
W('events.jsonl', JSON.stringify({ e: E }) + '\n' + JSON.stringify({ e: OTHER }));
W('unrelated.json', { a: OTHER });
// a module that keeps its document in memory and writes it back later (the reason erase works through the live copy)
let live = { rows: { [E]: { email: E, username: 'goneuser' }, [OTHER]: { email: OTHER } }, log: [{ email: E }] }; let saves = 0;
W('lsinbound.json', live);
const owner = { state: () => live, save: () => { saves++; W('lsinbound.json', live); } };
let reloads = 0;
const accts = { [E]: { email: E, username: 'goneuser', code: 'abc1234', address: null, memberId: 0 }, [OTHER]: { email: OTHER, username: 'stay', code: 'zzz9999', sponsorRef: '' },
'walleted@example.test': { email: 'walleted@example.test', username: 'wal', code: 'w1', address: '0x' + '1'.repeat(40), memberId: 0 } };
const accounts = { byEmail: async e => accts[e] || null, positions: async () => [], identities: async () => Object.values(accts),
listByReferrer: async refs => Object.values(accts).filter(a => refs.includes(a.sponsorRef)), removeAccount: async e => { if (!accts[e]) return { error: 'none' }; delete accts[e]; return { ok: true }; } };
const erase = require(path.join(ROOT, 'erase.js'));
let forgot = [];
erase.init({ dataDir: DIR, accounts, docstore: null, owners: { 'lsinbound.json': owner }, reload: { 'legacy.json': () => reloads++ }, forget: [e => forgot.push(e)] });
const before = fs.readFileSync(path.join(DIR, 'updates-log.json'), 'utf8');
await t('dry run (the default) counts and changes nothing', async () => {
const r = await erase.erase(E);
assert.strictEqual(r.dryRun, true); assert.strictEqual(r.found, true); assert.deepStrictEqual(r.blockers, []);
assert.deepStrictEqual(Object.keys(r.docs).sort(), ['events.jsonl', 'legacy.json', 'lsinbound.json', 'updates-log.json']);
assert.strictEqual(fs.readFileSync(path.join(DIR, 'updates-log.json'), 'utf8'), before); assert.ok(live.rows[E], 'live copy untouched');
assert.ok(accts[E]); assert.strictEqual(erase.isErased(E), false); assert.strictEqual(saves, 0);
});
await t('a linked wallet blocks it, force overrides', async () => {
const r = await erase.erase('walleted@example.test', { dryRun: false }); assert.ok(/main wallet/.test(r.error)); assert.ok(accts['walleted@example.test']);
const f = await erase.erase('walleted@example.test', { dryRun: false, force: true }); assert.strictEqual(f.forced, true); assert.ok(!accts['walleted@example.test']);
});
await t('erase: the account, the live copy (saved), plain docs, JSON Lines; reload hook; caches; tombstone; others intact', async () => {
const r = await erase.erase(E, { dryRun: false });
assert.strictEqual(r.ok, true); assert.ok(!accts[E]); assert.ok(accts[OTHER]);
assert.deepStrictEqual(Object.keys(live.rows), [OTHER]); assert.deepStrictEqual(live.log, []); assert.strictEqual(saves, 1);
assert.deepStrictEqual(Rd('lsinbound.json').rows[E], undefined);
assert.deepStrictEqual(Rd('updates-log.json').sends[0], { subject: 'S', recipients: [OTHER], delivered: [] });
assert.deepStrictEqual(Object.keys(Rd('legacy.json')), [OTHER]); assert.strictEqual(reloads, 1);
assert.strictEqual(fs.readFileSync(path.join(DIR, 'events.jsonl'), 'utf8'), JSON.stringify({ e: OTHER }));
assert.deepStrictEqual(r.docResidue, []); assert.deepStrictEqual(forgot.slice(-1), [E]);
assert.strictEqual(erase.isErased(E), true); assert.strictEqual(erase.isErased(OTHER), false);
const log = fs.readFileSync(path.join(DIR, 'erase.json'), 'utf8'); assert.ok(!log.includes(E), 'the erase log keeps no email'); assert.ok(log.includes(erase.hashOf(E).slice(0, 16)));
const again = await erase.erase(E, { dryRun: false }); assert.strictEqual(again.found, false); assert.deepStrictEqual(again.docs, {}, 'a second run finds nothing');
});
await t('hub member.erased: found by the email hash through hubsync.receive, answered 200', async () => {
accts['hubgone@example.test'] = { email: 'hubgone@example.test', username: 'hg', code: 'hg12345', address: null, memberId: 0 };
process.env.HUB_ENABLED = '1'; process.env.HUB_URL = 'http://127.0.0.1:9'; process.env.HUB_SECRET = 's'.repeat(40);
const hubsync = require(path.join(ROOT, 'hubsync.js'));
hubsync.init({ dataDir: DIR, accounts, lsinbound: { receive: async () => ({}) }, erase });
const raw = JSON.stringify({ events: [{ seq: 9001, at: Date.now(), type: 'member.erased', personId: 'h_' + '0'.repeat(16), data: { emailHash: erase.hashOf('HubGone@example.test') } }] });
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', 's'.repeat(40)).update(ts + '\n' + raw).digest('hex');
const r = await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': sig }, raw);
assert.strictEqual(r.status, 200); assert.ok(!accts['hubgone@example.test'], 'erased'); assert.strictEqual(erase.isErased('hubgone@example.test'), true);
const r2 = await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': sig }, raw); assert.strictEqual(r2.status, 200, 'delivered twice is fine');
});
await t('scrub.js is the same file in the sibling checkout (InstantAdPay <-> LinkSpin)', () => {
const sib = [path.join(ROOT, '..', '..', 'linkspin', 'site'), path.join(ROOT, '..', '..', 'onchain-ad-membership', 'site'), path.join(ROOT, '..', 'ls-erase'), path.join(ROOT, '..', 'iap-erase')]
.map(d => path.join(d, 'scrub.js')).find(f => fs.existsSync(f) && path.resolve(f) !== path.resolve(path.join(ROOT, 'scrub.js')));
if (!sib) { console.log(' (sibling scrub.js not found, skipped)'); return; }
const h = f => crypto.createHash('sha1').update(fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n')).digest('hex');
assert.strictEqual(h(path.join(ROOT, 'scrub.js')), h(sib), 'scrub.js differs from ' + sib);
});
console.log(fails ? fails + ' of ' + n + ' FAILED' : 'erase: all ' + n + ' passed');
process.exit(fails ? 1 : 0);
})();
+34
View File
@@ -0,0 +1,34 @@
// The shared network knowledge base in this site's chatbot (2026-11-15): node qa/netkb-merge.test.cjs
// No network: netkb's merged set is set by hand. Checks: this site's entries rank first for a general question, a named site's
// entries rank first when it is named, other sites never take the fast path, the prompt labels them with the site and link,
// a question naming another site skips this site's instant answers (a hand-off still wins), and own() is this site only.
// The SAME file ships in InstantAdPay and LinkSpin.
const fs = require('fs'); const os = require('os'); const path = require('path');
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'netkb-'));
delete process.env.DATABASE_URL; delete process.env.OPENROUTER_API_KEY; process.env.NETKB = '0';
const kb = require('../kb'); const netkb = require('../netkb'); const bot = require('../chatbot');
let pass = 0, fail = 0;
const ok = (c, m) => { if (c) { pass++; console.log('PASS', m); } else { fail++; console.log('FAIL', m); } };
(async () => {
await bot.init({ dataDir: DIR, chain: null });
const self = fs.existsSync(path.join(__dirname, '..', 'tickets.js')) ? 'iap' : 'linkspin';
netkb._set({ version: 'v1', sites: { downlinehydra: { name: 'DownlineHydra', url: 'https://downlinehydra.com' }, [self]: { name: 'Me', url: 'https://me.example' } },
entries: [
{ site: 'downlinehydra', id: 'c-pro', title: 'Pro: what it costs', questions: ['How much is Pro?', 'What do I get with Pro?'], answer: 'Pro is $30 one time.', tags: ['pro', 'price'] },
{ site: 'downlinehydra', id: 'c-withdraw', title: 'Withdrawals', questions: ['How do I withdraw?'], answer: 'Nothing to withdraw on DownlineHydra.', tags: ['withdraw'] },
{ site: self, id: 'c-own', title: 'Own entry from the hub', questions: ['x'], answer: 'never in remote', tags: [] }] });
await kb.load(true);
const top = async q => { const h = await kb.search(q, 8); return h[0] && h[0].entry; };
{ const t = await top('How do I withdraw?'); ok(t && !t.site, 'a general question ranks this site first (' + (t && t.id) + ')'); }
{ const t = await top('How do I withdraw on DownlineHydra?'); ok(t && t.site === 'downlinehydra', 'a named site ranks its own entry first (' + (t && t.id) + ')'); }
ok(!(await kb.search('Own entry from the hub', 8)).some(h => h.entry.site === self), 'this site\'s own copy on the hub is not read back as another site');
{ const b = kb.promptBlock(await kb.context('How much is Pro on DownlineHydra', 6)); ok(/about DownlineHydra, another network site; send people to /.test(b), 'remote entries labelled with site and link'); }
{ const r = await bot.answer('How much is Pro on DownlineHydra?'); ok(!r.canned, 'naming another site skips this site\'s instant answers (' + r.kb + ')'); }
{ const r = await bot.answer('How do I withdraw?'); ok(r.canned, 'this site\'s own question keeps its instant answer'); }
{ const r = await bot.answer('I need a real person, my DownlineHydra pro is missing'); ok(r.handoff === true, 'a hand-off still wins when another site is named'); }
{ const own = await kb.own(); ok(own.length > 10 && own.every(e => !e.site), 'own(): this site\'s entries only (' + own.length + ')'); }
ok(kb.namesOther('what is 5xYourTeam', self).includes('fivex') && !kb.namesOther('what is this site', self).length, 'namesOther finds a network site by name');
for (const e of await kb.own()) ok(!/\bmetamask\b/i.test(e.answer.replace(/never recommend MetaMask/gi, '')), e.id + ': no MetaMask recommendation in a shared answer');
console.log((fail ? 'FAILED ' : 'all network KB checks passed: ') + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });
+185
View File
@@ -0,0 +1,185 @@
// Network sign-in from a partner wallet site (5xYourTeam pattern) through InstantAdPay, with the login ad on its clock (2026-11-15).
// Same file in InstantAdPay and LinkSpin. node qa/networksso-partner.e2e.mjs
// Marty was stranded: 5xYourTeam's "get a position" sent him to sign in through InstantAdPay; IAP answered r=fivex as if LinkSpin
// asked, and after a fresh sign-in the login ad's "Go to dashboard" left him on the IAP dashboard. This boots IAP and LinkSpin on
// throwaway DATA_DIRs plus a stand-in partner (the same networksso.js as a wallet receiver, self 'fivex', on 127.0.0.2: its own
// cookie host) and drives a real browser. Proves:
// A. signed in on IAP (wallet linked): partner /sso/start -> straight back to the partner page with a session, no IAP page, no ad
// B. signed out: partner -> IAP sign-in -> code -> the login ad -> its finish button says Continue -> back on the partner page,
// signed in; the countdown restarted the member's clock (the next ask answers notDue)
// C. the login-ad clock on a plain dashboard load: due -> the gate shows, after the countdown it does not show again on reload
// D. signed in on LinkSpin (wallet linked): partner via=linkspin -> straight back with a session
// No mail key, JSON stores, devCode. Skips when the other repo is not beside this one.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import http from 'node:http';
import { spawn } from 'node:child_process';
import { pathToFileURL } from 'node:url';
import { createRequire } from 'node:module';
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
const peerGuess = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean);
const PEER = peerGuess.find(d => fs.existsSync(path.join(d, 'server.js')));
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
if (!PEER) { console.log('SKIP partner sign-in e2e: the other repo was not found. Set NSSO_PEER_DIR.'); process.exit(0); }
const require = createRequire(import.meta.url);
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
const { ethers } = require(path.join(IAP_DIR, 'node_modules', 'ethers'));
const SECRET = crypto.randomBytes(24).toString('hex');
const IP = Number(process.env.NSSO_IAP_PORT || 8831), LP = IP + 1, PP = IP + 2;
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP, P = 'http://127.0.0.2:' + PP;
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
// an idle keep-alive socket the server closed (5 s default) while the browser launched: the request never reached it, send again
const fetch0 = globalThis.fetch;
const fetch = async (...a) => { for (let i = 0; ; i++) { try { return await fetch0(...a); } catch (e) { if (i >= 3 || !/ECONNRESET|UND_ERR_SOCKET/.test(String((e.cause && (e.cause.code || e.cause.message)) || ''))) throw e; await sleep(300); } } };
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-partner-'));
const logs = { iap: '', ls: '' };
function boot(name, dir, port, extra) {
const data = path.join(TMP, name); fs.mkdirSync(path.join(data, 'uploads'), { recursive: true });
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: data, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DEV_POL_USD: '0.10',
NETWORK_SSO_SECRET: SECRET, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', DOCSTORE_URL: '', LS_SYNC_SECRET: '', HUB_ENABLED: '', FIVEX_URL: P }, extra);
const p = spawn(process.execPath, ['server.js'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env });
p.stdout.on('data', d => logs[name] += d); p.stderr.on('data', d => logs[name] += d); return p;
}
const srvI = boot('iap', IAP_DIR, IP, { LS_URL: LS });
const srvL = boot('ls', LS_DIR, LP, { IAP_URL: IAP });
// the stand-in partner: a wallet receiver exactly like 5xYourTeam (self fivex, asks IAP or LinkSpin, sessions by wallet)
process.env.NETWORK_SSO_SECRET = SECRET;
const N = require(path.join(IAP_DIR, 'networksso.js'));
const PS = new Map(); const sidOf = req => (/(?:^|;\s*)fx\.sid=([a-f0-9]{32})/.exec(req.headers.cookie || '') || [])[1];
N.init({ self: 'fivex', peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: path.join(TMP), defaultPath: '/team',
member: async req => { const s = PS.get(sidOf(req)); return s ? { address: s.address } : null; },
accept: async (e, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
signIn: async (e, req, v) => { const id = crypto.randomBytes(16).toString('hex'); PS.set(id, { address: v.wallet, via: v.iss }); return 'fx.sid=' + id + '; Path=/; HttpOnly; SameSite=Lax'; },
landing: to => to, signinPath: to => '/signin?to=' + encodeURIComponent(to) });
const partner = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://x');
if (await N.handle(req, res, u)) return;
if (u.pathname === '/api/whoami') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(PS.get(sidOf(req)) || {})); }
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>partner</title><p id="pg">' + u.pathname + '</p>');
});
await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); });
let ipN = 30;
const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.8.0.' + (ipN++), 'User-Agent': UA });
const sidFrom = r => ((r.headers.getSetCookie ? r.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid=')) || '').slice('iap.sid='.length);
async function codeSignIn(base, email) {
const h = H();
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
const sid = sidFrom(v); if (!sid) throw new Error('code sign-in failed on ' + base + ': ' + JSON.stringify(sj) + ' ' + v.status);
// members have a username (the dashboard asks for one before anything else)
const un = 'p' + email.split('@')[0].replace(/[^a-z0-9]/g, '').slice(0, 14) + crypto.randomBytes(2).toString('hex');
const pr = await fetch(base + '/api/my/profile', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: JSON.stringify({ username: un }) });
if (!pr.ok) throw new Error('username on ' + base + ': ' + pr.status + ' ' + (await pr.text()).slice(0, 120));
return sid;
}
// link a throwaway wallet to the signed-in account (the dashboard's Link wallet: challenge, personal_sign, verify)
async function linkWallet(base, sid) {
const w = ethers.Wallet.createRandom(); const h = Object.assign(H(), { Cookie: 'iap.sid=' + sid });
const ch = await (await fetch(base + '/api/auth/challenge', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address }) })).json();
const v = await fetch(base + '/api/auth/verify', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address, signature: await w.signMessage(ch.message) }) });
const j = await v.json(); if (j.error) throw new Error('wallet link on ' + base + ': ' + j.error);
return { address: w.address.toLowerCase(), sid: sidFrom(v) || sid };
}
const host = base => new URL(base).hostname;
let browser = null;
async function newCtx(sessions) {
const ctx = await browser.newContext({ userAgent: UA });
const add = Object.entries(sessions || {}).map(([base, sid]) => ({ name: 'iap.sid', value: sid, domain: host(base), path: '/' }));
if (add.length) await ctx.addCookies(add);
return ctx;
}
const whoami = async ctx => (await (await ctx.request.get(P + '/api/whoami')).json());
const mainNavs = page => { const n = []; page.on('framenavigated', f => { if (f === page.mainFrame()) n.push(f.url()); }); return n; };
try {
for (let i = 0; i < 240; i++) { let a = false, b = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} if (a && b) break; if (i === 239) throw new Error('servers not up: iap ' + a + ', linkspin ' + b); await sleep(500); }
browser = await chromium.launch();
// a house login ad on IAP (the admin path), so the gate has something to show
const hc = await fetch(IAP + '/api/admin/campaigns', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer localtest' }, body: JSON.stringify({ type: 'login', name: 'QA login sponsor', targetUrl: 'https://example.com/' }) });
const hj = await hc.json().catch(() => ({}));
ok(hc.ok && !hj.error, 'setup: a house login ad on InstantAdPay', JSON.stringify(hj).slice(0, 160));
// A. signed in on IAP with a wallet: straight back to the partner page with a session, never an IAP page, no login ad
const A = 'partner-a@example.com';
const wa = await linkWallet(IAP, await codeSignIn(IAP, A));
let ctx = await newCtx({ [IAP]: wa.sid }); let page = await ctx.newPage(); let navs = mainNavs(page);
await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?pick=1#buy')); await page.waitForLoadState('domcontentloaded');
let who = await whoami(ctx);
ok(page.url() === P + '/team?pick=1#buy' && who.address === wa.address && who.via === 'iap', 'A. signed in on IAP: back on the partner page signed in as the linked wallet', page.url() + ' ' + JSON.stringify(who));
ok(!navs.some(u => u.startsWith(IAP + '/my')), 'A. no IAP dashboard and no login ad on the way', navs.join(' , '));
ok(/token issued p\*\*\*@example\.com for 5xYourTeam/.test(logs.iap), 'A. IAP logged a token for 5xYourTeam (never "for LinkSpin")');
await ctx.close();
// B. signed out on IAP: sign in there, the login ad shows, its Continue goes back to the partner page
const B = 'partner-b@example.com';
const wb = await linkWallet(IAP, await codeSignIn(IAP, B));
await fetch(IAP + '/api/auth/logout', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + wb.sid }), body: '{}' });
ctx = await newCtx(); page = await ctx.newPage(); navs = mainNavs(page);
await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?pick=2')); await page.waitForSelector('#mcEmail', { timeout: 15000 });
ok(page.url().startsWith(IAP + '/my') && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), 'B. signed out: IAP asks for its sign-in and remembers the trip', page.url());
await page.fill('#mcEmail', B); await page.waitForTimeout(4600); await page.click('#mcSendBtn');
await page.waitForFunction(() => document.getElementById('mcCode') && document.getElementById('mcCode').value.length === 6, null, { timeout: 15000 });
await page.click('#mcVerifyBtn');
await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 });
ok(true, 'B. the login ad shows after the fresh sign-in');
await page.click('#lgOpen');
await page.waitForSelector('#lgContinue:not([hidden])', { timeout: 20000 });
ok((await page.textContent('#lgContinue')).trim() === 'Continue', 'B. its finish button continues the trip (not "Go to dashboard")', await page.textContent('#lgContinue'));
await page.click('#lgContinue');
await page.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 });
who = await whoami(ctx);
ok(page.url() === P + '/team?pick=2' && who.address === wb.address, 'B. back on the partner page it came from, signed in', page.url() + ' ' + JSON.stringify(who));
const again = await (await ctx.request.get(IAP + '/api/ads/slot?type=login')).json();
ok(again.notDue === true && !again.ad, 'B. the countdown restarted the clock: the next ask on IAP is not due', JSON.stringify(again).slice(0, 120));
await ctx.close();
// C. the clock on a plain dashboard load (no sign-in on this page): due -> the gate; after the countdown, a reload shows no gate
const C = 'partner-c@example.com';
const cI = await codeSignIn(IAP, C);
ctx = await newCtx({ [IAP]: cI }); page = await ctx.newPage();
await page.goto(IAP + '/my'); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 });
ok((await page.textContent('#lgContinue')).trim() === 'Go to dashboard', 'C. signed in earlier, first dashboard load: the login ad shows (due), finish says Go to dashboard');
const early = await (await ctx.request.post(IAP + '/api/ads/login/seen')).json();
ok(early.ok === false && early.reason === 'too soon', 'C. telling the server "seen" before the countdown is refused', JSON.stringify(early));
await page.click('#lgOpen', { timeout: 10000 }); await page.waitForSelector('#lgContinue:not([hidden])', { timeout: 20000 }); await page.waitForTimeout(800); await page.click('#lgContinue');
ok(await page.locator('#loginGate').isHidden(), 'C. Go to dashboard closes the gate');
await page.reload(); await page.waitForTimeout(3500);
ok(await page.locator('#loginGate').isHidden(), 'C. a reload inside the setting (3 hours) shows no login ad');
const d2 = await ctx.newPage(); await d2.goto(IAP + '/my'); await d2.waitForTimeout(3000);
ok(await d2.locator('#loginGate').isHidden(), 'C. nor does another tab');
await ctx.close();
// and a reload DURING the countdown does not skip it
const D0 = 'partner-d0@example.com'; const d0 = await codeSignIn(IAP, D0);
ctx = await newCtx({ [IAP]: d0 }); page = await ctx.newPage();
await page.goto(IAP + '/my'); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 }); await page.click('#lgOpen'); await page.waitForTimeout(2000);
await page.reload(); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 });
ok(true, 'C. a reload during the countdown brings the login ad back');
await ctx.close();
// D. signed in on LinkSpin with a wallet: via=linkspin, straight back to the partner
const D = 'partner-d@example.com';
const wd = await linkWallet(LS, await codeSignIn(LS, D));
ctx = await newCtx({ [LS]: wd.sid }); page = await ctx.newPage(); navs = mainNavs(page);
await page.goto(P + '/sso/start?mode=go&via=linkspin&to=' + encodeURIComponent('/team')); await page.waitForLoadState('domcontentloaded');
who = await whoami(ctx);
ok(page.url() === P + '/team' && who.address === wd.address && who.via === 'linkspin', 'D. signed in on LinkSpin: back on the partner page signed in', page.url() + ' ' + JSON.stringify(who));
ok(/token issued p\*\*\*@example\.com for 5xYourTeam/.test(logs.ls), 'D. LinkSpin logged a token for 5xYourTeam');
await ctx.close();
} catch (e) { console.log('FAIL exception', e && e.stack || e, e && e.cause ? 'cause: ' + (e.cause.stack || e.cause) : ''); fails++; }
finally {
try { if (browser) await browser.close(); } catch (e) {}
try { srvI.kill(); } catch (e) {} try { srvL.kill(); } catch (e) {} try { partner.close(); } catch (e) {}
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
}
if (fails) { for (const k of ['iap', 'ls']) console.log('--- ' + k + ' log (tail)\n' + logs[k].split('\n').filter(l => !/rpc eth_call/.test(l)).slice(-30).join('\n')); }
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
+1 -1
View File
@@ -127,7 +127,7 @@ try {
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads' && starts.length === 1, 'signed in nowhere: one bounce, back on the page signed out', starts.length + ' bounce(s), ' + page.url());
ok(await page.locator('#siEmail').isVisible(), 'the normal email-code sign-in shows');
await page.reload(); await page.waitForTimeout(2500);
ok(starts.length === 1, 'reload inside 30 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)');
ok(starts.length === 1, 'reload inside 2 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)');
await page.goto(IAP + '/my'); await page.waitForTimeout(3000);
ok(!(await meOf(ctx, IAP)).signedIn && starts.length === 2 && (await page.locator('#mcEmail').count()) === 1, 'IAP /my signed in nowhere: one bounce, then the normal sign-in', starts.length + ' bounce(s), ' + page.url());
await ctx.close();
+4 -2
View File
@@ -78,14 +78,14 @@ const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/
r = await call(R('/sso/start?to=/my', '', undefined, { 'sec-fetch-dest': 'empty' }));
ok(r.loc === '/my' && !r.set.length, 'a fetch (not a page load) never bounces');
r = await call(R('/sso/start?to=/my', 'nsso.tried=1'));
ok(r.loc === '/my', 'loop guard: a second silent check inside 30 minutes goes straight to the page');
ok(r.loc === '/my', 'loop guard: a second silent check inside 2 minutes goes straight to the page');
r = await call(R('/sso/start?to=/my', 'nsso.off=1'));
ok(r.loc === '/my', 'after a sign-out here: no silent check');
r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1'));
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy&m=go$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
r = await call(R('/sso/start?to=https://evil.example'));
const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1];
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=1800/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 30-minute guard, off-site path replaced', r.loc);
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=120/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 2-minute guard, off-site path replaced', r.loc);
r = await call(R('/sso/start?to=/my', 'sid=tok-a'));
ok(r.loc === '/my' && !r.set.length, 'already signed in here: no bounce');
r = await call(R('/sso/check?st=' + st + '&to=/ads'));
@@ -95,6 +95,8 @@ const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/
r = await call(R('/sso/check?st=' + st + '&to=/ads', 'sid=tok-a'));
const issued = new URL(r.loc).searchParams.get('t');
ok(r.loc.startsWith('https://ls.example/sso/in?t=v1.') && N.verify(issued, { iss: 'iap', aud: 'linkspin', st }).email === 'a@example.com', 'provider, signed in: a token for the other site only, bound to the state');
r = await call(R('/sso/check?st=' + st + '&r=fivex&to=/team', 'sid=tok-a'));
ok(r.loc === '/my' && !/sso\/in/.test(r.loc), 'provider: a site it does not know (r=fivex with no wallets entry) gets nothing, never a token for the peer (2026-11-15)', r.loc);
// receiver: a LinkSpin-issued token arriving here
const mk = (email, to) => N.mint({ iss: 'linkspin', aud: 'iap', email, st, to });
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my#buy'), 'nsso.st=' + st));
+7
View File
@@ -66,16 +66,20 @@ if [ "$MODE" = "public" ]; then
elif [ "$MODE" = "sso" ]; then
node qa/networksso.test.cjs || status=1
node qa/networksso.e2e.mjs || status=1
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
elif [ "$MODE" = "member" ]; then
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; LOCAL=http://127.0.0.1:8796 node qa/member-extra.mjs || status=1; }; stop_local 8796
node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
node qa/tank-hold.mjs || status=1
node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap
node qa/draft-partner.test.mjs || status=1 # 5xYourTeam draft partner routes (DRAFT_E2E_PORT, default 8825)
node qa/walletnudge.test.cjs || status=1
node qa/bixpay.test.cjs || status=1
node qa/profile-policy.test.cjs || status=1
node qa/sov-heroes-store.cjs || status=1
node qa/erase.test.cjs || status=1 # member erase (erase.js + scrub.js, 2026-11-15); qa/erase.mysql.test.cjs needs TEST_DATABASE_URL
elif [ "$MODE" = "draft" ]; then
node qa/draft-partner.test.mjs || status=1
elif [ "$MODE" = "theme" ]; then
@@ -90,12 +94,14 @@ elif [ "$MODE" = "walletnudge" ]; then
node qa/walletnudge.test.cjs || status=1
elif [ "$MODE" = "tankhold" ]; then
node qa/tank-hold.mjs || status=1
node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap
elif [ "$MODE" = "sponsorfollow" ]; then
node qa/sponsorfollow.test.cjs || status=1
node qa/sponsorfollow-e2e.mjs || status=1
elif [ "$MODE" = "kb" ]; then
node qa/kb-retrieval.cjs || status=1
node qa/kb-chat.mjs || status=1
node qa/netkb-merge.test.cjs || status=1 # the shared network knowledge base: home first, a named site first, labels, fast-path skip (2026-11-15)
elif [ "$MODE" = "door" ]; then
node qa/door.mjs || status=1
elif [ "$MODE" = "warpwares" ]; then
@@ -105,6 +111,7 @@ elif [ "$MODE" = "gamepass" ]; then
elif [ "$MODE" = "sov-passes" ]; then
node qa/sov-passes-store.cjs || status=1
node qa/sov-heroes-store.cjs || status=1
node qa/erase.test.cjs || status=1 # member erase (erase.js + scrub.js, 2026-11-15); qa/erase.mysql.test.cjs needs TEST_DATABASE_URL
node qa/sov-passes-local.mjs || status=1
elif [ "$MODE" = "nas" ]; then
node qa/nas-served.mjs || status=1
+186
View File
@@ -0,0 +1,186 @@
// Holding tank batches (tankbatch.js, Marty 2026-11-15). No server: the real tank.js + tankbatch.js with in-memory accounts, a
// fake chain, a fake refuel standing and capturing mail/notice/feed hooks, on a throwaway dir, mocked clock. node qa/tank-batch.test.mjs
// Covers: the ladder (incl. opgnetwerk's real case = 25), switch off = no writes, preview writes nothing, highest tier first by
// rotation, sizes, sign-up grace, self / loop / adopted twice / opted out never dealt, cadence (2 days, top up to size), the
// follow-up (uncontacted back to the tank, not counted), tank.sweep leaves batch picks alone, the 5x draft's separate cap.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createRequire } from 'node:module';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const require = createRequire(path.join(SITE, 'package.json'));
delete process.env.DATABASE_URL;
let fails = 0, passes = 0; const ok = (c, l, x) => { console.log((c ? 'PASS ' : 'FAIL ') + l + (x !== undefined && !c ? ' ' + String(typeof x === 'string' ? x : JSON.stringify(x)).slice(0, 400) : '')); if (c) passes++; else fails++; };
const DAY = 86400000, H = 3600000;
// ---- the ladder, pure ----
const TB0 = require(path.join(SITE, 'tankbatch.js'));
{
const c = Object.assign({}, { base: 10, fueled: 20, twin: 25, step: 5, max: 50, minIap: 2000, minLs: 2500, higherIap: 5000, higherLs: 5000, topIap: 50000, topLs: 50000 });
const t = f => TB0.tierFor(Object.assign({ iapMax: 0, lsMax: 0, refuel: null }, f), c);
ok(t({}).size === 0 && !t({}).level, 'no package: not on the ladder');
ok(t({ iapMax: 1000 }).size === 0, 'a $10 package does not qualify');
ok(t({ iapMax: 2000 }).size === 10 && t({ iapMax: 2000 }).level === 'Paid', '$20 InstantAdPay = Paid 10');
ok(t({ lsMax: 2500 }).size === 10, '$25 LinkSpin = Paid 10');
ok(t({ lsMax: 2000 }).size === 0, '$20 on LinkSpin is below its $25 bar');
ok(t({ iapMax: 5000 }).size === 20 && t({ iapMax: 5000 }).level === 'Fueled', 'a $50 (higher) package = Fueled 20');
ok(t({ iapMax: 2000, refuel: { active: true, streak: 1, both: false } }).size === 20, 'refuel streak active = Fueled 20');
ok(t({ iapMax: 25000 }).size === 20, '$250 is higher, not top: 20');
ok(t({ iapMax: 50000 }).size === 25 && t({ iapMax: 50000 }).level === 'Twin Engine', 'the top package ($500) = 25');
const opg = t({ iapMax: 2000, lsMax: 2500, refuel: { active: true, streak: 1, both: true } });
ok(opg.size === 25 && opg.level === 'Twin Engine', 'opgnetwerk (month 1, both engines 10-27, $20 IAP + $25 LS, nothing above $20) = Twin Engine 25', opg);
ok(t({ iapMax: 2000, refuel: { active: true, streak: 3, both: false } }).size === 30, 'single engine month 3 = 20 + 10 = 30');
ok(t({ iapMax: 2000, lsMax: 2500, refuel: { active: true, streak: 3, both: true } }).size === 35, 'twin month 3 = 25 + 10 = 35');
ok(t({ iapMax: 2000, lsMax: 2500, refuel: { active: true, streak: 12, both: true } }).size === 50, 'capped at 50');
ok(t({ iapMax: 2000, refuel: { active: false, streak: 0, both: false } }).size === 10, 'a lapsed streak counts nothing');
ok(/20/.test(TB0.nextStep(t({ iapMax: 2000 }), { iapMax: 2000 }, c)), 'next step from Paid names 20');
ok(!/income|earn|\$/.test(TB0.ladderView(c).map(r => r.how).join(' ').replace(/\$\d+/g, '')), 'ladder copy promises no income');
}
// ---- the bench ----
function bench(opts) {
for (const m of ['tank.js', 'tankbatch.js']) delete require.cache[require.resolve(path.join(SITE, m))];
const tank = require(path.join(SITE, 'tank.js')); const tb = require(path.join(SITE, 'tankbatch.js'));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankbatch-'));
let now = Date.UTC(2026, 10, 16, 15, 0, 0); const clock = () => now;
const by = new Map(); let n = 100; const pub = a => a ? Object.assign({}, a) : null; const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
const accounts = {
add(email, o) { by.set(email, Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (n++), sponsorRef: '', memberId: 0, address: null, created: now - 5 * DAY, lastSeen: now - 2 * H, joinedVia: 'page', joinedRef: null }, o || {})); },
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); }, async byUsername(u) { return find(a => a.username === String(u || '').toLowerCase()); }, async byCode(c) { return find(a => a.code === String(c || '').toLowerCase()); },
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); }, async setSponsorRef(e, ref) { const a = by.get(e); a.sponsorRef = String(ref || ''); return { ok: true }; },
async listAll() { return [...by.values()].map(pub); }, async positions() { return []; },
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; const t = a.sponsorRef; return find(x => x.username === t || x.code === t || String(x.memberId) === t); }, _by: by };
const events = []; const mails = []; const chats = []; const notices = []; const feeds = []; const toasts = []; const sent = [];
const standing = new Map(); const optOut = new Set();
const messages = { sendChat: async (id, from, to, text) => { chats.push({ from, to, text, at: now }); sent.push({ from, to, at: now }); }, lastFrom: async (f, t) => sent.filter(x => x.from === f && x.to === t).reduce((m, x) => Math.max(m, x.at), 0) };
const mailer = { hasKey: () => true, send: async (to, subject, text) => { mails.push({ to, subject, text }); } };
const chain = { recentEvents: () => events.slice(), getConfig: () => ({}), catalog: async () => [500, 1000, 2000, 5000, 10000, 25000, 50000].map((p, i) => ({ id: i + 1, priceCents: p })) };
const site = Object.assign({ tankBatches: '0' }, opts && opts.site);
tank.init({ dataDir: dir, accounts, chain, messages, mailer, site: 'https://instantadpay.test', capOpen: () => 10,
hooks: { isBatchPick: id => tb.isBatchPick(id), isDraftPick: async () => false } });
tank.setClock(clock);
return { tank, tb, accounts, events, mails, chats, notices, feeds, toasts, standing, optOut, site, dir, messages,
advance: ms => { now += ms; }, now: () => now,
async start() {
await tb.init({ dataDir: dir, db: { enabled: () => false }, accounts, chain, tank, messages, mailer, siteConfig: () => site, clock,
refuel: { standing: async e => standing.get(e) || null },
hooks: { companyId: () => 1, claim: async () => true, excludedPerson: async e => optOut.has(e) ? 'unsubscribed from email' : null,
notify: async (to, subject, text) => { notices.push({ to, subject, text }); }, feed: async (who, what, level) => { feeds.push(who + ' just received ' + what + ' from the holding tank (' + level + ' level)'); }, toast: ev => toasts.push(ev) } });
} };
}
function seed(B, tankCount) {
const { accounts, events, standing } = B;
accounts.add('house@x.co', { username: 'house', memberId: 1, address: '0x' + '0'.repeat(40) });
accounts.add('opg@x.co', { username: 'opgnetwerk', memberId: 2, address: '0x' + '2'.repeat(40) });
accounts.add('fuel@x.co', { username: 'fueler', memberId: 3, address: '0x' + '3'.repeat(40) });
accounts.add('paid@x.co', { username: 'paider', memberId: 4, address: '0x' + '4'.repeat(40) });
accounts.add('sleepy@x.co', { username: 'sleepy', memberId: 5, address: '0x' + '5'.repeat(40), lastSeen: B.now() - 9 * DAY });
accounts.add('free@x.co', { username: 'freebie', memberId: 6, address: '0x' + '6'.repeat(40) });
// opgnetwerk's real purchases: 11 x $20, 2 x $10, 9 x $5 on InstantAdPay
let blk = 1; for (let i = 0; i < 11; i++) events.push({ type: 'Purchase', buyerId: 2, priceCents: 2000, block: blk++ }); for (let i = 0; i < 2; i++) events.push({ type: 'Purchase', buyerId: 2, priceCents: 1000, block: blk++ }); for (let i = 0; i < 9; i++) events.push({ type: 'Purchase', buyerId: 2, priceCents: 500, block: blk++ });
standing.set('opg@x.co', { active: true, streak: 1, both: true, lastDay: '2026-10-27', maxCents: { iap: 2000, linkspin: 2500 } });
events.push({ type: 'Purchase', buyerId: 3, priceCents: 5000, block: blk++ }); // fueler: a $50 package = higher
events.push({ type: 'Purchase', buyerId: 4, priceCents: 2000, block: blk++ }); // paider: $20
events.push({ type: 'Purchase', buyerId: 5, priceCents: 2000, block: blk++ }); // sleepy: paid but away 9 days
events.push({ type: 'Purchase', buyerId: 6, priceCents: 1000, block: blk++ }); // freebie: $10 only
for (let i = 0; i < tankCount; i++) B.accounts.add('t' + String(i).padStart(3, '0') + '@tank.co', { lastSeen: B.now() - (i + 1) * 60000 });
}
// ---- switch off: nothing written, nothing sent; the preview is read-only ----
{
const B = bench(); seed(B, 70); await B.start();
const r = await B.tb.round();
ok(r.on === false, 'switch off: the round does not run');
ok(!B.mails.length && !B.chats.length && !B.feeds.length && !B.toasts.length && !B.notices.length, 'switch off: no mail, chat, feed or toast');
ok(!fs.existsSync(path.join(B.dir, 'tank-batch.json')) && !fs.existsSync(path.join(B.dir, 'tank.json')), 'switch off: no state file written');
const v = await B.tb.myView('opg@x.co'); ok(v.on === false, 'switch off: the member panel is hidden');
const before = JSON.stringify([...B.accounts._by.values()]);
const pv = await B.tb.preview();
ok(pv.readOnly && pv.on === false, 'preview runs with the switch off');
ok(JSON.stringify([...B.accounts._by.values()]) === before && !B.mails.length && !B.chats.length && !fs.existsSync(path.join(B.dir, 'tank-batch.json')) && !fs.existsSync(path.join(B.dir, 'tank.json')), 'preview writes nothing and sends nothing');
const opg = pv.sponsors.find(s => s.name === '@opgnetwerk');
ok(opg && opg.size === 25 && /Twin Engine/.test(opg.level) && opg.wouldGet === 25, 'preview: opgnetwerk at Twin Engine, 25', opg);
ok(pv.sponsors[0].name === '@opgnetwerk', 'preview: highest tier first');
ok((pv.sponsors.find(s => s.name === '@fueler') || {}).size === 20 && (pv.sponsors.find(s => s.name === '@paider') || {}).size === 10, 'preview: fueler 20, paider 10');
ok(!pv.sponsors.some(s => ['@sleepy', '@freebie', '@house'].includes(s.name)), 'preview: inactive, $10-only and the company are not sponsors');
ok(pv.notEligible.members.some(m => m.name === '@sleepy' && /not active/.test(m.reason)), 'preview: the inactive paid member is listed as a near miss');
ok(pv.totals.people === 55 && pv.tank.leftAfterRound === 15, 'preview: 55 dealt, 15 left', pv.totals);
}
// ---- switch on: a live round ----
{
const B = bench({ site: { tankBatches: '1' } }); seed(B, 50); await B.start();
// exclusions: 2 in the sign-up grace, 1 adopted twice, 1 opted out, 1 above a sponsor in their own line (paider's sponsor)
B.accounts.add('new1@tank.co', { created: B.now() - 2 * H }); B.accounts.add('new2@tank.co', { created: B.now() - 20 * H });
B.accounts.add('twice@tank.co'); const tj = B.tank._json.state(); tj.adoptions.push({ id: tj.nextId++, adoptee: 'twice@tank.co', adopter: 'z@x.co', ts: 1, expires: 1, status: 'expired' }, { id: tj.nextId++, adoptee: 'twice@tank.co', adopter: 'y@x.co', ts: 1, expires: 1, status: 'dropped' }); B.tank._json.save();
B.accounts.add('optout@tank.co'); B.optOut.add('optout@tank.co');
B.accounts.add('upline@tank.co', { username: 'uplinez' }); B.accounts._by.get('paid@x.co').sponsorRef = 'uplinez';
const r = await B.tb.round();
const got = e => B.tank._json.state().adoptions.filter(a => a.adopter === e && a.status === 'open').length;
ok(r.on && r.assigned === 51, 'round assigns the whole offered pool (51 open waiting people incl. the upline of paider, 55 places)', r);
ok(got('opg@x.co') === 21 && got('fuel@x.co') === 20 && got('paid@x.co') === 10, 'rotation: paider fills 10, then opg and fueler share the rest one by one, opg first (21 / 20)', [got('opg@x.co'), got('fuel@x.co'), got('paid@x.co')]);
const first = B.tank._json.state().adoptions.filter(a => a.status === 'open')[0];
ok(first && first.adopter === 'opg@x.co', 'the first person goes to the highest tier');
const dealt = new Set(B.tank._json.state().adoptions.filter(a => a.status === 'open').map(a => a.adoptee));
ok(!dealt.has('new1@tank.co') && !dealt.has('new2@tank.co'), 'the 24-hour sign-up grace is respected');
ok(!dealt.has('twice@tank.co'), 'nobody adopted twice already');
ok(!dealt.has('optout@tank.co'), 'an opted-out person is never dealt');
ok(!B.tank._json.state().adoptions.some(a => a.adoptee === 'upline@tank.co' && a.adopter === 'paid@x.co'), 'never a sponsor\'s own upline');
ok(![...dealt].some(e => /@x\.co$/.test(e)), 'never a sponsor themself');
ok(B.accounts._by.get('t000@tank.co').sponsorRef === 'opgnetwerk', 'the sponsor change is written like an adoption');
const adoptMails = B.mails.filter(m => /is now your sponsor on InstantAdPay/.test(m.subject));
ok(adoptMails.length === 51, 'every person gets the normal "X is now your sponsor" email, once', adoptMails.length);
ok(B.chats.length === 51 && B.chats.every(c => /matched with me from the holding tank/.test(c.text)), 'every person gets a chat from their new sponsor');
ok(B.notices.filter(x => /holding tank are in your line/.test(x.subject)).length === 3 && B.mails.filter(m => /from the holding tank are in your line/.test(m.subject)).length === 3, 'each sponsor gets one notice and one email per batch, not one per person');
ok(B.feeds.length === 3 && B.feeds[0] === '@opgnetwerk just received 21 new team members from the holding tank (Twin Engine level)', 'tank feed card: sponsor, count, level', B.feeds);
ok(!B.feeds.some(f => /t0\d\d/.test(f)) && B.toasts.length === 3 && B.toasts.every(t => t.type === 'Adopted' && !/t0\d\d/.test(t.member)), 'feed and toasts never name the people');
ok(!B.mails.concat(B.notices).some(m => /—/.test(m.subject + m.text)), 'no em dash in any batch copy');
// the member's own tank button and the 5x draft keep their own allowances
ok((await B.tank.eligibility('opg@x.co')).ok, 'batch people do not use up the member\'s own tank-button cap');
ok((await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok, '5x draft cap is separate from batches');
const mv = await B.tb.myView('opg@x.co'); ok(mv.on && mv.me.size === 25 && mv.me.open === 21 && /month adds 5/.test(mv.me.next), 'member panel: level, size, open, next step', mv.me);
// cadence: nothing before 2 days; at 2 days only room (size - held) is topped up
const more = n => { for (let i = 0; i < n; i++) B.accounts.add('late' + i + '@tank.co', { created: B.now() - 3 * DAY }); };
more(30);
B.advance(1 * DAY); let r2 = await B.tb.round(); ok(r2.assigned === 0, 'no new batch before 2 days');
B.advance(1 * DAY + H); r2 = await B.tb.round();
ok(got('opg@x.co') === 25 && got('fuel@x.co') === 20 && got('paid@x.co') === 10, 'after 2 days: opg topped up to 25, full sponsors get nothing', [got('opg@x.co'), got('fuel@x.co'), got('paid@x.co')]);
ok(r2.assigned === 4, 'second round dealt 4', r2);
// tank.sweep leaves batch picks to tankbatch (its window ended in the tank's own terms)
for (const a of B.tank._json.state().adoptions) if (a.status === 'open') a.expires = 0; B.tank._json.save();
await B.tank.sweep();
ok(got('opg@x.co') === 25, 'tank.sweep does not close batch adoptions');
// follow-up at 7 days: contacted stay / close, uncontacted go back to the tank as 'unreached' (not counted)
const opgPeople = B.tank._json.state().adoptions.filter(a => a.adopter === 'opg@x.co' && a.status === 'open').map(a => a.adoptee).slice(0, 20);
const [chatted, marked, walletC, activated] = opgPeople;
B.advance(1 * DAY); // now 3 days after the first batch
await B.messages.sendChat(2, 'opg@x.co', chatted, 'hello');
B.tank._json.state().marks[marked] = { sponsor: 'opg@x.co', contacted: B.now(), warned: 0 }; B.tank._json.save();
await B.messages.sendChat(2, 'opg@x.co', walletC, 'hi'); B.accounts._by.get(walletC).address = '0x' + 'a'.repeat(40);
B.accounts._by.get(activated).memberId = 900;
B.advance(2 * DAY); let f = await B.tb.followUp(); ok(f.done === 1 && f.unreached === 0, 'before 7 days only the activated one closes (done)', f);
B.advance(2 * DAY + H); f = await B.tb.followUp();
ok(f.unreached === 47 && f.done === 1 && f.returned === 2, 'at 7 days (first batch only): 47 never contacted go back, contacted+wallet done, 2 contacted without wallet back (counted); the 2-day-old top-up waits', f);
ok(B.accounts._by.get(opgPeople[5]).sponsorRef === '' && (B.tank._json.state().adoptions.find(a => a.adoptee === opgPeople[5] && a.adopter === 'opg@x.co') || {}).status === 'unreached', 'an uncontacted person is back in the tank, status unreached');
ok((await B.tank.countAll(opgPeople[5])) === 0, 'unreached does not count toward their two adoptions');
ok((await B.tank.countAll(chatted)) === 1, 'a contacted, unconverted return still counts');
ok(B.notices.some(x => x.to === 'opg@x.co' && /went back to the tank/.test(x.subject)), 'the sponsor is told once who went back');
}
// ---- the 5x draft cap counts draft picks only ----
{
const B = bench({ site: { tankBatches: '1' } }); seed(B, 15); await B.start();
let draftIds = new Set();
B.tank.init({ dataDir: B.dir, accounts: B.accounts, chain: { recentEvents: () => B.events.slice(), getConfig: () => ({}) }, messages: B.messages, mailer: { hasKey: () => false }, capOpen: () => 10, hooks: { isDraftPick: async id => draftIds.has(id), isBatchPick: id => B.tb.isBatchPick(id) } });
for (let i = 0; i < 10; i++) { const r = await B.tank.adopt('opg@x.co', 't' + String(i).padStart(3, '0') + '@tank.co'); if (r.ok) draftIds.add(r.adoption.id); }
ok(draftIds.size === 10, 'ten plain adoptions');
draftIds = new Set(); // they were plain: the draft has 0 of its own
ok((await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok, 'ten plain adoptions do not fill the draft cap');
ok(!(await B.tank.eligibility('opg@x.co')).ok, 'and they do fill the plain tank-button cap');
const ids = B.tank._json.state().adoptions.filter(a => a.status === 'open').map(a => a.id); draftIds = new Set(ids);
ok(!(await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok && (await B.tank.eligibility('opg@x.co')).ok, 'ten draft picks fill the draft cap only');
}
console.log('\n' + passes + ' passed, ' + fails + ' failed'); process.exit(fails ? 1 : 0);
+1 -1
View File
@@ -305,4 +305,4 @@ function resetConversions(kinds) {
return { cleared: n };
}
module.exports = { init, tick, stats, resetConversions, PACKS, compose };
module.exports = { init, tick, stats, resetConversions, PACKS, compose, _state: () => S, _save: save }; // _state/_save: the member erase (erase.js)
+17 -1
View File
@@ -404,6 +404,22 @@ async function setGoal(email, goal) {
}
function badgesOf(email) { return getRec(String(email || '').toLowerCase()).then(r => (r && cfg().on) ? Object.keys(r.badges || {}) : []).catch(() => []); }
// ---- one member's standing, read-only (holding tank batches, tankbatch.js 2026-11-15) ---------------------------------
// streak + both engines this cycle (a settled COPY: a passed grace reads as it will be stored), and the biggest package of each
// site the streak has seen (refuels and Pit Stops keep cents; LinkSpin packages reach InstantAdPay only through this record)
async function standing(email, now) {
email = String(email || '').toLowerCase(); if (!email) return null;
const rec0 = await getRec(email); if (!rec0) return null;
const rec = JSON.parse(JSON.stringify(rec0)); settle(rec, ctDay(now || Date.now()));
const max = { iap: 0, linkspin: 0 };
for (const cy of [rec.cycle].concat(rec.history || [])) {
if (!cy) continue;
for (const grp of [cy.sites || {}, cy.pit || {}]) for (const s of ['iap', 'linkspin']) if (grp[s]) max[s] = Math.max(max[s], Number(grp[s].cents) || 0);
}
return { active: !!rec.active && (rec.streak || 0) >= 1, streak: rec.active ? (rec.streak || 0) : 0, both: !!(rec.active && rec.cycle && rec.cycle.both),
lastDay: rec.lastDay || null, dueDay: rec.dueDay || null, maxCents: max };
}
// ---- admin ------------------------------------------------------------------------------------------
async function stats() {
const c = cfg(); const recs = await allRecs(); const rows = await outRows();
@@ -414,5 +430,5 @@ async function stats() {
recent: rows.slice(0, 40).map(r => ({ ref: r.ref, site: r.site, email: r.email, kind: r.kind === 'grant' ? r.payload.kind : 'reminder:' + r.payload.remind, credits: r.payload.credits || 0, status: r.status, at: r.created })) };
}
module.exports = { setGoal, init, cfg, record, roundup, weekOf, feedLine, onIapPurchase, decide, settle, blank, view, streakLine, badgesOf, outbox, ack, drainLocal, tick, stats, reminderCopy,
module.exports = { standing, setGoal, init, cfg, record, roundup, weekOf, feedLine, onIapPurchase, decide, settle, blank, view, streakLine, badgesOf, outbox, ack, drainLocal, tick, stats, reminderCopy,
_days: { ctDay, addDays, diffDays, label, ctHour }, SINGLE, BOTH };
+1 -1
View File
@@ -65,7 +65,7 @@ function renderPage() {
h += '<h2 style="font-size:24px;margin:10px 0 16px">Release notes</h2>';
h += v.notes.length ? v.notes.map(n => '<article class="note" id="' + esc(n.id) + '"><h2>' + esc(n.title) + n.tags.map(tagChip).join('') + '</h2><p class="when">' + fmt(n.date) + '</p>' + bodyHtml(n.body) + '</article>').join('') : '<p class="muted">No notes yet.</p>';
h += '<p class="muted small" style="margin-top:30px">Suggestions and bug reports: the chat bubble on any page, or the InstantAdPay Telegram group.</p>';
h += '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
h += '</div><script src="/assets/common.js?v=20261115nr"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
return h;
}
module.exports = { init, notes, roadmap, saveNote, saveRoadmap, remove, publicView, renderPage, bodyHtml, TAGS, STATUSES };
+61
View File
@@ -0,0 +1,61 @@
// Member erase helper (Marty 2026-11-15, ticket LS-1021): take one person out of a data document without touching anyone
// else's entries. The SAME file ships in InstantAdPay and LinkSpin (qa/erase.test.cjs checks the copies match).
//
// needles = { emails: [...], exact: [...] }: an email matches anywhere inside a string at word edges ("x|a@b.com|y",
// "tankpay1:a@b.com:17"); an exact needle (username, referral code, hub id) only matches a whole string or key, so a short
// username never eats unrelated text. Rules, applied from the top of the document down:
// - a key that matches is deleted with everything under it (byEmail[a@b.com], hashes[a@b.com], own[..][a@b.com])
// - an array item that is a matching string, or an object with a matching field (other than a pointer, below), is removed
// - in a map, a record that is THEIRS (its email / owner / adoptee / username ... field matches) is removed whole
// (clicks {owner}, refill records {owner}, rows {email})
// - in another member's record, a field that only POINTS at them (sponsorEmail, prevEmail, adopter, ...) is set to null
// - any other matching string value in a map is deleted with its key (byCode[code] = email)
// - anything else is walked into. Numbers, booleans and other people's records stay as they were.
// Returns how many keys / items / records / fields were removed or blanked (0 = nothing about them in it).
'use strict';
const esc = s => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
function matcher(needles) {
const emails = [...new Set(((needles && needles.emails) || []).map(e => String(e || '').trim().toLowerCase()).filter(e => e.includes('@')))];
const exact = new Set(((needles && needles.exact) || []).map(x => String(x || '').trim().toLowerCase()).filter(x => x.length >= 3));
const re = emails.length ? new RegExp('(^|[^a-z0-9._%+-])(' + emails.map(esc).join('|') + ')(?![a-z0-9-]|\\.[a-z0-9])', 'i') : null;
const hit = s => { if (typeof s !== 'string' || !s) return false; const l = s.trim().toLowerCase(); return exact.has(l) || (re ? re.test(s) : false); };
const inText = s => { if (!s) return false; if (re && re.test(s)) return true; for (const x of exact) if (s.toLowerCase().includes('"' + x + '"')) return true; return false; };
return { hit, inText, empty: !emails.length && !exact.size };
}
const isObj = v => v && typeof v === 'object' && !Array.isArray(v);
const OWN = new Set(['email', 'owner', 'owneremail', 'adoptee', 'member', 'memberemail', 'user', 'username', 'account', 'lead', 'person', 'recipient', 'e', 'u']);
const REF = new Set(['sponsoremail', 'prevemail', 'previousemail', 'adopter', 'adopteremail', 'sponsor', 'from', 'to', 'by', 'inviter', 'referrer', 'mentor', 'coach']);
const otherHit = (v, m) => isObj(v) && Object.entries(v).some(([k, x]) => typeof x === 'string' && !REF.has(k.toLowerCase()) && m.hit(x)); // not just a pointer
const ownHit = (v, m) => isObj(v) && Object.entries(v).some(([k, x]) => typeof x === 'string' && OWN.has(k.toLowerCase()) && m.hit(x));
function scrubDeep(node, needles, m0) {
const m = m0 || matcher(needles); if (m.empty) return 0;
let n = 0;
if (Array.isArray(node)) {
for (let i = node.length - 1; i >= 0; i--) {
const v = node[i];
if ((typeof v === 'string' && m.hit(v)) || otherHit(v, m)) { node.splice(i, 1); n++; } // their item / a log line about them
else if (v && typeof v === 'object') n += scrubDeep(v, null, m);
}
} else if (isObj(node)) {
for (const k of Object.keys(node)) {
const v = node[k];
if (m.hit(k) || ownHit(v, m)) { delete node[k]; n++; continue; }
if (typeof v === 'string' && m.hit(v)) { if (REF.has(k.toLowerCase())) node[k] = null; else delete node[k]; n++; continue; }
if (v && typeof v === 'object') n += scrubDeep(v, null, m);
}
}
return n;
}
// a whole document as text: JSON is parsed, scrubbed and written back; JSON Lines lose every line that mentions them.
// Returns { body, removed } (body unchanged and removed 0 when nothing matched).
function scrubText(body, needles, isLines) {
const m = matcher(needles); if (m.empty || !m.inText(body)) return { body, removed: 0 };
if (isLines) { const lines = String(body).split('\n'); const keep = lines.filter(l => !m.inText(l)); return { body: keep.join('\n'), removed: lines.length - keep.length }; }
const obj = JSON.parse(body); const removed = scrubDeep(obj, null, m);
return { body: removed ? JSON.stringify(obj) : body, removed };
}
const mentions = (body, needles) => matcher(needles).inText(String(body || ''));
module.exports = { scrubDeep, scrubText, mentions, matcher };
+56 -8
View File
@@ -55,7 +55,10 @@ const lssync = require('./lssync');
const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23)
const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07)
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
const tankbatch = require('./tankbatch'); // holding tank batches (2026-11-15): switch tankBatches, default off
const draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET)
const loginClock = require('./loginadclock'); // login ads on a clock, not only at sign-in (Marty 2026-11-15): see loginadclock.js
const erase = require('./erase'); // member erase (2026-11-15, LS-1021): POST /api/admin/erase + the hub's member.erased event
const hubsync = require('./hubsync'); // network hub: members from other doors arrive as waiting accounts, ours are reported (2026-11-12, only with HUB_ENABLED)
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22)
const bixpay = require('./bixpay'); // BixPay Visa card: partner-link field, sponsor-follows resolver, tracked clicks (2026-10-29, gated by site config bixpayLive)
@@ -64,6 +67,7 @@ const LS_BASE = () => String(process.env.LS_URL || 'https://linkspin.app').repla
const BL_BASE = () => String(process.env.BL_URL || 'https://downlinebanners.com').replace(/\/+$/, ''); // Downline Banners (network sign-in by wallet, 2026-11-13)
const VBB_BASE = () => String(process.env.VBB_URL || 'https://viralbannerblitz.com').replace(/\/+$/, ''); // Viral Banner Blitz (network sign-in by wallet, 2026-11-14)
const VAB_BASE = () => String(process.env.VAB_URL || 'https://viraladblitz.com').replace(/\/+$/, ''); // ViralAdBlitz (network sign-in by wallet, 2026-11-15; VAB_URL = the staging host until the domain switch)
const FIVEX_BASE = () => String(process.env.FIVEX_URL || 'https://5xyourteam.com').replace(/\/+$/, ''); // 5xYourTeam (network sign-in by wallet, 2026-11-15: it asked with r=fivex and was answered as LinkSpin)
const DH_BASE = () => String(process.env.DH_URL || 'https://downlinehydra.com').replace(/\/+$/, ''); // DownlineHydra (network sign-in, 2026-11-15; DH_URL = https://dh.saasy.top until the domain switch)
// Refuel spots (Marty 2026-11-13: paid from the company fee share, $50+): refuel.js calls this once per counted $50+ refuel tx
// (either site). Downline Banners buys the spot for the member's main wallet from the engine wallet (its refuelspots.js), with
@@ -610,7 +614,7 @@ async function boot() {
// only (the admin portal is never shared); an account that is not here yet, or is still a waiting LinkSpin/BTC4Hits account,
// gets the normal email-code sign-in with the email filled in, so every new-account check (anti-fraud, sponsor) runs as before.
networksso.init({ self: 'iap', peer: 'linkspin', peerBase: LS_BASE, isProd: IS_PROD, dataDir: DATA_DIR, db, defaultPath: '/my',
wallets: { bannerline: BL_BASE, vbb: VBB_BASE, viraladblitz: VAB_BASE, downlinehydra: DH_BASE }, // Downline Banners members are wallets: vouch for the wallet they signed in with, else the account's linked one
wallets: { bannerline: BL_BASE, vbb: VBB_BASE, viraladblitz: VAB_BASE, downlinehydra: DH_BASE, fivex: FIVEX_BASE }, // Downline Banners members are wallets: vouch for the wallet they signed in with, else the account's linked one
wallet: async s => { const a = await accounts.byEmail(s.email); const addr = String(s.address || (a && a.address) || '').toLowerCase(); return addr ? { address: addr, name: (a && a.username) || '' } : null; },
member: async req => { // a wallet sign-in carries the address, not the email: find the account that owns the wallet (2026-11-13)
const s = await auth.fromRequest(req); if (!s) return null;
@@ -634,6 +638,7 @@ async function boot() {
signinPath: to => { const x = new URL(to, 'http://x'); return x.pathname === '/my' ? '/my' + x.hash : '/my'; } });
accounts.init({ dataDir: DATA_DIR });
ads.init({ dataDir: DATA_DIR, chain, tiers: () => geo.tierLists(siteConfig()) });
loginClock.init({ url: process.env.DATABASE_URL || process.env.DOCSTORE_URL, hours: () => siteConfig().loginAdEveryHours });
mailer.init({ dataDir: DATA_DIR });
messages.init({ dataDir: DATA_DIR });
reports.init({ dataDir: DATA_DIR });
@@ -738,6 +743,7 @@ async function boot() {
networkHeld: hubsync.enabled() ? accts => hubsync.heldAmong(accts) : null, networkLocked: hubsync.enabled() ? email => hubsync.lockedAnywhere(email) : null,
isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em),
isDraftPick: id => draftpartner.isDraftPick(id), // a 5xYourTeam pick's adoption: draftpartner.js owns its 3-day window
isBatchPick: id => tankbatch.isBatchPick(id), // a holding tank batch adoption: tankbatch.js owns its follow-up window
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text),
// switch-on-payouts reminders after an assignment (2026-10-27): one send per key across both app copies (deploy overlap),
@@ -746,12 +752,20 @@ async function boot() {
notify: async (email, subject, text) => { const html = '<p>' + String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/(https:\/\/[^\s)]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [email], subject, html, 'notice'); } } });
// LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest
lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email));
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore });
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore, erased: email => erase.isErased(email) });
// member erase (erase.js): the modules that keep a document in memory are scrubbed through their live copy, the rest through docstore
erase.init({ dataDir: DATA_DIR, accounts, docstore,
owners: { 'lsinbound.json': { state: lsinbound._state, save: lsinbound._save }, 'lssync.json': { state: lssync._state, save: lssync._save },
'sponsorfollow.json': { state: followStore._state, save: followStore._save }, 'refill.json': { state: refill._state, save: refill._save },
'tank-ready.json': tank._ready, ...(db.enabled() ? {} : { 'tank.json': tank._json }),
...(hubsync.enabled() ? { 'hubsync.json': { state: hubsync._state, save: hubsync._save } } : {}) },
reload: { 'legacy.json': () => legacy.reload(), 'legacy-grants.json': () => legacy.reload() },
forget: [email => loginClock.forget(String(email || '').toLowerCase()), email => lssync._forget(email), email => { if (hubsync.enabled()) hubsync._forgetHeld(email); }] });
// network hub (hubsync.js): nothing at all happens here unless HUB_ENABLED is on; the LinkSpin sync above runs either way
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain, erase }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
// 5xYourTeam draft picks (draftpartner.js, 2026-11-15): the routes answer 503 until DRAFT_PARTNER_SECRET is set; the pool stays empty
// and nobody can be drafted while the hub is off (DRAFT_ALLOW_NO_HUB=1 is for local tests only, refused in production)
await draftpartner.init({ dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
await draftpartner.init({ maxOpen: () => siteConfig().fiveXDraftCap, dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
hooks: { hubInfo: email => (hubsync.enabled() ? hubsync.hubInfo(email) : null), resolvePerson: q => (hubsync.enabled() ? hubsync.resolvePerson(q) : null), networkOn: () => hubsync.enabled(),
excluded: em => fraud.excluded(em), spamEmails: () => (((spamscan.view() || {}).last || {}).candidates || []).map(c => c.email), suggestDomain: d => require('./emailcheck').suggestDomain(d) } }).catch(e => console.error('draftpartner init', e.message));
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
@@ -835,6 +849,15 @@ async function boot() {
geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message));
setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily
setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window
// holding tank batches (tankbatch.js, 2026-11-15): hourly follow-up + a round while tankBatches is on; the feed card goes where the other sale cards go
{ let spamC = { at: 0, set: new Set() }; const spamSet = () => { if (Date.now() - spamC.at > 60000) { try { spamC = { at: Date.now(), set: new Set((((spamscan.view() || {}).last || {}).candidates || []).map(c => String(c.email || '').toLowerCase())) }; } catch (e) { spamC = { at: Date.now(), set: new Set() }; } } return spamC.set; };
await tankbatch.init({ dataDir: DATA_DIR, db, accounts, chain, tank, refuel, messages, mailer, siteConfig,
hooks: { excluded: em => fraud.excluded(em), companyId: () => Number(siteConfig().defaultSponsorId) || 1, claim: key => marks.claim(key), toast: ev => pushFeed(ev),
excludedPerson: async em => { if (spamSet().has(em)) return 'spam scan'; const d = String(em).split('@')[1] || ''; const fix = require('./emailcheck').suggestDomain(d); if (fix && fix !== d) return 'mistyped email domain'; if (erase.isErased(em)) return 'erased'; if (await drip.isUnsubscribed(em).catch(() => false)) return 'unsubscribed from email'; return null; },
notify: async (email, subject, text) => { const html = '<p>' + String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/(https:\/\/[^\s)]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [email], subject, html, 'notice'); },
feed: async (who, what, level) => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; const clean = t => String(t || '').replace(/[<>&]/g, ''); await telegramSend(sc.telegramEchoChatId, '\u{1F91D} <b>InstantAdPay</b> · <b>' + clean(who) + '</b> just received ' + clean(what) + ' from the holding tank (' + clean(level) + ' level)', sc.telegramEchoTopicId); } } }).catch(e => console.error('tankbatch init', e.message)); }
setTimeout(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 4 * 60 * 1000); // past the deploy overlap window
setInterval(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 60 * 60 * 1000);
setInterval(() => draftpartner.sweep().then(r => { if (r.done || r.returned || r.kept || r.moved) console.log('draft sweep', JSON.stringify(r)); }).catch(e => console.error('draft sweep', e.message)), 60 * 60 * 1000); // 5xYourTeam picks: 3-day window
burner.init({ chain, ads, accounts });
setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000);
@@ -907,7 +930,10 @@ function siteConfig() {
memberWeeklyEmail: '0', // 1 = the weekly 'Your week on InstantAdPay' email goes to every active member, not only sponsors with a line
noPayoutIds: '25', // positions kept for linkage only (compromised wallets): no buys signed from them, no new joins routed under them or their upline chain (Marty, 2026-09-14)
leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover)
loginAdEveryHours: 3, // login ad: shown again on the next member page once the last finished view is this many hours old (Marty 2026-11-15)
tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11
fiveXDraftCap: 10, // 5xYourTeam draft: open picks one coach may hold, its own cap (Marty 2026-11-15), never shared with tankAdoptCap or batches
...tankbatch.DEFAULTS, // holding tank batches (tankbatch.js, Marty 2026-11-15): master switch tankBatches '0'; every number of the ladder, cadence and follow-up
legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand>
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
@@ -947,7 +973,7 @@ const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': '
'.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp',
'.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2',
'.gif': 'image/gif', '.webm': 'video/webm', '.vtt': 'text/vtt; charset=utf-8', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' };
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' 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 https://linkspin.app https://downlinebanners.com https://viralbannerblitz.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:";
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' 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 https://linkspin.app https://downlinebanners.com https://viralbannerblitz.com https://viraladblitz.com https://downlinehydra.com https://5xyourteam.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:";
function baseHeaders(extra) {
return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {});
@@ -3072,7 +3098,7 @@ const server = http.createServer(async (req, res) => {
if (tankHold) sponsorBlocked = 'tankHold';
else if (!sponsorId && memberId !== _defSpon) { sponsorId = _defSpon; sponsorFallback = true; } // orphan fallback → #1 (never self-sponsor)
if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {});
const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['turkeydrop', 'polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'polminer', 'warpwares', 'shardsofvalor', 'forum'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : (networksso.pendingBack(req) ? 'nsso' : null), sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
const out = { signedIn: true, nssoBack: networksso.pendingBack(req), gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['turkeydrop', 'polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'polminer', 'warpwares', 'shardsofvalor', 'forum'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : (networksso.pendingBack(req) ? 'nsso' : null), sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
address: s.address || (acct && acct.address) || null, memberId,
username: (acct && acct.username) || null, theme: (acct && acct.theme) || null,
inviteAsk: !memberId && acct ? tank.inviteAsk(acct) : null, // the Who invited you card (2026-11-07)
@@ -3348,6 +3374,13 @@ const server = http.createServer(async (req, res) => {
spamscan.setAllow(e, !b.remove); console.log('spamscan allowlist', b.remove ? 'removed' : 'added', e);
return json(res, 200, spamscan.view());
}
// member erase (2026-11-15, ticket LS-1021): {email, dryRun (default true; only dryRun: false erases), force, names}. erase.js
if (p === '/api/admin/erase' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const r = await erase.erase(String(b.email || ''), { dryRun: b.dryRun !== false, force: b.force === true, by: 'admin', names: b.names });
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/erase' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, erase.view()); }
if (p === '/api/admin/member' && req.method === 'DELETE') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const e = String(u.searchParams.get('email') || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e);
@@ -3551,6 +3584,7 @@ const server = http.createServer(async (req, res) => {
for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i;
return json(res, 200, { suggest: pick });
}
if (p === '/api/my/tank/feed' && req.method === 'GET') { const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); return json(res, 200, await tankbatch.myView(s.email)); } // How to get fed leads (off with tankBatches)
if (p === '/api/my/tank' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
@@ -3847,6 +3881,8 @@ const server = http.createServer(async (req, res) => {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await draftpartner.adminView());
}
if (p === '/api/admin/tank/batches/preview' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.preview()); } // read-only: no writes, no mail
if (p === '/api/admin/tank/batches' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.adminView()); }
if (p === '/api/admin/tank' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await tank.adminView());
@@ -5519,10 +5555,22 @@ const server = http.createServer(async (req, res) => {
// -- ad engine (spec §8b v1: banners, text, login ads)
if (p === '/api/ads/slot' && req.method === 'GET') {
const t = String(u.searchParams.get('type') || 'banner');
if (t === 'login') return json(res, 200, { ad: await loginAdFor(req, 'dashboard') });
if (t === 'login') { // on the member's clock (loginadclock.js); back = a network sign-in hop to finish when the countdown ends (2026-11-15)
const s = await auth.fromRequest(req).catch(() => null); const lk = loginClock.keyOf(s);
const back = networksso.pendingBack(req) ? '/sso/resume' : null;
if (lk && !(await loginClock.due(lk))) return json(res, 200, { ad: null, notDue: true, back });
const ad = await loginAdFor(req, 'dashboard');
if (ad && lk) await loginClock.served(lk);
return json(res, 200, { ad, back });
}
const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req)));
return json(res, 200, { ad });
}
if (p === '/api/ads/login/seen' && req.method === 'POST') { // the login-ad countdown ended: restart this member's clock
const s = await auth.fromRequest(req).catch(() => null); const k = loginClock.keyOf(s);
if (!k) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await loginClock.seen(k, ads.rates().loginDwellSeconds || 10));
}
m = /^\/api\/ads\/click\/(\d+)$/.exec(p);
if (m && req.method === 'GET') {
// an advertiser opening their own ad's link (from Campaigns, a preview, a test) is not a click: relay it uncounted (Marty, 2026-09-30)
@@ -6322,7 +6370,7 @@ const server = http.createServer(async (req, res) => {
+ '<style>.bp{max-width:560px;text-align:center;padding:40px 16px 60px}.bp img{width:100%;max-width:520px;border-radius:18px;border:1px solid var(--line);box-shadow:0 20px 60px rgba(0,0,0,.45)}.bp h1{font-size:clamp(24px,5vw,34px);margin:22px 0 8px}.bp p{color:var(--muted);max-width:44ch;margin:0 auto 20px}</style></head>'
+ '<body><div class="wrap bp"><img src="' + img + '" alt="' + esc(label) + ' badge for @' + esc(un) + '"><h1>@' + esc(un) + ' unlocked <em>' + label + '</em></h1><p>' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On InstantAdPay every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.</p>'
+ '<a class="btn" href="/join/' + esc(un) + '">Join @' + esc(un) + '\u2019s line free</a><p class="small" style="margin-top:26px">Advertising with a performance referral program. Not an investment; no income is guaranteed.</p></div>'
+ '<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
+ '<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }));
return res.end(html);
}
+1 -1
View File
@@ -134,7 +134,7 @@ function create(opts) {
setPeer(proto) { const s = load(); if (s.peer.proto !== proto) { s.peer.proto = proto; s.peer.at = Date.now(); save(); } },
peerProto() { return Number(load().peer.proto) || 1; },
view() { const s = load(); return { records: Object.keys(s.prov).length, remoteTank: Object.keys(s.remote).length, pending: Object.keys(s.pending).length, peerProto: Number(s.peer.proto) || 1, recent: s.log.slice(-40).reverse() }; },
_state: load, _reset() { st = null; }
_state: load, _save: save, _reset() { st = null; } // _state/_save: the member erase (erase.js) scrubs the live copy
};
return api;
}
+33 -11
View File
@@ -17,13 +17,19 @@ const db = require('./db');
const CAP_DEFAULT = 10; let capFn = () => CAP_DEFAULT;
const capOpen = () => { const n = Math.round(Number(capFn())); return n >= 1 && n <= 50 ? n : CAP_DEFAULT; };
async function holding(open) { const out = []; for (const ad of open || []) { const a = await accounts.byEmail(ad.adoptee); if (!(a && Number(a.memberId) > 0)) out.push(ad); } return out; }
// each allowance counts only its own people (Marty 2026-11-15: "5x your team's draft is a different thing altogether"): the member's own
// tank button and the 24-hour safety net count plain adoptions; a 5xYourTeam draft pick counts only against the draft's cap; a holding
// tank batch (tankbatch.js) only against the batch size. A hook that throws counts the adoption as plain (the conservative side).
const pickKind = async id => { try { if (hooks.isDraftPick && await hooks.isDraftPick(id)) return 'draft'; if (hooks.isBatchPick && await hooks.isBatchPick(id)) return 'batch'; } catch (e) {} return 'plain'; };
async function holdingOf(open, kind) { const out = []; for (const ad of await holding(open)) if (await pickKind(ad.id) === kind) out.push(ad); return out; }
const TTL_MS = 7 * 86400000; // an adoption's window to convert
const MAX_ADOPTIONS = 2; // per adoptee, lifetime (dropped adoptions count too, since 2026-09-13)
const HOLD_MS = 3 * 24 * 3600 * 1000; // an adoption is a commitment: no releasing someone you picked up less than 3 days ago (Marty, 2026-09-13)
// statuses that do not count toward a person's two adoptions: a release record, and the later side of a network race
// (both sites adopted the same person within minutes; the earlier adoption won on both, sponsorfollow.js), and a record of a
// member naming who invited them (nobody adopted them; nameSponsor below)
const NOT_COUNTED = ['released', 'conflict', 'invited'];
// 'unreached' (2026-11-15): a holding tank batch person the sponsor never contacted, back in the tank; the sponsor's miss, not theirs
const NOT_COUNTED = ['released', 'conflict', 'invited', 'unreached'];
const MIN_OWN_BUY_CENTS = 2000; // adopter must have bought a $20+ package themselves
const WARN_DAYS = 10; // dormant lead: sponsor warned after this many days without contact
const RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old)
@@ -57,10 +63,10 @@ const D = {
const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'");
return rows.map(rowA);
},
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n); },
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited','unreached')", [adoptee]); return Number(r[0].n); },
async setStatus(id, status) { await db.q('UPDATE adoptions SET status=?, closed=? WHERE id=?', [status, Date.now(), Number(id)]); },
async recent(n) { return (await db.q('SELECT * FROM adoptions ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowA); },
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n) > 0; },
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited','unreached')", [adoptee]); return Number(r[0].n) > 0; },
async all() { return (await db.q('SELECT * FROM adoptions ORDER BY id')).map(rowA); },
async mark(lead) { const r = await db.q('SELECT * FROM lead_marks WHERE `lead`=?', [lead]); return r[0] ? { sponsor: r[0].sponsor, contacted: Number(r[0].contacted_ts || 0), warned: Number(r[0].warned_ts || 0) } : null; },
async setMark(lead, f) {
@@ -135,7 +141,7 @@ async function eligibility(email) {
if (!a) return { ok: false, reason: 'Sign in first.' };
if (!a.memberId) return { ok: false, reason: 'Switch on payouts and buy your first $20 package to adopt from the tank.' };
if (!hasOwnBuy(a.memberId)) return { ok: false, reason: 'Buy your own $20 or more package first. Adopting is for members who have made that move themselves.' };
const open = await impl().open(a.email); const held = await holding(open); const cap = capOpen();
const open = await impl().open(a.email); const held = await holdingOf(open, 'plain'); const cap = capOpen();
if (held.length >= cap) return { ok: false, reason: 'You are already helping ' + held.length + ' people from the holding tank, and ' + cap + ' at one time is the most anyone can hold. A slot opens when one of them switches on payouts, or when their 7-day window ends.', full: true, cap, held: held.length };
return { ok: true, account: a, open };
}
@@ -154,11 +160,25 @@ async function partnerEligibility(email, p) {
const payee = await firstOnContract(a);
if (!payee) return { ok: false, code: 'no_contract_line', reason: 'Neither you nor anyone above you has switched on payouts on InstantAdPay, so a pick who starts there would land under the company. Switch on payouts on InstantAdPay first (one free transaction).' };
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { ok: false, code: 'payout_blocked', reason: 'Your line cannot take new members right now.' };
const open = await impl().open(a.email); const held = await holding(open); const cap = Math.min(capOpen(), Number(p.maxOpen) > 0 ? Number(p.maxOpen) : capOpen());
if (held.length >= cap) return { ok: false, code: 'full', reason: 'You are already helping ' + held.length + ' people from the holding tank, and ' + cap + ' at one time is the most anyone can hold.', full: true, cap, held: held.length };
// the draft's own cap (2026-11-15): only open draft picks count, never the member's plain adoptions or tank batches
const open = await impl().open(a.email); const held = await holdingOf(open, 'draft'); const cap = Number(p.maxOpen) > 0 ? Number(p.maxOpen) : 10;
if (held.length >= cap) return { ok: false, code: 'full', reason: 'You already have ' + held.length + ' open draft picks, and ' + cap + ' at one time is the most a coach can hold.', full: true, cap, held: held.length };
return { ok: true, account: a, open };
}
// a holding tank batch (tankbatch.js, 2026-11-15): tankbatch has already decided the sponsor qualifies (active, own paid package on
// InstantAdPay or LinkSpin) and has room in their batch; this is the InstantAdPay side of the same gate as a 5x coach: a real account,
// not suspended or flagged, someone on THIS contract in their line, and that line takes payouts (else the person walks up to the company)
async function batchEligibility(email) {
const a = await accounts.byEmail(email);
if (!a) return { ok: false, code: 'no_account', reason: 'No such member.' };
const bar = hooks.excluded || hooks.isSuspended; if (bar && bar(a.email)) return { ok: false, code: 'excluded', reason: 'Adoptions are not available on this account.' };
const payee = await firstOnContract(a);
if (!payee) return { ok: false, code: 'no_contract_line', reason: 'Nobody in this line has switched on payouts on InstantAdPay.' };
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { ok: false, code: 'payout_blocked', reason: 'This line cannot take new members right now.' };
return { ok: true, account: a };
}
async function view(email) {
const e = String(email || '').toLowerCase();
const el = await eligibility(e);
@@ -175,8 +195,9 @@ async function adopt(adopterEmail, who, note, opts) {
// partner = a 5xYourTeam draft pick (draftpartner.js, 2026-11-15): the coach qualifies by a 5x position instead of the $20 buy,
// the window is the pick's (3 days, partner.ttlMs), the hub is asked fresh that nobody locked is taken, no reminder mails
const partner = (opts && opts.partner) || null;
const batch = !!(opts && opts.batch); // a holding tank batch (tankbatch.js): its own allowance, the grace and the two-adoptions rule still apply
const e = String(adopterEmail || '').toLowerCase();
const el = partner ? await partnerEligibility(e, partner) : await eligibility(e);
const el = partner ? await partnerEligibility(e, partner) : batch ? await batchEligibility(e) : await eligibility(e);
if (!el.ok) return { error: el.reason, code: el.code || 'not_eligible' };
const me = el.account;
const key = String(who || '').trim().toLowerCase().replace(/^@/, '');
@@ -187,10 +208,10 @@ async function adopt(adopterEmail, who, note, opts) {
if (!auto && target.opensAt > clock()) return { error: 'That member joined less than 24 hours ago, so they still have time to tell us who invited them. You can adopt them in ' + leftText(target.opensAt - clock()) + '.', code: 'grace' }; // the safety net is not held by this: it keeps its 24-hour clock from the wallet link
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.', code: 'linkspin' };
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.', code: 'adopted_twice' }; // the safety net never leaves anyone to the company
if ((partner || batch) && await inDownlineOf(target.email, me)) return { error: 'That member is above you in your own line.', code: 'loop' };
if (partner) { // never anyone locked on a network contract: asked fresh, a hub that does not answer refuses (the conservative side)
const lk = await lockedWhy(target.email);
if (lk) return { error: lk === 'locked' ? 'That member is locked to a sponsor on a network contract.' : 'The network record cannot be checked right now. Try again in a few minutes.', code: lk === 'locked' ? 'locked' : 'hub_unknown' };
if (await inDownlineOf(target.email, me)) return { error: 'That member is above you in your own line.', code: 'loop' };
}
const token = me.username || me.code || String(me.memberId);
const r = await setSponsor(target.email, token, 'adopt');
@@ -255,7 +276,8 @@ async function sweep() {
let done = 0, back = 0, kept = 0;
for (const ad of await impl().open(null)) {
if (ad.expires > now) continue;
if (hooks.isDraftPick && await Promise.resolve(hooks.isDraftPick(ad.id)).catch(() => true)) continue; // a 5xYourTeam pick: draftpartner.js owns its 3-day window (started = payouts on, not a wallet)
if (hooks.isDraftPick && await Promise.resolve(hooks.isDraftPick(ad.id)).catch(() => true)) continue;
if (hooks.isBatchPick && await Promise.resolve(hooks.isBatchPick(ad.id)).catch(() => true)) continue; // a holding tank batch: tankbatch.js owns its follow-up window // a 5xYourTeam pick: draftpartner.js owns its 3-day window (started = payouts on, not a wallet)
const a = await accounts.byEmail(ad.adoptee);
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; }
@@ -517,7 +539,7 @@ async function autoAssignRun() {
let done = null;
for (const c of pool) {
if (c.a.email === e) continue;
if ((await holding(await impl().open(c.a.email))).length >= capOpen()) continue;
if ((await holdingOf(await impl().open(c.a.email), 'plain')).length >= capOpen()) continue;
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(c.a.memberId))).catch(() => true)) continue; // no-payout chain: they would fall to the company after all
if (await inDownlineOf(e, c.a)) continue;
const msg = 'Hi, I am ' + nameOf(c.a) + '. ' + ((a.joinedVia === 'btc4hits' || a.joinedRef === 'btc4hits') ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor and nobody picked you up from the holding tank within 24 hours, so you were matched with me. I will walk you through the first steps whenever you are ready. Reply here.';
@@ -718,5 +740,5 @@ async function adminView() {
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
}
module.exports = { partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
module.exports = { batchEligibility, holdingOf, firstOnContract, inDownlineOf, markOf: email => impl().mark(String(email || '').toLowerCase()), _ready: { state: () => RS.load(), save: () => RS.save() }, _json: { state: () => J.db, save: () => J.save() } /* member erase (erase.js) */, partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
+329
View File
@@ -0,0 +1,329 @@
'use strict';
// Holding tank batches (Marty 2026-11-15: "let's auto-assign 10 at a time if they've got a paid package of $20 or $25, depending on
// which platform it was. If they fueled their engines or they've bought higher packages, let's raise that batch up to be like 20 or
// 25 at a time and keep climbing up (because I want those people in the holding tank to get people that are active paying sponsors)").
//
// THE RULES (every number is a site setting, see DEFAULTS)
// eligible sponsor signed in within tankBatchActiveDays (7) and holds their own paid package: $20+ on InstantAdPay (a chain
// Purchase by their member number or a linked position) or $25+ on LinkSpin (known here through the refuel
// streak record, the only place LinkSpin packages reach InstantAdPay); not the company, not suspended or flagged,
// someone on this contract in their line and that line takes payouts (tank.batchEligibility)
// batch size Paid 10. Fueled 20: a counted refuel streak is active, or a higher package ($50+ on either site). Twin Engine
// 25: both engines refueled this cycle, or the top package (the highest package on the live InstantAdPay
// catalog, $500 Elite today; LinkSpin $500 Network). Then +5 for every further consecutive refuel month, up to 50.
// "at a time" a sponsor holds at most one batch size of batch people who have not switched on payouts; a person who
// switches on payouts frees their place at once
// cadence every tankBatchEveryDays (2) per sponsor a fresh batch tops them back up to their size. One round deals by
// rotation, highest tier first (ties: longest since their last batch), one person per sponsor per pass, from
// the waiting tank in the order the tank already uses (tank.adoptable: past the 24-hour sign-up grace, rule 3
// applied, nobody adopted on LinkSpin). Never: the sponsor themself, anyone above them in their own line, anyone
// adopted twice, a flagged, spam, throwaway or unsubscribed address
// assignment tank.adopt(.., { batch: true }): the same sponsor change, chat, "X is now your sponsor" email and switch-on-payouts
// reminders as any adoption. The sponsor gets one notice per batch (not one per person)
// follow-up a batch person the sponsor has not contacted (a chat after the assignment, or "Contacted them") within
// tankBatchFollowDays (7) goes back to the tank as 'unreached' (does not count toward their two adoptions:
// the sponsor's miss). Contacted ones close like any adoption window: payouts on or wallet linked = done,
// else back to the tank (counted)
// tank feed per batch: one card to the shared payments topic and the live toast feed, naming the sponsor, the count and
// the level, never the people (Marty 2026-11-15: "if the others see that happening, it may pick up the pace")
// the 24-hour activation-hold safety net (tank.autoAssign) is unchanged and runs beside this; the 5xYourTeam draft has its own cap
// MASTER SWITCH: site setting tankBatches (default '0'). Off: no round, no feed, the member panel answers { on:false }. The follow-up
// still runs for batch people already assigned (they must not sit uncontacted). preview() is read-only whatever the switch says.
const fs = require('fs');
const path = require('path');
const D = 86400000;
const DEFAULTS = {
tankBatches: '0', tankBatchActiveDays: 7, tankBatchBase: 10, tankBatchFueled: 20, tankBatchTwin: 25, tankBatchStep: 5, tankBatchMax: 50,
tankBatchEveryDays: 2, tankBatchFollowDays: 7, tankBatchMinIapCents: 2000, tankBatchMinLsCents: 2500,
tankBatchHigherIapCents: 5000, tankBatchHigherLsCents: 5000, tankBatchTopIapCents: 0 /* 0 = the highest package on the live catalog */, tankBatchTopLsCents: 50000,
tankBatchFeed: '1'
};
let R = null; // { dataDir, db, accounts, chain, tank, refuel, messages, mailer, siteConfig, hooks: { excluded, excludedPerson, claim, feed, toast, notify, companyId, networkSeen }, clock }
const clock = () => (R && R.clock ? R.clock() : Date.now());
const lc = v => String(v || '').trim().toLowerCase();
const usd = c => ('$' + (Number(c || 0) / 100).toFixed(2)).replace(/\.00$/, '');
const nameOf = a => a ? (a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'a member')) : 'a member';
function cfg() {
const sc = (R && R.siteConfig && R.siteConfig()) || {};
const num = (k, lo, hi) => { const v = Number(sc[k] == null || sc[k] === '' ? DEFAULTS[k] : sc[k]); return Number.isFinite(v) && v >= lo && v <= hi ? v : DEFAULTS[k]; };
return { on: String(sc.tankBatches == null ? DEFAULTS.tankBatches : sc.tankBatches) === '1', feed: String(sc.tankBatchFeed == null ? '1' : sc.tankBatchFeed) !== '0',
activeDays: num('tankBatchActiveDays', 1, 60), base: num('tankBatchBase', 1, 200), fueled: num('tankBatchFueled', 1, 200), twin: num('tankBatchTwin', 1, 200),
step: num('tankBatchStep', 0, 100), max: num('tankBatchMax', 1, 500), everyDays: num('tankBatchEveryDays', 0.04, 60), followDays: num('tankBatchFollowDays', 1, 60),
minIap: num('tankBatchMinIapCents', 0, 1e7), minLs: num('tankBatchMinLsCents', 0, 1e7), higherIap: num('tankBatchHigherIapCents', 0, 1e7), higherLs: num('tankBatchHigherLsCents', 0, 1e7),
topIap: num('tankBatchTopIapCents', 0, 1e8), topLs: num('tankBatchTopLsCents', 0, 1e8) };
}
// ---- the ladder (pure: the tests drive it directly) ----
// f = { iapMax, lsMax, refuel: { active, streak, both } | null }, c = cfg() with topIap resolved
function tierFor(f, c) {
const rf = f.refuel || {}; const reasons = [];
const paidIap = f.iapMax >= c.minIap, paidLs = f.lsMax >= c.minLs;
if (!paidIap && !paidLs) return { level: null, size: 0, reasons: ['no own package of ' + usd(c.minIap) + '+ on InstantAdPay or ' + usd(c.minLs) + '+ on LinkSpin'] };
if (paidIap) reasons.push('own ' + usd(f.iapMax) + ' InstantAdPay package'); if (paidLs) reasons.push('own ' + usd(f.lsMax) + ' LinkSpin package');
let level = 'Paid', size = c.base;
const higher = (c.higherIap > 0 && f.iapMax >= c.higherIap) || (c.higherLs > 0 && f.lsMax >= c.higherLs);
const top = (c.topIap > 0 && f.iapMax >= c.topIap) || (c.topLs > 0 && f.lsMax >= c.topLs);
if (rf.active || higher) { level = 'Fueled'; size = c.fueled; if (rf.active) reasons.push('refuel streak month ' + rf.streak); if (higher) reasons.push('higher package (' + usd(c.higherIap) + '+ InstantAdPay / ' + usd(c.higherLs) + '+ LinkSpin)'); }
if ((rf.active && rf.both) || top) { level = 'Twin Engine'; size = c.twin; if (rf.active && rf.both) reasons.push('both engines refueled this cycle'); if (top) reasons.push('top package'); }
const extra = rf.active && rf.streak > 1 ? (rf.streak - 1) * c.step : 0;
if (extra) { size += extra; reasons.push('+' + extra + ' for ' + (rf.streak - 1) + ' further refuel month' + (rf.streak === 2 ? '' : 's')); }
size = Math.min(size, c.max);
const label = level + (rf.active && rf.streak > 1 ? ', month ' + rf.streak : '');
return { level, label, size, reasons };
}
// the member panel's "next step" line: what raises their batch, in leads they can sponsor (never money)
function nextStep(t, f, c) {
const rf = f.refuel || {};
if (!t.level) return 'Buy your own ' + usd(c.minIap) + ' package on InstantAdPay (or ' + usd(c.minLs) + ' on LinkSpin) to start receiving ' + c.base + ' people at a time.';
if (t.size >= c.max) return 'You are at the top of the ladder: ' + c.max + ' people at a time. Keep your refuel streak going to stay there.';
if (t.level === 'Paid') return 'A counted monthly refuel (or a higher package) raises your batch to ' + c.fueled + '. Refuel both InstantAdPay and LinkSpin in the same cycle for ' + c.twin + '.';
if (t.level === 'Fueled' && !(rf.active && rf.both)) return 'Refuel the other engine this cycle too (InstantAdPay and LinkSpin) to raise your batch to ' + Math.min(c.max, c.twin + (rf.active && rf.streak > 1 ? (rf.streak - 1) * c.step : 0)) + '.';
return 'Your next consecutive refuel month adds ' + c.step + ' more (up to ' + c.max + ').';
}
const ladderView = c => [
{ level: 'Paid', size: c.base, how: 'your own ' + usd(c.minIap) + ' InstantAdPay package or ' + usd(c.minLs) + ' LinkSpin package' },
{ level: 'Fueled', size: c.fueled, how: 'a counted monthly refuel, or a higher package (' + usd(c.higherIap) + '+)' },
{ level: 'Twin Engine', size: c.twin, how: 'both engines refueled this cycle, or the top package' },
{ level: 'Streak', size: c.max, how: '+' + c.step + ' for every further consecutive refuel month, up to ' + c.max }
];
// ---- storage: MySQL tank_batch_picks when DATABASE_URL is set, else a JSON document (local QA) ----
const J = {
st: null, FILE: () => path.join(R.dataDir, 'tank-batch.json'),
load() { if (this.st) return this.st; try { this.st = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.st = null; } if (!this.st || typeof this.st !== 'object') this.st = {}; this.st.nextId = this.st.nextId || 1; this.st.picks = this.st.picks || []; this.st.rounds = this.st.rounds || []; return this.st; },
save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); },
async add(p) { const s = this.load(); const row = Object.assign({ id: s.nextId++ }, p); s.picks.push(row); this.save(); return Object.assign({}, row); },
async close(id, status, why) { const x = this.load().picks.find(r => r.id === id); if (x) { x.status = status; x.closed = clock(); x.why = why || null; this.save(); } },
async open() { return this.load().picks.filter(r => r.status === 'open').map(x => Object.assign({}, x)); },
async byAdoption(aid) { const x = this.load().picks.find(r => r.adoptionId === Number(aid)); return x ? Object.assign({}, x) : null; },
async lastBySponsor() { const m = new Map(); for (const r of this.load().picks) m.set(r.sponsor, Math.max(m.get(r.sponsor) || 0, r.roundAt || r.at)); return m; },
async recent(n) { return this.load().picks.slice(-(n || 100)).reverse().map(x => Object.assign({}, x)); },
async addRound(x) { const s = this.load(); s.rounds.push(x); if (s.rounds.length > 200) s.rounds = s.rounds.slice(-200); this.save(); },
async rounds(n) { return this.load().rounds.slice(-(n || 30)).reverse(); }
};
const rowP = r => ({ id: Number(r.id), adoptionId: Number(r.adoption_id), sponsor: r.sponsor, adoptee: r.adoptee, at: Number(r.at), roundAt: Number(r.round_at), level: r.level, size: Number(r.size), status: r.status, closed: r.closed ? Number(r.closed) : null, why: r.why || null });
const Q = {
async add(p) { const r = await R.db.q('INSERT INTO tank_batch_picks (adoption_id,sponsor,adoptee,at,round_at,level,size,status) VALUES (?,?,?,?,?,?,?,?)', [p.adoptionId, p.sponsor, p.adoptee, p.at, p.roundAt, p.level, p.size, 'open']); return Object.assign({ id: r.insertId }, p); },
async close(id, status, why) { await R.db.q('UPDATE tank_batch_picks SET status=?, closed=?, why=? WHERE id=?', [status, clock(), why ? String(why).slice(0, 200) : null, Number(id)]); },
async open() { return (await R.db.q("SELECT * FROM tank_batch_picks WHERE status='open' ORDER BY id")).map(rowP); },
async byAdoption(aid) { const r = (await R.db.q('SELECT * FROM tank_batch_picks WHERE adoption_id=? LIMIT 1', [Number(aid)]))[0]; return r ? rowP(r) : null; },
async lastBySponsor() { return new Map((await R.db.q('SELECT sponsor, MAX(round_at) t FROM tank_batch_picks GROUP BY sponsor')).map(r => [r.sponsor, Number(r.t)])); },
async recent(n) { return (await R.db.q('SELECT * FROM tank_batch_picks ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); },
async addRound(x) { await R.db.q('INSERT INTO tank_batch_rounds (at, summary) VALUES (?,?)', [x.at, JSON.stringify(x).slice(0, 60000)]); },
async rounds(n) { return (await R.db.q('SELECT summary FROM tank_batch_rounds ORDER BY id DESC LIMIT ?', [Number(n) || 30])).map(r => { try { return JSON.parse(r.summary); } catch (e) { return null; } }).filter(Boolean); }
};
const dbOn = () => !!(R && R.db && R.db.enabled && R.db.enabled());
const S = () => (dbOn() ? Q : J);
async function ensureTables() {
if (!dbOn()) return;
await R.db.q(`CREATE TABLE IF NOT EXISTS tank_batch_picks (
id INT AUTO_INCREMENT PRIMARY KEY, adoption_id INT NOT NULL, sponsor VARCHAR(190) NOT NULL, adoptee VARCHAR(190) NOT NULL, at BIGINT NOT NULL, round_at BIGINT NOT NULL,
level VARCHAR(40) NULL, size INT NOT NULL DEFAULT 0, status VARCHAR(16) NOT NULL, closed BIGINT NULL, why VARCHAR(200) NULL,
KEY adoption (adoption_id), KEY sp (sponsor, status), KEY st (status), KEY adoptee (adoptee)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // holding tank batches (each one a tank adoption)
await R.db.q('CREATE TABLE IF NOT EXISTS tank_batch_rounds (id INT AUTO_INCREMENT PRIMARY KEY, at BIGINT NOT NULL, summary MEDIUMTEXT NOT NULL, KEY t (at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
}
async function init(opts) { R = opts; R.hooks = R.hooks || {}; J.st = null; await ensureTables(); }
// ---- facts about the members ----
function iapMaxByMember() { const m = new Map(); for (const ev of R.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.buyerId) { const id = Number(ev.buyerId); m.set(id, Math.max(m.get(id) || 0, Number(ev.priceCents) || 0)); } return m; }
async function topIapCents(c) {
if (c.topIap > 0) return c.topIap;
try { const cat = await R.chain.catalog(); const top = Math.max(0, ...(cat || []).map(p => Number(p.priceCents) || 0)); if (top > 0) return top; } catch (e) {}
return 50000; // Elite $500, the top of the published ladder (chatbot.js) when the catalog cannot be read
}
async function factsOf(a, byMember) {
let iapMax = Number(a.memberId) > 0 ? byMember.get(Number(a.memberId)) || 0 : 0;
if (R.accounts.positions) { try { for (const p of await R.accounts.positions(a.email)) if (p.memberId) iapMax = Math.max(iapMax, byMember.get(Number(p.memberId)) || 0); } catch (e) {} }
let rf = null; try { rf = R.refuel && R.refuel.standing ? await R.refuel.standing(a.email, clock()) : null; } catch (e) { rf = null; }
const lsMax = rf ? Number(rf.maxCents.linkspin) || 0 : 0;
if (rf) iapMax = Math.max(iapMax, Number(rf.maxCents.iap) || 0);
return { iapMax, lsMax, refuel: rf };
}
const companyIds = () => new Set([1, Number(R.hooks.companyId ? R.hooks.companyId() : 1) || 1]);
async function lastSeenOf(a) {
let t = Number(a.lastSeen) || 0;
if (R.hooks.networkSeen) { try { t = Math.max(t, Number(await R.hooks.networkSeen(a.email)) || 0); } catch (e) {} }
return t;
}
// every member, sorted out: eligible sponsors (with tier, room, due) and the near misses (why not)
async function sponsors(c, now) {
const byMember = iapMaxByMember(); const co = companyIds(); const last = await S().lastBySponsor();
const openByS = new Map(); for (const p of await S().open()) { if (!openByS.has(p.sponsor)) openByS.set(p.sponsor, []); openByS.get(p.sponsor).push(p); }
const out = [], skipped = []; const why = {};
const skip = (a, reason, extra) => { why[reason] = (why[reason] || 0) + 1; if (skipped.length < 300) skipped.push(Object.assign({ name: nameOf(a), reason }, extra || {})); };
for (const a of await R.accounts.listAll(1e6)) {
if (Number(a.memberId) > 0 && co.has(Number(a.memberId))) continue;
const seen = await lastSeenOf(a); const active = !!seen && now - seen <= c.activeDays * D;
if (!active && !(Number(a.memberId) > 0)) continue; // cheap first: a free inactive account is nobody's near miss
const f = await factsOf(a, byMember); const t = tierFor(f, Object.assign({}, c, { topIap: c.topIapResolved }));
if (!t.level) continue; // free members are not sponsors here (not listed: the near misses are paid members)
if (!active) { skip(a, 'not active in the last ' + c.activeDays + ' days', { level: t.label, size: t.size, lastSeen: seen || 0 }); continue; }
const bar = R.hooks.excluded || R.hooks.isSuspended; if (bar && bar(a.email)) { skip(a, 'suspended or flagged'); continue; }
const el = await R.tank.batchEligibility(a.email); if (!el.ok) { skip(a, el.code === 'no_contract_line' ? 'nobody in their line has payouts on at InstantAdPay' : el.reason, { level: t.label, size: t.size }); continue; }
const open = []; for (const p of openByS.get(a.email) || []) { const acc = await R.accounts.byEmail(p.adoptee); if (!(acc && Number(acc.memberId) > 0)) open.push(p); }
const lastAt = last.get(a.email) || 0; const dueAt = lastAt ? lastAt + c.everyDays * D : 0;
out.push({ account: a, email: a.email, name: nameOf(a), username: a.username || null, memberId: Number(a.memberId) || 0, lastSeen: seen, tier: t, facts: f,
holding: open.length, room: Math.max(0, t.size - open.length), lastBatchAt: lastAt, dueAt, due: !dueAt || now >= dueAt });
}
const rank = { 'Twin Engine': 3, Fueled: 2, Paid: 1 };
out.sort((x, y) => y.tier.size - x.tier.size || (rank[y.tier.level] || 0) - (rank[x.tier.level] || 0) || x.lastBatchAt - y.lastBatchAt || y.lastSeen - x.lastSeen || (x.email < y.email ? -1 : 1));
return { list: out, skipped, why };
}
// the waiting people a batch may take, in the tank's own order
async function poolOf() {
const list = await R.tank.adoptable(); const local = await R.tank.summaryMap(); const ex = {}; const rows = [];
const no = k => { ex[k] = (ex[k] || 0) + 1; };
for (const w of list) {
if (R.hooks.excluded && R.hooks.excluded(w.email)) { no('flagged or suspended'); continue; }
const n = ((local.get(w.email) || {}).count || 0) + (R.tank.remoteCount ? R.tank.remoteCount(w.email) : 0);
if (n >= (R.tank.MAX_ADOPTIONS || 2)) { no('adopted twice already'); continue; }
let px = null; if (R.hooks.excludedPerson) { try { px = await R.hooks.excludedPerson(w.email); } catch (e) { px = 'check failed'; } }
if (px) { no(px); continue; }
rows.push(w);
}
return { waiting: list.length, rows, excluded: ex };
}
// one round: who gets whom. Read-only: the live run applies it, the preview shows it.
async function plan(c, now) {
const sp = await sponsors(c, now); const pool = await poolOf();
const takers = sp.list.filter(s => s.due && s.room > 0).map(s => Object.assign(s, { give: [] }));
const left = pool.rows.slice(); const loopCache = new Map();
let moved = true;
while (moved && left.length) {
moved = false;
for (const s of takers) {
if (s.give.length >= s.room || !left.length) continue;
for (let i = 0; i < left.length; i++) {
const w = left[i];
if (w.email === s.email) continue;
const k = w.email + '>' + s.email;
if (!loopCache.has(k)) loopCache.set(k, await R.tank.inDownlineOf(w.email, s.account).catch(() => true));
if (loopCache.get(k)) continue;
s.give.push(w); left.splice(i, 1); moved = true; break;
}
}
}
return { sponsors: sp, pool, takers, left: left.length };
}
// ---- the live round ----
let busy = null;
const lock = fn => (dbOn() && R.db.withLock ? R.db.withLock('tankbatch', fn, 5) : fn());
async function round() {
const c = cfg(); if (!c.on) return { on: false };
if (busy) return busy;
busy = (async () => {
c.topIapResolved = await topIapCents(c);
const now = clock(); const summary = { at: now, batches: [], assigned: 0, refused: 0 };
await lock(async () => {
const p = await plan(c, now);
for (const s of p.takers) {
if (!s.give.length) continue;
const got = [];
for (const w of s.give) {
const msg = 'Hi, I am ' + s.name + '. ' + (w.via === 'btc4hits' ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor, so you were matched with me from the holding tank: active members who have bought their own package take turns. I will walk you through the first steps whenever you are ready. Reply here.';
const r = await R.tank.adopt(s.email, w.username || w.email, msg, { batch: true, recordNote: 'holding tank batch (' + s.tier.label + ', ' + s.tier.size + ' at a time)' }).catch(e => ({ error: e.message }));
if (!(r && r.ok)) { summary.refused++; continue; }
await S().add({ adoptionId: Number(r.adoption.id), sponsor: s.email, adoptee: r.adoptee, at: clock(), roundAt: now, level: s.tier.label, size: s.tier.size, status: 'open' });
got.push(r.adopteeName);
}
if (!got.length) continue;
summary.assigned += got.length; summary.batches.push({ sponsor: s.name, level: s.tier.label, size: s.tier.size, count: got.length });
await tellSponsor(s, got, c);
await feedCard(s, got.length, now, c);
}
});
if (summary.batches.length) { try { await S().addRound(summary); } catch (e) { console.error('tankbatch round log', e.message); } console.log('tankbatch round', JSON.stringify({ assigned: summary.assigned, batches: summary.batches.length, refused: summary.refused })); }
return Object.assign({ on: true }, summary);
})().finally(() => { busy = null; });
return busy;
}
async function tellSponsor(s, names, c) {
const subject = names.length + ' new ' + (names.length === 1 ? 'person' : 'people') + ' from the holding tank are in your line';
const text = 'As a ' + s.tier.label + ' member you receive up to ' + s.tier.size + ' people at a time from the holding tank. These ' + names.length + ' joined without a sponsor and are now in your line: ' + names.join(', ')
+ '.\n\nEach one got a chat from you and an email saying you are their sponsor. Say hello in the next ' + c.followDays + ' days: anyone you have not contacted by then (a chat from you, or "Contacted them" on their row in My line) goes back to the holding tank for another member.\n\n' + 'https://instantadpay.com/my#line';
if (R.hooks.notify) { try { await R.hooks.notify(s.email, subject, text); } catch (e) {} }
if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) { try { await R.mailer.send(s.email, 'InstantAdPay: ' + subject, text + '\n\nInstantAdPay'); } catch (e) {} }
}
async function feedCard(s, n, roundAt, c) {
if (!c.feed) return;
if (R.hooks.claim) { let mine = false; try { mine = await R.hooks.claim('tankbatch:feed:' + s.email + ':' + roundAt); } catch (e) {} if (!mine) return; }
const who = s.username ? '@' + s.username : s.name;
const what = n + ' new team member' + (n === 1 ? '' : 's');
if (R.hooks.feed) { try { await R.hooks.feed(who, what, s.tier.label); } catch (e) { console.error('tankbatch feed', e.message); } }
if (R.hooks.toast) { try { R.hooks.toast({ type: 'Adopted', sponsor: who, member: what + ' (' + s.tier.label + ' level)', ts: clock() }); } catch (e) {} }
}
// ---- follow-up: uncontacted batch people go back to the tank ----
let following = null;
function followUp() { if (!following) following = followRun().finally(() => { following = null; }); return following; }
async function followRun() {
const c = cfg(); const now = clock(); const out = { done: 0, unreached: 0, returned: 0, kept: 0, moved: 0, waiting: 0 }; const back = new Map();
for (const p of await S().open()) {
const open = await R.tank.openOf(p.adoptee);
if (!open.some(ad => Number(ad.id) === p.adoptionId)) { await S().close(p.id, 'moved', 'the adoption was closed elsewhere (released, moved or followed)'); out.moved++; continue; }
const a = await R.accounts.byEmail(p.adoptee);
if (a && Number(a.memberId) > 0) { await R.tank.closeAdoption(p.adoptionId, 'done'); await S().close(p.id, 'done', 'payouts on'); out.done++; continue; }
if (now - p.at < c.followDays * D) continue;
if (!a) { await R.tank.closeAdoption(p.adoptionId, 'expired'); await S().close(p.id, 'gone', 'account gone'); continue; }
const chat = R.messages && R.messages.lastFrom ? await R.messages.lastFrom(p.sponsor, p.adoptee).catch(() => 0) : 0;
const mk = R.tank.markOf ? await R.tank.markOf(p.adoptee).catch(() => null) : null;
const contacted = chat > p.at + 60000 || !!(mk && mk.contacted > p.at); // the assignment's own chat is sent at p.at: it does not count
if (contacted && a.address) { await R.tank.closeAdoption(p.adoptionId, 'done'); await S().close(p.id, 'done', 'contacted, wallet linked'); out.done++; continue; }
if (contacted && await R.tank.countAll(p.adoptee) >= (R.tank.MAX_ADOPTIONS || 2)) { await R.tank.closeAdoption(p.adoptionId, 'expired'); await S().close(p.id, 'kept', 'adopted twice: stays with this sponsor'); out.kept++; continue; }
const lk = await R.tank.lockedWhy(p.adoptee);
if (lk === 'unknown') { out.waiting++; continue; }
if (lk === 'locked') { await R.tank.closeAdoption(p.adoptionId, 'expired'); await S().close(p.id, 'kept', 'locked on a network contract'); out.kept++; continue; }
const r = await R.tank.setSponsorDeliberate(p.adoptee, '', 'expire', contacted ? 'holding tank batch window ended' : 'holding tank batch: not contacted in ' + c.followDays + ' days');
if (r && r.error) { out.waiting++; continue; }
await R.tank.closeAdoption(p.adoptionId, contacted ? 'expired' : 'unreached');
await S().close(p.id, contacted ? 'returned' : 'unreached', contacted ? 'window ended' : 'not contacted');
if (contacted) out.returned++; else { out.unreached++; if (!back.has(p.sponsor)) back.set(p.sponsor, []); back.get(p.sponsor).push(nameOf(a)); }
}
for (const [sp, names] of back) {
if (R.hooks.notify) { try { await R.hooks.notify(sp, names.length + ' from your holding tank batch went back to the tank', names.join(', ') + (names.length === 1 ? ' was' : ' were') + ' in your line for ' + c.followDays + ' days with no chat from you and no "Contacted them" mark, so ' + (names.length === 1 ? 'they have' : 'they have') + ' gone back to the holding tank for another member. Your next batch still comes on schedule: say hello to each new person in the first few days.\n\nhttps://instantadpay.com/my#line'); } catch (e) {} }
}
return out;
}
async function isBatchPick(adoptionId) { if (!R) return false; const p = await S().byAdoption(adoptionId); return !!(p && p.status === 'open'); }
// the hourly pass (server.js): follow-up always, a round only while the switch is on
async function tick() { const f = await followUp().catch(e => { console.error('tankbatch follow', e.message); return null; }); const r = await round().catch(e => { console.error('tankbatch round', e.message); return { error: e.message }; }); return { follow: f, round: r }; }
// ---- admin preview: the first round against the live tank, nothing written, nothing sent ----
async function preview() {
const c = cfg(); c.topIapResolved = await topIapCents(c); const now = clock();
const p = await plan(c, now);
const sp = p.sponsors.list.map(s => ({ name: s.name, memberId: s.memberId || null, level: s.tier.label, size: s.tier.size, reasons: s.tier.reasons,
lastSeen: s.lastSeen, iapMaxUsd: s.facts.iapMax / 100, lsMaxUsd: s.facts.lsMax / 100,
refuel: s.facts.refuel ? { active: s.facts.refuel.active, streak: s.facts.refuel.streak, both: s.facts.refuel.both, lastDay: s.facts.refuel.lastDay } : null,
holding: s.holding, room: s.room, due: s.due, dueAt: s.dueAt || null,
wouldGet: (s.give || []).length, firstNames: (s.give || []).slice(0, 8).map(w => w.name) }));
const byLevel = {}; for (const s of sp) { const b = byLevel[s.level.replace(/, month \d+$/, '')] = byLevel[s.level.replace(/, month \d+$/, '')] || { sponsors: 0, people: 0 }; b.sponsors++; b.people += s.wouldGet; }
return { readOnly: true, on: c.on, generatedAt: now, settings: Object.assign({}, c, { topIapCents: c.topIapResolved }), ladder: ladderView(c),
tank: { waiting: p.pool.waiting, offered: p.pool.rows.length, excluded: p.pool.excluded, leftAfterRound: p.left },
totals: { eligibleSponsors: sp.length, takingThisRound: p.takers.filter(t => t.give.length).length, people: p.takers.reduce((n, t) => n + t.give.length, 0), capacity: sp.reduce((n, s) => n + s.room, 0), byLevel },
sponsors: sp, notEligible: { counts: p.sponsors.why, members: p.sponsors.skipped } };
}
// ---- the member panel "How to get fed leads" ----
async function myView(email) {
const c = cfg(); if (!c.on) return { on: false };
c.topIapResolved = await topIapCents(c);
const a = await R.accounts.byEmail(lc(email)); if (!a) return { on: true, ladder: ladderView(c) };
const f = await factsOf(a, iapMaxByMember()); const t = tierFor(f, Object.assign({}, c, { topIap: c.topIapResolved }));
const seen = await lastSeenOf(a); const active = !!seen && clock() - seen <= c.activeDays * D;
const mine = (await S().open()).filter(p => p.sponsor === a.email);
const last = (await S().lastBySponsor()).get(a.email) || 0;
return { on: true, ladder: ladderView(c), everyDays: c.everyDays, followDays: c.followDays,
me: { level: t.level, label: t.label || null, size: t.size, reasons: t.reasons, next: nextStep(t, f, c), active, open: mine.length, lastBatchAt: last || null, nextBatchAt: last ? last + c.everyDays * D : null } };
}
async function adminView() { return { settings: cfg(), open: (await S().open()).length, recent: await S().recent(100), rounds: await S().rounds(20) }; }
module.exports = { init, cfg, tierFor, nextStep, ladderView, plan, round, followUp, tick, preview, myView, adminView, isBatchPick, DEFAULTS };