Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c06c58daf | |||
| e1bee03b95 | |||
| e17d8c4fbb | |||
| 7f57aedcb6 | |||
| 968e60835f | |||
| 911dd623c0 | |||
| 4ccdb914c7 | |||
| 82eab8016b | |||
| 4787390e8b | |||
| d033cc7122 | |||
| efb054d916 | |||
| 32f001aade | |||
| edc484db27 | |||
| 836c7b17c2 | |||
| a01d6f2e8c | |||
| ff568d973c | |||
| 5398faadee | |||
| a7c36a908a | |||
| 92288a30f5 | |||
| d626469980 | |||
| e98a6ebcd8 | |||
| f29f6d1407 | |||
| 9efdfc8ee9 | |||
| 4e2178d779 | |||
| f20062133f | |||
| 24b4ae9134 | |||
| 2d4fc7a9f3 | |||
| 00cfd09c8f | |||
| 4cf3512106 | |||
| 1f584f894f | |||
| ff2f668583 | |||
| fab7732620 | |||
| 5c896cb782 | |||
| 74354346a3 | |||
| dbdeb5a7e6 | |||
| 85d43f7483 | |||
| cedb291aaa | |||
| 574a0cafb1 | |||
| 55d3597f12 | |||
| fe70c857be | |||
| 5585abb663 | |||
| db1ab8359c | |||
| 3eae242dc3 | |||
| 5e8dee7517 | |||
| ffcc0c6339 |
+7
-2
@@ -483,8 +483,13 @@ async function count() { return impl().count(); }
|
||||
// A waiting account made from a LinkSpin registry row (lsinbound.js, 2026-10-15) that its owner has not signed in to yet.
|
||||
// It exists so the LinkSpin line is already in place; it is not a member yet, so the sweeps that mail, count or adopt
|
||||
// members (listAll by default) leave it out. It becomes an ordinary account the first time its owner signs in (lastSeen).
|
||||
const isUnclaimedShell = a => !!a && a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId;
|
||||
async function listAll(limit = 500, opts) { const all = await impl().listAll(limit); return opts && opts.shells ? all : all.filter(a => !isUnclaimedShell(a)); }
|
||||
// BTC4Hits members imported 2026-11-11 (btc4hits-migration, joinedVia 'btc4hits') are the same kind of waiting account.
|
||||
// Network hub members who joined at another door (hubsync.js, 2026-11-12, only while HUB_ENABLED) arrive as joinedVia 'hub'.
|
||||
const SHELL_VIAS = new Set(['linkspin', 'btc4hits', 'hub']);
|
||||
const isUnclaimedShell = a => !!a && SHELL_VIAS.has(a.joinedVia) && !a.lastSeen && !a.memberId;
|
||||
// the limit counts members, not waiting accounts: newest-first LIMIT before the filter let thousands of waiting accounts push
|
||||
// older real members out of the sweeps that read listAll(5000) (tank, coach, leaderboard, Friday, Wednesday)
|
||||
async function listAll(limit = 500, opts) { if (opts && opts.shells) return impl().listAll(limit); const all = await impl().listAll(1e7); return all.filter(a => !isUnclaimedShell(a)).slice(0, limit); }
|
||||
async function identities() { return impl().identities(); }
|
||||
async function setSponsorRef(email, ref) { const r = await impl().setSponsorRef(normEmail(email), String(ref || '').trim().toLowerCase().slice(0, 40)); if (r && !r.error) changed(normEmail(email)); return r; }
|
||||
|
||||
|
||||
@@ -105,12 +105,12 @@ function head(o) {
|
||||
+ (o.article ? '<meta property="article:published_time" content="' + new Date(o.article.publishedAt || o.article.created).toISOString() + '"><meta property="article:modified_time" content="' + new Date(o.article.updated).toISOString() + '"><meta property="article:author" content="' + esc(AUTHOR) + '">' + (o.article.tags || []).map(t => '<meta property="article:tag" content="' + esc(t) + '">').join('') : '')
|
||||
+ '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' + esc(o.title) + '"><meta name="twitter:description" content="' + esc(o.desc) + '"><meta name="twitter:image" content="' + esc(img) + '">'
|
||||
+ '<link rel="alternate" type="application/rss+xml" title="InstantAdPay blog" href="' + SITE + '/blog/feed.xml"><link rel="icon" type="image/png" href="/logo-icon.png">'
|
||||
+ '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261101th">'
|
||||
+ '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln">'
|
||||
+ '<style>.bl{max-width:760px}.bl h1{font-size:clamp(30px,4.6vw,44px);line-height:1.12;margin:10px 0 12px}.bl .meta{color:var(--muted);font-size:14px;margin:0 0 22px}.bl .cover{width:100%;border-radius:14px;border:1px solid var(--line);margin:0 0 26px;display:block}.bl article{font-size:17.5px;line-height:1.7}.bl article p{margin:0 0 18px;max-width:68ch}.bl article h2{font-size:26px;margin:36px 0 12px}.bl article h3{font-size:20px;margin:28px 0 10px}.bl article ul,.bl article ol{margin:0 0 18px 22px;max-width:66ch}.bl article li{margin:6px 0}.bl article blockquote{border-left:4px solid var(--mint);margin:0 0 18px;padding:8px 18px;color:var(--muted);font-style:italic}.bl article img{max-width:100%;border-radius:12px;border:1px solid var(--line)}.bl article a{color:var(--mint)}.bl article pre{background:var(--ground-soft);border:1px solid var(--line);border-radius:10px;padding:14px;overflow:auto;font-size:14px}.bl article table{border-collapse:collapse;width:100%;font-size:15px}.bl article th,.bl article td{border-bottom:1px solid var(--line);padding:8px 10px;text-align:left}.tags a{display:inline-block;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--mint);border:1px solid var(--mint-line);border-radius:999px;padding:3px 10px;margin:0 6px 6px 0;text-decoration:none}.post-card{display:block;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:20px 22px;margin:0 0 14px;color:inherit;text-decoration:none}.post-card:hover{border-color:var(--mint)}.post-card h2{font-size:22px;margin:0 0 6px}.post-card p{margin:0;color:var(--muted);font-size:15px;max-width:70ch}.post-card .meta{margin:8px 0 0;font-size:13px}.author{display:flex;gap:14px;align-items:center;border:1px solid var(--line);border-radius:14px;padding:16px 18px;margin:36px 0 0;background:var(--panel)}.author img{width:56px;height:56px;border-radius:50%;object-fit:cover}.author b{display:block}.author span{color:var(--muted);font-size:14px}.share a{margin-right:14px;font-size:14px}.pager{display:flex;justify-content:space-between;margin:26px 0}.related{margin-top:40px}.related h3{margin-bottom:10px}</style>'
|
||||
+ '</head><body><div class="wrap bl">';
|
||||
}
|
||||
function tail() {
|
||||
return '</div><script src="/assets/common.js?v=20261101th"></script><script src="/assets/blog-page.js?v=20261101th"></script></body></html>';
|
||||
return '</div><script src="/assets/common.js?v=20261114ns"></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>';
|
||||
|
||||
+35
-15
@@ -34,9 +34,13 @@ function key() {
|
||||
function enabled() { return !!key(); }
|
||||
|
||||
// ---- canned answers: instant, free, always in voice ----
|
||||
const KNOWLEDGE_DATE = '2026-11-10'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const KNOWLEDGE_DATE = '2026-11-14'; // 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)
|
||||
{ id: 'network-signin', title: 'One sign-in for InstantAdPay and LinkSpin', q: ['Do I have to sign in again on LinkSpin?', 'Why was I signed in on LinkSpin without a code?', 'Is it one sign-in for both sites?'], tags: ['sign in', 'network sign-in', 'linkspin', 'code', 'single sign-on'],
|
||||
re: /(((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password).{0,40}(linkspin|both sites|other site)|(linkspin|both sites|other site).{0,40}((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password)|single sign|sso|one sign.?in|network sign.?in)/i,
|
||||
a: 'One sign-in covers both sites. While you are signed in on InstantAdPay, any link inside your account that opens LinkSpin (the Engine Room, Refuel and the other LinkSpin links) lands you there signed in, with no code. It works the other way too, and if you open the sign-in screen on either site while you are signed in on the other, it signs you in by itself. Both sites use the same email. The one exception: if your account on the other site is not set up yet (for example you joined minutes ago, or it is waiting for your first visit), you get the usual email code that one time, with your email already filled in. Signing out signs you out of that site only, and it stays signed out there until you sign in again or follow a link from the other site. A session still lasts 4 hours on each site. This sign-in never moves money: buying, payouts and wallet actions work exactly as before.' },
|
||||
// Stack POL (2026-11-09): stackpol.com, every POL payout across the network on one page; members opt in to a page in Promo tools
|
||||
// Earners Corner (2026-11-10): earnerscorner.com, the network's forum; sign-in is the InstantAdPay account (DiscourseConnect)
|
||||
{ id: 'earners-corner', title: 'Earners Corner forum', q: ['What is Earners Corner?', 'Is there a forum?', 'How do I sign in to the forum?'], tags: ['earners corner', 'forum', 'earnerscorner', 'community', 'discussion'],
|
||||
@@ -49,7 +53,7 @@ const CANNED = [
|
||||
// this answer names neither; heroesFact() gives the AI the live state.
|
||||
{ id: 'sov-bonus-heroes', title: 'Shards of Valor bonus heroes', q: ['What are the bonus heroes in Shards of Valor?', 'How do I get Kestrel, Valda, Morag or Roland?', 'Is the hero a subscription?'], tags: ['shards of valor', 'heroes', 'bonus heroes', 'kestrel', 'valda', 'morag', 'roland', 'party'],
|
||||
re: /\b(bonus heroe?s?|kestrel|valda|morag|roland|paladin|barbarian|druid hero|archer hero|hero bundle)\b/i,
|
||||
a: 'Shards of Valor has four bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid and Roland the Paladin. Each is a one-time purchase, yours for good, with no subscription, and there is a bundle of three. Like a Game Pass, a hero is paid by a new package purchase of at least its price (your sponsor and team are paid as usual and you keep the package credits for your ads); credits you already hold never buy one. When they are on sale they show on the Game Pass card in Members > Games (https://instantadpay.com/my#games) with each price; if you do not see them there, they are not on sale yet. In the game three heroes fight at a time and you pick which three at an inn, a rest spot or a dungeon camp; heroes waiting in the roster keep their gear and level and earn half experience. A bonus hero joins at your party level (at most 20) and is never stronger than the free heroes. The whole story stays free with Aldric, Sylwen and Borin.' },
|
||||
a: 'Shards of Valor has four bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid and Roland the Paladin. Kestrel is free for every player: she joins for good once a hero in your party reaches level 20, and she is not sold. Valda, Morag and Roland are each a one-time purchase, yours for good, with no subscription, and there is a bundle of those three. Like a Game Pass, a hero is paid by a new package purchase of at least its price (your sponsor and team are paid as usual and you keep the package credits for your ads); credits you already hold never buy one. When they are on sale they show on the Game Pass card in Members > Games (https://instantadpay.com/my#games) with each price; if you do not see them there, they are not on sale yet. In the game three heroes fight at a time and you pick which three at an inn, a rest spot or a dungeon camp; heroes waiting in the roster keep their gear and level and earn half experience. A bonus hero joins at your party level (at most 20) and is never stronger than the free heroes. The whole story stays free with Aldric, Sylwen and Borin.' },
|
||||
{ id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a support ticket?'], tags: ['support', 'help', 'ticket', 'contact', 'help desk'],
|
||||
re: SUPPORT_RE, handoff: true,
|
||||
a: 'Open Help in your member dashboard (https://instantadpay.com/my#help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use https://instantadpay.com/support, or email support@instantadpay.com. You can also tap "Send this to support" below and I will pass this chat along.' },
|
||||
@@ -125,7 +129,16 @@ const CANNED = [
|
||||
a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' },
|
||||
{ id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'],
|
||||
re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i,
|
||||
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus a 100-credit Featured bonus on InstantAdPay from month 4 (enough for two Featured days and more). Either site alone keeps your streak going; both sites in a cycle is the bigger bonus. The bonus stacks on Five Dollar Friday and Wired Wednesday. Another $20+/$25+ package on a site you already refueled this cycle, before your next window opens, is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in Promo tools; they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your first counted refuel also opens the Engine Room tab in your member area: three plain dials (fuel left on both sites against this cycle’s refuel with days left at your burn, clicks this week with clicks per 1,000 credits, goals this month against a goal you set), warning lights, six part lights with setup links and one next move. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Overview (with a Refuel LinkSpin link once this site is done for the cycle). Buy here: https://instantadpay.com/my#buy. The full guide, with the flow step by step: https://instantadpay.com/refuel. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
|
||||
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus a 100-credit Featured bonus on InstantAdPay from month 4 (enough for two Featured days and more). Either site alone keeps your streak going; both sites in a cycle is the bigger bonus. The bonus stacks on Five Dollar Friday and Wired Wednesday. Another $20+/$25+ package on a site you already refueled this cycle, before your next window opens, is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in Promo tools; they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your first counted refuel also opens the Engine Room tab in your member area: three plain dials (fuel left on both sites against this cycle’s refuel with days left at your burn, clicks this week with clicks per 1,000 credits, goals this month against a goal you set), warning lights, six part lights with setup links and one next move. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Overview (with a Refuel LinkSpin link once this site is done for the cycle). Buy here: https://instantadpay.com/my#buy. The full guide, with the flow step by step: https://instantadpay.com/refuel. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed. A counted refuel of $50 or more (either site) also earns you one free Downline Banners spot (downlinebanners.com, the network banner board), paid by the company and placed for your main wallet, so link a wallet to receive it.' },
|
||||
{ id: 'downline-banners', title: 'Downline Banners (network banner board)', q: ['What is Downline Banners?', 'How do I use my LinkSpin Banner Spin on Downline Banners?', 'How do I sign in to Downline Banners?'], tags: ['downline banners', 'banner board', 'spot', 'banner spin'],
|
||||
re: /(downline ?banners|banner (board|spot)|banner line)/i,
|
||||
a: 'Downline Banners (https://downlinebanners.com) is the Crypto Team Build Network banner board on Polygon. A $5 spot (paid in POL) buys 300 guaranteed views on the board and a place in one global line; when later spots sell, the contract pays the 10 spots above them and the buyer\u2019s sponsor in the same transaction. Nothing is promised: you are paid only when spots sell after yours. Signed in on InstantAdPay? Open its My Spots page and you arrive signed in as your linked wallet, and your share link uses your InstantAdPay username. In My Spots, the "Use a LinkSpin Banner Spin" button puts one of your 468x60 Banner Spins on a spot in two taps, with click tracking under a Downline Banners source on LinkSpin. A $50+ Monthly Refuel earns one free spot. To promote it: Promo tools > Network sites > Downline Banners (or downlinebanners.com/promote) has your links, creatives in every common size, lines, headlines, an email and posts, all carrying your username.' },
|
||||
{ id: 'viral-banner-blitz', title: 'Viral Banner Blitz (network banner loop)', q: ['What is Viral Banner Blitz?', 'How do I post on Viral Banner Blitz?'], tags: ['viral banner blitz', 'vbb', 'banner loop', '125x125'],
|
||||
re: /(viral ?banner ?blitz|vbb|banner loop)/i,
|
||||
a: 'Viral Banner Blitz (https://viralbannerblitz.com) is the network’s shared loop of 125x125 banners. InstantAdPay and LinkSpin members get one free post credit each day they sign in there (Sign in with InstantAdPay works). Real, verified visitors move the loop; a banner that rides out the end has cycled and earns network ad views, which are advertising, not cash. Weekly leaderboards count the visitors you send and the traffic sources they come from, with a prize pot paid in POL to the top three on each board. Your link is viralbannerblitz.com/?ref=your-username. Promo tools > Network sites > Viral Banner Blitz (or viralbannerblitz.com/promote) has your links, creatives, lines, headlines, an email and posts.' },
|
||||
{ id: 'network-sites-kits', title: 'Promo tools: Network sites', q: ['Where are the Downline Banners and Viral Banner Blitz banners?', 'How do I promote the other network sites?'], tags: ['network sites', 'promo kit', 'promote', 'creatives'],
|
||||
re: /(network sites|promo kit|promote (downline|viral|the other|network))/i,
|
||||
a: 'Members > Promo tools > Network sites shows the promo kits of Downline Banners and Viral Banner Blitz with your InstantAdPay username already in every link: your personal links, creatives in 125x125, 468x60, 728x90, 300x250, 160x600, 1200x630 and 1080x1080 (download, copy the URL or copy ready HTML that links to you), 5 short lines, 3 headlines, an email and 2 social posts. Your username works as your sponsor link on those sites even if you never visited them. Each site keeps its own kit, so the copy here is always the current one; the same kit is on each site’s Promote page. Each link also has a tracked version that goes through LinkSpin first (so the network can see which site sent the visit) and then opens the same page with your username; use either one.' },
|
||||
{ id: 'wired-wednesday', title: 'Wired Wednesday bonus', q: ['What is Wired Wednesday?', 'What happens on Wednesday?'], tags: ['wired wednesday', 'bonus credits', 'promotion'],
|
||||
re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i,
|
||||
a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' },
|
||||
@@ -163,9 +176,9 @@ const CANNED = [
|
||||
{ id: 'split', title: 'How much do I earn: the split', q: ['How much do I earn?', 'What commission do I get?', 'What is the split on a package?'], tags: ['earn', 'commission', 'split', 'percent', 'levels'],
|
||||
re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i,
|
||||
a: 'Every package splits the same way: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, 20 percent to the platform. Those numbers are constants in the contract and cannot be changed. The package ladder is on the home page. No income is promised; nobody earns unless real ad buying happens.' },
|
||||
{ id: 'network-rate', title: 'Network views and partner visits cost a quarter of the rate', q: ['Do network views use my credits?', 'How much do Network Ad Space views cost?', 'Why are network views cheaper?'], tags: ['network views', 'network ad space', 'syndication', 'passivedrip', 'partner visits', 'credits', 'rate'],
|
||||
{ id: 'network-rate', title: 'Network views and partner visits cost less than views here', q: ['Do network views use my credits?', 'How much do Network Ad Space views cost?', 'Why are network views cheaper?'], tags: ['network views', 'network ad space', 'syndication', 'passivedrip', 'partner visits', 'credits', 'rate'],
|
||||
re: /((network (views?|ad space)|syndicat\w*|partner (sites?|visits?)).{0,60}(credits?|charge[ds]?|cost|spend|balance|budget|free|pay|rate|cheap)|(credits?|charge[ds]?|cost|spend|balance|budget|pay|rate).{0,60}(network (views?|ad space)|syndicat\w*|partner (sites?|visits?)))/i,
|
||||
a: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs a quarter of the rate: 4 network views cost what 1 view here does, and 4 partner visits use up 1 visit of your pack. So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/4 rate)" lines in Credit activity.' },
|
||||
a: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs less: for a banner, 4 network views cost what 1 view here does, and 4 partner visits use up 1 visit of your pack. Text ads go further still: since November 12, 10 network views of a text ad cost what 1 view here does. So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/4 rate)" or, for text ads, "Network views (1/10 rate)" lines in Credit activity.' },
|
||||
{ id: 'balance-rule', title: 'Why my balance went down', q: ['Why did my balance go down?', 'Where did my credits go?', 'What does In live campaigns mean?'], tags: ['balance', 'credits', 'campaigns', 'credit activity'],
|
||||
re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down|ticking)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i,
|
||||
a: 'One rule: your balance is what is NOT committed to a live campaign. When you start a campaign its whole budget is set aside right then (earned credits first, then purchased), so your Available number drops once and then sits still while the ad runs. The budget spends down inside that campaign in Members > Campaigns, where you can see delivered views, network views and what is left. The dashboard shows Purchased available, Earned available and In live campaigns as three separate numbers; a paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live. Purchased credits live on the blockchain; if we ever refund or credit purchased money it shows under Purchased as "credited to you" and spends like a purchase, login ads included. Earned credits fund every format except login ads. Two formats are flat buys paid in full when booked: featured links (sold by the day) and verified-visit packs. Adding credits to a featured link does nothing, so its row offers Extend run instead, which books more days at the daily rate; a visit pack offers Buy more visits. Every credit that comes in or goes out is listed with its reason under Members > Campaigns > Credit activity (also linked from Earn credits): sign-in bonus, daily claim, video watched, verified visit, campaign buys, views delivered per day, grants and refunds. Check it before assuming credits went missing.' },
|
||||
@@ -196,7 +209,7 @@ const CANNED = [
|
||||
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: '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 2 open adoptions at a time 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 2 open adoptions, signed in within the last 7 days). Adopters take turns, so the one assigned least recently goes first.' },
|
||||
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.' },
|
||||
{ id: 'qualification', title: 'Qualification, levels 2 and 3, credits vs POL', q: ['How do I unlock level 2?', 'How does qualification work?', 'What is a pass-up?'], tags: ['qualification', 'level 2', 'level 3', 'pass-up', 'qualified start'],
|
||||
re: /(qualif|unlock level|level 2|level 3|pass.?up)/i,
|
||||
a: 'Two different things are earned here. CREDITS: every member, free ones included, earns ad credits by viewing ads, videos, visits and the daily sign-in; credits buy your own ads and are never withdrawn. POL: real crypto paid to your wallet when your referrals buy packages, once you are activated: the $20 starter package plus payouts switched on from your wallet. Level 1 pays 50 percent of the packages your direct referrals buy, from the day you are activated. Bring 2 buyers of $20 or more and level 2 unlocks; 5 unlock level 3. When a level is not qualified, its share climbs the sponsor line, checking up to 25 positions, and pays the first qualified person. Qualification never expires and cannot be bought. Qualified Start: you may link extra wallets of your own as positions under your account (Buy packages > Qualified Start); each one that buys a $20+ package counts as a qualifying buyer, its credits pool with yours, and 50% of its purchase comes back to your main wallet. Your own money, your own wallets, a faster start, never an income promise.' },
|
||||
@@ -277,9 +290,9 @@ function seeds() {
|
||||
// BONUS HEROES (2026-11-05): sold one time; while heroSales is off the assistant says they are coming soon, once on it quotes the live prices
|
||||
function heroesFact() {
|
||||
let h = null; try { h = HERO_SALE ? HERO_SALE() : null; } catch (e) { h = null; }
|
||||
const base = 'Shards of Valor bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid, Roland the Paladin. Sold ONE TIME, owned for good, never a subscription; paid by a NEW package purchase of at least the price (sponsor and team paid as usual, the member keeps the package credits); credits already held never buy one. Three heroes fight at a time, picked at an inn, rest spot or dungeon camp; the roster keeps gear and level and earns half experience. A bonus hero joins at the party level (at most 20) and is never stronger than the free heroes. The Champion and Sovereign passes no longer include a hero (the Necromancer was dropped); the Legend pass opens every bonus hero while it is active.';
|
||||
const base = 'Shards of Valor bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid, Roland the Paladin. Kestrel is FREE for every player once a hero in the party reaches level 20 (since 2026-11-14) and is NOT sold; anyone who bought her before keeps her. Valda, Morag and Roland are sold ONE TIME, owned for good, never a subscription; paid by a NEW package purchase of at least the price (sponsor and team paid as usual, the member keeps the package credits); credits already held never buy one. Three heroes fight at a time, picked at an inn, rest spot or dungeon camp; the roster keeps gear and level and earns half experience. A bonus hero joins at the party level (at most 20) and is never stronger than the free heroes. The Champion and Sovereign passes no longer include a hero (the Necromancer was dropped); the Legend pass opens every bonus hero while it is active.';
|
||||
if (!h || !h.sale) return '- BONUS HEROES (COMING SOON, not on sale yet): ' + base + ' Never quote their prices or a launch date while they are not on sale.\n';
|
||||
const each = (h.rows || []).map(r => r.name + (r.free ? ' free for everyone' : ' $' + r.usd)).join(', ');
|
||||
const each = (h.rows || []).map(r => r.name + (r.freeAt ? ' free at level ' + r.freeAt + ' (not sold)' : r.free ? ' free for everyone' : ' $' + r.usd)).join(', ');
|
||||
return '- BONUS HEROES (ON SALE, Members > Games > Game Pass card at https://instantadpay.com/my#games): ' + each + (h.bundle && h.bundle.names.length ? '; the bundle ' + h.bundle.names.join(', ') + ' $' + h.bundle.usd : '') + '. ' + base + ' The bundle is heroes only (no level cap change).\n';
|
||||
}
|
||||
function passTiersFact() {
|
||||
@@ -294,9 +307,11 @@ function passTiersFact() {
|
||||
// SYNDICATED RATE (Marty, 2026-10-27, approved 4:1) follows ads rates().synRateDivisor; the canned answer quotes 1/4, so
|
||||
// the fast path rewrites it when the admin picks another N, and the AI fact always states the live N.
|
||||
const SYN_N = () => { try { return Math.max(1, Math.floor(Number(require('./ads').synRateDivisor()) || 1)); } catch (e) { return 4; } };
|
||||
// text ads have their own N since 2026-11-12 (Marty: 1/10); the canned answer quotes 4 and 10
|
||||
const SYN_T = () => { try { return Math.max(1, Math.floor(Number(require('./ads').synRateDivisorText()) || 1)); } catch (e) { return 10; } };
|
||||
const netRateAnswer = n => n === 1 ? 'Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery uses credits at the same rate as views and visits here.'
|
||||
: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs 1/' + n + ' of the rate: ' + n + ' network views cost what 1 view here does, and ' + n + ' partner visits use up 1 visit of your pack. So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/' + n + ' rate)" lines in Credit activity.';
|
||||
function synFact() { const n = SYN_N(); return '- NETWORK RATE (live, Marty 2026-10-27): delivery ON instantadpay.com is charged at the normal rate. Network Ad Space impressions of banner/text ads cost 1/' + n + ' of the on-site rate (' + n + ' network views = the price of 1 view here; credit log line "Network views (1/' + n + ' rate)"), and PassiveDrip partner visits use up 1 visit of a pack per ' + n + ' partner visits. The budget is the limit, burns follow what was charged, nothing charged before 2026-10-27 changed. AdRevLinks popups and DripOffers clicks are not charged. Game refuels and Spooky Doors are charged as normal visits.' + String.fromCharCode(10); }
|
||||
: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs 1/' + n + ' of the rate: ' + n + ' network views of a banner cost what 1 view here does, and ' + n + ' partner visits use up 1 visit of your pack.' + (SYN_T() !== n ? ' Text ads: ' + SYN_T() + ' network views cost what 1 view here does.' : '') + ' So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/' + n + ' rate)" lines in Credit activity.';
|
||||
function synFact() { const n = SYN_N(); return '- NETWORK RATE (live, Marty 2026-10-27): delivery ON instantadpay.com is charged at the normal rate. Network Ad Space impressions of BANNER ads cost 1/' + n + ' of the on-site rate (' + n + ' network views = the price of 1 view here; credit log line "Network views (1/' + n + ' rate)"); TEXT ads have their own network rate since 2026-11-12 (Marty): 1/' + SYN_T() + ' of the on-site text rate (' + SYN_T() + ' network views = the price of 1 view here, so 1 credit = ' + (10 * SYN_T()) + ' network text views at the default 1 credit per 10 views; credit log line "Network views (1/' + SYN_T() + ' rate)"), going forward only; and PassiveDrip partner visits use up 1 visit of a pack per ' + n + ' partner visits. The budget is the limit, burns follow what was charged, nothing charged before 2026-10-27 changed. AdRevLinks popups and DripOffers clicks are not charged. Game refuels and Spooky Doors are charged as normal visits.' + String.fromCharCode(10); }
|
||||
// the refuel fact follows the refuelStreak switch: while it is off the assistant says it is not live yet (2026-10-24)
|
||||
let REFUEL_ON = () => false;
|
||||
// POL Miner (2026-10-28) follows site config gamesLive: until 'polminer' is in it the assistant only says it is coming soon
|
||||
@@ -334,13 +349,14 @@ const gpWithTd = a => tdLive() ? String(a).replace('plus one free supply crate e
|
||||
function sovTestFact() { return GAME_LIVE && GAME_LIVE('shardsofvalor') ? '- SHARDS OF VALOR (OPEN TESTING since Nov 6, https://shardsofvalor.com, Members > Games > Shards of Valor > Play): a pixel adventure RPG for many players at once; lead three heroes across the islands, help the townspeople, fight in the dungeons and recover the eight Shards of Valor. It is in open testing: anyone can play it now, but it is NOT live and pays NO POL until a launch date is set; there is no launch date yet. ALL TESTING PROGRESS IS WIPED AT LAUNCH (heroes, levels, gold and items start fresh), because this phase is only for finding bugs. Never promise a date or a payout. Ask testers to report bugs through Support.\n' : ''; }
|
||||
function turkeydropFact() { return tdLive() ? '- TURKEY DROP (Thanksgiving season game, https://turkeydropgame.com, Members > Games; open Nov 2 through Nov 30 Central, its Games card shows a "Limited time, ends Nov 30" ribbon and is gone after): a free 70s-cartoon arcade game. The WFWL 98.7 radio helicopter drops turkeys over the mall; the player swings a net to catch them before they splat; too many splats and the station pulls them off the air. One-tap sign-in with the InstantAdPay account. PAYS POL: the first time a player reaches each score milestone, plus a weekly top-3 leaderboard POL prize. POL collects in the Turkey Drop balance and is paid automatically to the wallet linked on InstantAdPay. BACK ON THE AIR: after being pulled off the air, a short verified sponsor visit (charged to the advertiser like any game refuel visit) gives one extra life; gameplay only, never POL. Game Pass perk: one free back-on-the-air extra life every day. Never state amounts, caps, totals or a season budget.\n' : tdOver() ? '- TURKEY DROP: the Thanksgiving season game (Nov 2 to 30) has ENDED; say the season is over and point to the other games.\n' : '- TURKEY DROP: COMING SOON, not open yet. Never send members to turkeydropgame.com; say it is coming soon to the Games tab, and do not bring it up unless asked.\n'; }
|
||||
function polminerFact() { return pmLive() ? '- POL MINER (https://polminer.com, Members > Games): a free dig-down mining game. Dig, sell ore for coins, upgrade pick/lamp/cart/thruster, beat a drill boss every 30 m. Pink Polygon crystals pay a random POL amount the first time each one is dug out; each boss pays POL on its first win per account; first trips to 50/100/150/200 m pay POL. Coins never turn into POL. Guests can play and collect at sign-in. POL is paid automatically to the wallet linked on InstantAdPay. The SUPPLY pad opens a sponsored supply crate (full lamp + coins, never POL) after a short sponsor visit.\n' : '- POL MINER: COMING SOON, not open yet. Never send members to polminer.com; say it is coming soon to the Games tab.\n'; }
|
||||
function refuelFact() { return REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus a 100-credit Featured bonus on InstantAdPay at m4+ (purchased-grade credits, any format). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: another $20+/$25+ package on a site already refueled this cycle, before the next window opens (the other site's first package in the cycle is the second engine instead) = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. ENGINE ROOM: unlocked by the first counted refuel (greyed 'Refuel to start your engine' before), IAP tab Engine Room + LinkSpin Ads screen panel, same data both sites: dials Fuel left (credits free + in campaigns on both sites vs this cycle's refuel credits incl. bonus, days left at the recent burn), Clicks this week (vs last week, clicks per 1,000 credits), Goals this month (conversion pixel conversions since the 1st Central vs the member's own goal); streak panel; warning lights (ads at 80%, ads out, refuel day coming, login slot open); six part lights (fuel, banner spin, spin link, page, testing, conversion tracking: green working, amber needs attention, grey not started with a Set it up link); one Next move button from simple rules. REFUEL KIT: each counted refuel unlocks the Central-month's members-only banner set for this site's own program (5 sizes, personalized server-side with @username + QR to the member's link; IAP: Promo tools card with Use in an IAP banner campaign; LinkSpin: Ads screen card with Load into my Banner Spin); kits stay usable after the month; streak month 3+ adds an animated GIF, month 6+ a BannerKitAI custom-banners credit (coming, entitlement saved). Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Either site alone keeps the streak (one-engine rates); both sites in one cycle = the bigger bonus; never say both are required. MEMBER GUIDE PAGE (public, 2026-10-24): /refuel on both sites (https://instantadpay.com/refuel and https://linkspin.app/refuel): the flow, the numbers, the member steps, leader coaching and FAQ; point members there for the full picture. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package. ROUTES (2026-10-25): LinkSpin menu item Refuel = https://linkspin.app/credits#refuel (the Refuel panel, scrolled to and highlighted); packages of $25+ there are marked counts for Refuel; https://linkspin.app/credits#buy = the package picker; https://linkspin.app/ads#engine = LinkSpin Engine Room. InstantAdPay Engine Room = https://instantadpay.com/my#engine; its Set up conversion tracking opens https://instantadpay.com/my#conversions (Campaigns > Conversion tracking card, same goals LinkSpin counts). Engine Room links that cross to LinkSpin (Banner Spin, spin link, page, testing, refuel LinkSpin) open LinkSpin with a note at the top naming the job, Step 1, a guide link and Back to InstantAdPay; same email signs in on both.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'; }
|
||||
function refuelFact() { return "- DOWNLINE BANNERS (LIVE 2026-11-13, https://downlinebanners.com, contract verified on Polygonscan): network banner board; a $5 spot in POL = 300 guaranteed views + a place in one line; the contract pays the 10 spots above and the buyer's sponsor when later spots sell; nothing promised. InstantAdPay sign-in carries members in as their linked wallet; share links use the InstantAdPay username; My Spots has a 'Use a LinkSpin Banner Spin' button. A counted Monthly Refuel of $50+ (either site) earns one free spot for the member's main wallet, paid by the company (no wallet linked = no spot).\n" + (REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus a 100-credit Featured bonus on InstantAdPay at m4+ (purchased-grade credits, any format). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: another $20+/$25+ package on a site already refueled this cycle, before the next window opens (the other site's first package in the cycle is the second engine instead) = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. ENGINE ROOM: unlocked by the first counted refuel (greyed 'Refuel to start your engine' before), IAP tab Engine Room + LinkSpin Ads screen panel, same data both sites: dials Fuel left (credits free + in campaigns on both sites vs this cycle's refuel credits incl. bonus, days left at the recent burn), Clicks this week (vs last week, clicks per 1,000 credits), Goals this month (conversion pixel conversions since the 1st Central vs the member's own goal); streak panel; warning lights (ads at 80%, ads out, refuel day coming, login slot open); six part lights (fuel, banner spin, spin link, page, testing, conversion tracking: green working, amber needs attention, grey not started with a Set it up link); one Next move button from simple rules. REFUEL KIT: each counted refuel unlocks the Central-month's members-only banner set for this site's own program (5 sizes, personalized server-side with @username + QR to the member's link; IAP: Promo tools card with Use in an IAP banner campaign; LinkSpin: Ads screen card with Load into my Banner Spin); kits stay usable after the month; streak month 3+ adds an animated GIF, month 6+ a BannerKitAI custom-banners credit (coming, entitlement saved). Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Either site alone keeps the streak (one-engine rates); both sites in one cycle = the bigger bonus; never say both are required. MEMBER GUIDE PAGE (public, 2026-10-24): /refuel on both sites (https://instantadpay.com/refuel and https://linkspin.app/refuel): the flow, the numbers, the member steps, leader coaching and FAQ; point members there for the full picture. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package. ROUTES (2026-10-25): LinkSpin menu item Refuel = https://linkspin.app/credits#refuel (the Refuel panel, scrolled to and highlighted); packages of $25+ there are marked counts for Refuel; https://linkspin.app/credits#buy = the package picker; https://linkspin.app/ads#engine = LinkSpin Engine Room. InstantAdPay Engine Room = https://instantadpay.com/my#engine; its Set up conversion tracking opens https://instantadpay.com/my#conversions (Campaigns > Conversion tracking card, same goals LinkSpin counts). Engine Room links that cross to LinkSpin (Banner Spin, spin link, page, testing, refuel LinkSpin) open LinkSpin with a note at the top naming the job, Step 1, a guide link and Back to InstantAdPay; same email signs in on both.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'); }
|
||||
const REFUEL_OFF_ANSWER = 'The Monthly Refuel streak (bonus ad credits for refueling every month, more when you refuel both InstantAdPay and LinkSpin) is built but not switched on yet, so nothing counts toward it today. The bonuses running now are Five Dollar Friday and Wired Wednesday on InstantAdPay. When the streak goes live, your Refuel card will show your refuel day.';
|
||||
function systemPrompt(kbBlock) {
|
||||
return `You are the assistant on InstantAdPay (https://instantadpay.com), a membership advertising platform.
|
||||
|
||||
FACTS:
|
||||
- LEVEL 4 OVERRIDE (LIVE 2026-10-26, first payout Monday 2026-11-02): company-paid, off-chain decision, on-chain payment. 3% of every package purchase (the POL actually paid) goes to the buyer's 4th upline on the contract sponsor chain if that member's contract buyerCount is 5 or more (qualifying buyer = direct referral with a $20+ purchase, same bar as level 3); otherwise it hunts up to the next qualified upline, max 25 hops; the company account (#1) or no qualified upline = company keeps it; exactly one recipient per purchase. Paid weekly in POL every Monday after 9 AM Central for the previous Monday to Sunday Central week, from a company payer wallet via the contract's award(memberId), shown in Earnings as 'Level 4 override' with a Polygon link and announced by email and an on-site notice. Under 0.01 POL carries to the next week. Purchases from the start date only, no back pay. Funded from the platform's 20%; the contract split 50/20/10 is unchanged. Never promise amounts.
|
||||
- NETWORK SIGN-IN (built 2026-11-12): one sign-in for InstantAdPay and LinkSpin, same email on both. A member signed in on one site who follows a link from inside their account to the other (Engine Room, Refuel, Back to InstantAdPay) arrives signed in with no email code; opening the other site's sign-in screen while signed in here also signs them in by itself (one quiet try per browser every 30 minutes). Exception: when the account on the receiving site does not exist yet or is still a waiting account (never signed in), they get the normal email code once, email prefilled. Sign-out is per site and switches the automatic sign-in off on that site for 12 hours (a deliberate link from the other site still works). Sessions are ordinary member sessions (4 hours), the admin portal is never shared, and the sign-in grants nothing extra: purchases, payouts and wallet actions still need the wallet. If it fails, the email code always works.
|
||||
- EARNERS CORNER (LIVE 2026-11-10, https://earnerscorner.com): the network's own forum (Discourse) for people who earn online: business opportunities, PTC, traffic exchanges and mailers, crypto earning and wallets, affiliate marketing, tools, plus an Our Network section. Read is open to everyone; posting needs signing in with the InstantAdPay account (no separate forum password). New accounts' first posts are reviewed; links unlock with trust and are open from day one for members with an on-chain position; referral links only in Promote Your Program; AI spam detection; a forum assistant answers network questions from the same official knowledge and links threads.
|
||||
- STACK POL (LIVE 2026-11-09, https://stackpol.com): one site that adds up every POL payout in the network (InstantAdPay and LinkSpin TierPaid referral payments plus every game's payouts), refreshed every 5 minutes, with per-program pages (/earn/<program>), a public ledger showing each payout's username and Polygonscan link, and a blog. Members get a public page at stackpol.com/<username> by switching on 'Show my Stack POL page' in Promo tools > Stack POL; it is ON by default for every paid member (since 2026-11-09) and off only when they switch it off. It never holds money. STACK POL PRO (2026-11-09): one-time unlock, NEW MONEY only: ANY package of $10 or more bought by the member's own position unlocks it automatically (since 2026-11-09 evening, no order step); credits never count; it never uses up a package that also fulfils a Game Pass or hero order. Pro pages show the member's own LinkSpin Banner Spins in the ad spots (network zones otherwise), their spin links, a purple QR code to the page, a 'Want a personalized page like this?' button, and articles opened from the page (?ref=<username>) use the member's referral on every call to action. Pro owners get the Stack POL Pro badge. Totals are past payouts, never a promise of earnings.
|
||||
${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${warpwaresFact()}${bixFact()}${turkeydropFact()}${sovTestFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref=<username> link.
|
||||
@@ -354,7 +370,7 @@ ${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${w
|
||||
- Free to join with email only (6-digit code sign-in, no passwords). Wallet appears only at purchase or payout activation. Every new member gets a small welcome batch of ad credits — unlocked by the WELCOME TOUR on first sign-in: they visit their upline's line-banner sites (up to 3, 10 seconds each — the same 3 levels the contract pays), then claim the credits. Members with no upline banners get the credits instantly.
|
||||
- SPONSOR ATTRIBUTION: last touch. The invite link opened most recently sets the sponsor (30-day cookie), shown on the join page and again at the code step ("Joining under @name"). It locks when the account is created; the contract binds the buyer to that sponsor at their first purchase. Wrong sponsor before joining: open the right link. Already joined wrong: admin can move the account before the first purchase.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
@@ -364,10 +380,11 @@ ${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${w
|
||||
- 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.
|
||||
- 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.
|
||||
- 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 2 open adoptions, 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.
|
||||
- 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 (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.
|
||||
- TANK ACTIVATION HOLD (2026-10-27, Marty: never default a tank member to the company): a tank member (no sponsor, not activated) can NOT switch on payouts on its own yet (a PURCHASE is NEVER held, Marty 2026-10-27: with no sponsor anywhere a buy goes ahead under the catch position #1); the Wallet tab and Getting started card say "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours)." with the time left, and the activate button is hidden. The 24-hour clock starts when they link a wallet; they then show at the top of every holding tank with a green "Ready to activate" badge and hours left, and a post goes to the team's Telegram payments topic. If nobody adopts them in 24 hours, the site auto-assigns them to the next eligible adopter in rotation (own $20+ package, fewer than 2 open adoptions, signed in within 7 days, not suspended; least recently auto-assigned first); the adopter gets a chat + email and Telegram shows the pickup marked (auto-assigned). If nobody is eligible they stay on hold and the admin is alerted; never the company. Someone whose same email or wallet already has a sponsor on LinkSpin is placed under that sponsor instead (not one they were released or rescued from). A member who arrived through a sponsor link is never held. Once they have a sponsor the hold lifts by itself. ONE-TAP SWITCH ON PAYOUTS (2026-10-27): every tank assignment (manual adoption or the 24-hour auto-assign) sends the member a chat and an email with a Switch on payouts link, https://instantadpay.com/my?activate=1#wallet; it opens the Wallet tab and starts the normal Activate payouts flow with the new sponsor prefilled (after sign-in, and after linking a wallet if none is linked yet). It never starts while the hold applies or when no sponsor resolves. The site cannot activate for anyone: activation is one free transaction from the member's own wallet. Not activated 24 hours after the assignment: one reminder email to the member with the same link and one notice to the sponsor ("@x hasn't switched on payouts yet; a nudge from you helps"); at 72 hours one last email to the member only; both stop once the member switches on payouts or buys.
|
||||
- TANK ACTIVATION HOLD (2026-10-27, Marty: never default a tank member to the company): a tank member (no sponsor, not activated) can NOT switch on payouts on its own yet (a PURCHASE is NEVER held, Marty 2026-10-27: with no sponsor anywhere a buy goes ahead under the catch position #1); the Wallet tab and Getting started card say "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours)." with the time left, and the activate button is hidden. The 24-hour clock starts when they link a wallet; they then show at the top of every holding tank with a green "Ready to activate" badge and hours left, and a post goes to the team's Telegram payments topic. If nobody adopts them in 24 hours, the site auto-assigns them to the next eligible adopter in rotation (own $20+ package, fewer than 10 people held from the tank who have not switched on payouts yet, signed in within 7 days, not suspended; least recently auto-assigned first); the adopter gets a chat + email and Telegram shows the pickup marked (auto-assigned). If nobody is eligible they stay on hold and the admin is alerted; never the company. Someone whose same email or wallet already has a sponsor on LinkSpin is placed under that sponsor instead (not one they were released or rescued from). A member who arrived through a sponsor link is never held. Once they have a sponsor the hold lifts by itself. ONE-TAP SWITCH ON PAYOUTS (2026-10-27): every tank assignment (manual adoption or the 24-hour auto-assign) sends the member a chat and an email with a Switch on payouts link, https://instantadpay.com/my?activate=1#wallet; it opens the Wallet tab and starts the normal Activate payouts flow with the new sponsor prefilled (after sign-in, and after linking a wallet if none is linked yet). It never starts while the hold applies or when no sponsor resolves. The site cannot activate for anyone: activation is one free transaction from the member's own wallet. Not activated 24 hours after the assignment: one reminder email to the member with the same link and one notice to the sponsor ("@x hasn't switched on payouts yet; a nudge from you helps"); at 72 hours one last email to the member only; both stop once the member switches on payouts or buys.
|
||||
- DAILY CLAIM STREAK: finishing the daily ad set and claiming pays 5 credits on day 1, 7 on day 2, 10 from day 3, and 25 on every 7th consecutive day; miss a day and it restarts. After the set, verified visits (up to 20 a day, 1 credit each) keep earning, and the credits are meant to be spent on a campaign.
|
||||
- FOUR-MINUTE OVERVIEW VIDEO (2026-09-16): 'InstantAdPay in four minutes' is the first card on Members > Training (group 'Start here') and embedded on the home page at instantadpay.com/#overview-video (hero button 'Watch the 4-minute overview'). Send it to anyone asking what the platform is; the tab-by-tab walkthrough videos on Training go deeper. It is evergreen: no dates, no launch talk.
|
||||
- ANTI-FRAUD CHECKS (2026-09-16): at sign-up the site records IP, browser type and a browser cookie id. A second account from a browser that already has one is refused, so is a burst of new accounts from one connection in a day, and so is a sign-up through an invite link whose owner used that same browser. A sign-up from the same IP as the sponsor is allowed but flagged (households are fine). Flagged accounts never count on the leaderboard and cannot adopt from the holding tank; a suspended account cannot sign in. If a member says they were refused at sign-up, or asks how to get a second account to qualify themselves: one account per person, sign in to the existing one, and use QUALIFIED START (Buy packages tab) to link extra wallets of their own as positions under that account; each linked wallet that buys $20+ counts as one of their qualifying buyers, credits pool, and half of each such purchase returns to their main wallet. Levels 2 and 3 open at 2 and 5 qualifying buyers whether those buyers are referrals or the member's own linked positions. Shared computer at work or a library: contact support. Never suggest a second account.
|
||||
@@ -381,6 +398,9 @@ ${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${w
|
||||
- PIPELINE (live since 2026-09-15): a follow-up board on the dashboard, tab 'Pipeline' between My line and Buy packages, with its own training video on the Training tab. Columns: Talking to, Joined, Wallet linked, Payouts on, Bought, Building, Later. Prospects (from the My line prospect list) and directs are placed automatically from what they have actually done (coaching rung, on-chain buys); nobody drags cards. The sponsor adds a note, a follow-up date and a tag (hot, later, no response, not interested); a 'Follow up today' strip lists due cards; stalled cards (quiet 3+ days) are flagged; each card carries the message for its exact stage with 'Open chat with this message' (member chat) or copy.
|
||||
- LEADER TOOLS (since 2026-10-16): a 'Leader tools' section on the Training tab with the Leader's Guide (a downloadable PDF: building wide, how width unlocks levels 2 and 3, network reach, Qualified Start, LinkSpin, the wallet as your key, the first week), the narrated presentation to share, and the Build wide video. My line and Pipeline each have a Leader tools card with a direct 'Download the Leader's Guide (PDF)' button and 'Open Leader tools'.
|
||||
- UNACTIVATED SPONSOR = WALK UP, NEVER HOLD (2026-09-16, Marty): if a buyer's sponsor has not linked a wallet or switched on payouts, the purchase is NOT held. The site walks the sponsor line upward to the first upline who is activated with payouts on and the buy goes through under them (on-chain sponsorship for that buyer is then theirs, permanently); if nobody in the line is activated it goes under the company catch position (#1). The buyer sees a one-line notice and proceeds; once the position exists on the chain the skipped sponsor gets a blunt email + on-site message (they lost this referral for good, how to switch on payouts) and the upline who was paid gets a message that the referral is theirs permanently with a nudge to coach the one who missed it; the referral MOVES to whoever got paid (the account's stored sponsor is re-pointed when the position is created on-chain), so the buyer leaves the skipped sponsor's My line for good; the skipped sponsor can never earn from that wallet. Only a transient chain error ('rpc') still pauses a buy ("try again in a minute").
|
||||
- CHASING UNICORNS (2026-11-12): a promo tool at instantadpay.com/chasing-unicorns (Members > Promo tools > 'Chasing Unicorns: the scam-spotting game', copy your own link, which ends in ?ref=<your username> so a join counts for you). It is a clearly labeled training simulation: a fake 'UnicornYield Pro' dashboard (ticking balance, countdown, fake cash-out popups, VIP upgrade, connect-wallet airdrop) where every button reveals one of 8 scam red flags and scores the visitor's 'scam radar'; then it shows what chasing scams costs and how InstantAdPay works instead, with a free join button. Nothing on the fake dashboard is real or touches any account. Made for people still waiting on a payout from another site.
|
||||
- YOUR DIRECTS' DETAILS (2026-11-12): in Members > My line > 'Your line', each person who joined through your link shows their email (with a copy button), where they came from (the referring site and the link's source tag, e.g. 'from mailer.gold/mailergold'; 'no referring site' when the browser hid it; accurate source tags start 2026-11-12, older sign-ups mostly read 'no referring site') and how they joined (your invite link, your bridge page, a link version, a game, came over from LinkSpin, moved over from BTC4Hits). The same email + origin show in the Activity drop-down and the three-level downline card for your directs. Levels 2 and 3 never show emails: they belong to their own sponsor's direct relationship. The search box also matches email and source.
|
||||
- FIND A MEMBER (2026-11-12): every member list on My line (Your line, the three-level downline, the Holding tank) has a search box at the top of its sort/filter bar. Type part of a name, username (with or without @), email or member number and the list narrows as you type, starting on page 1; it works together with the sort and the filter chips. Emails only show (and match) for your own level 1.
|
||||
- DRILL DOWN FROM THE OVERVIEW (2026-09-15): every name chip in 'Your line at a glance' on the Overview is clickable; it jumps to My line with that person's Activity panel already open and the row highlighted.
|
||||
- VISIT PACKS ARE PAID UP FRONT (2026-09-15, Michael's question): a verified-visits campaign charges the whole pack when it is created (3 credits per visit, so 1,000 visits = 3,000 credits) and then delivers over time as members complete verified visits (each member can do at most 20 a day, so packs fill gradually: tens per day at today's size). The Campaigns row shows 'paid up front' and 'N of M visits delivered'; the credits are not being consumed again, they were reserved once. Same for featured-day bookings: a featured link is a flat buy (featuredPerDay credits per day, whole run charged when booked), its row shows 'paid up front', the day count and 'runs through <date>', and it ends on its last day ('run ended'). FEATURED CANNOT TAKE ADDED CREDITS (2026-09-16, Hugh and Michael both tried): the row offers 'Extend run' which books more days after the current run (or from today if it ended) and charges them right away; there is no 'Buy more views' on a featured row any more. Visit packs offer 'Buy more visits' (charged now, adds to the pack). Credits added to a campaign are set aside immediately (Available drops at once) and whatever is unspent returns to Available when the campaign ends.
|
||||
- BANNER CREATIVE MUST BE AN IMAGE LINK (2026-09-16): the New campaign image field needs a direct image URL (ends in .png/.jpg/.gif/.webp/.svg) or an upload; a web-page link (a join page, an imgbb/ibb.co page) is refused with a message. Easiest source: Promo tools > Banners > Copy image URL. A campaign created with a page link before this check served a broken banner and was repaired by admin.
|
||||
@@ -500,7 +520,7 @@ async function answerRaw(message, historyText) {
|
||||
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return c.id === 'refuel' && !REFUEL_ON() ? { reply: REFUEL_OFF_ANSWER, canned: true } : c.id === 'polminer' && !pmLive() ? { reply: POLMINER_SOON_ANSWER, canned: true } : c.id === 'turkeydrop' && !tdLive() ? { reply: tdAnswer(), canned: true } : c.id === 'game-pass' ? { reply: gpWithTd(c.a), canned: true } : c.id === 'network-rate' && SYN_N() !== 4 ? { reply: netRateAnswer(SYN_N()), canned: true } : Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||
if (hit && (hit.id === 'warpwares' || hit.id === 'c-warpwares') && !wwLive()) return { reply: wwAnswer(), canned: true, kb: hit.id };
|
||||
if (hit && isBixId(hit.id) && !bixLive()) return { reply: BIX_SOON_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'network-rate' || hit.id === 'c-network-rate') && SYN_N() !== 4) return { reply: netRateAnswer(SYN_N()), canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'network-rate' || hit.id === 'c-network-rate') && (SYN_N() !== 4 || SYN_T() !== 10)) return { reply: netRateAnswer(SYN_N()), canned: true, kb: hit.id };
|
||||
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
|
||||
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return c.id === 'refuel' && !REFUEL_ON() ? { reply: REFUEL_OFF_ANSWER, canned: true } : c.id === 'polminer' && !pmLive() ? { reply: POLMINER_SOON_ANSWER, canned: true } : c.id === 'warpwares' && !wwLive() ? { reply: wwAnswer(), canned: true } : isBixId(c.id) && !bixLive() ? { reply: BIX_SOON_ANSWER, canned: true } : c.id === 'network-rate' && SYN_N() !== 4 ? { reply: netRateAnswer(SYN_N()), canned: true } : Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||
// retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far)
|
||||
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
// Database-backed data documents (Marty 2026-11-13, standing rule: "everything database-driven ... files only for early
|
||||
// prototyping"). Every *.json / *.jsonl data document under DATA_DIR that a module reads or writes with the fs *Sync calls lives
|
||||
// in MySQL instead of on the volume: table `docs` (name = path relative to DATA_DIR, body LONGTEXT, updated_at). The modules keep
|
||||
// their code; install() routes their fs calls on those paths to an in-memory copy that init() loads from MySQL at boot, and every
|
||||
// change is written through to MySQL (coalesced per document, newest body wins, in order, retried until it lands).
|
||||
//
|
||||
// One writer at a time: init() claims the `docs_writer` row; an older app copy still running during a deploy finds the row taken
|
||||
// and stops writing (logged), so it can never put stale data over the new copy's (the 2026-11-13 rotator.json loss).
|
||||
// First boot: a document missing from MySQL is imported from its file, and the file is renamed <name>.imported-<date> (kept, not
|
||||
// read again). Files the volume keeps on purpose: KEEP (rebuildable caches, uploads, images, the geo database, queues read by
|
||||
// listing a folder). The SAME file ships in InstantAdPay and LinkSpin.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const KEEP_FILES = new Set(['chain-index.json']); // a rebuildable cache of the blockchain
|
||||
const KEEP_DIRS = ['uploads', 'geo', 'refuel-pending', 'backups', 'marks', 'kits', 'kitimg']; // binary files, or folders read by listing
|
||||
const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, renameSync: fs.renameSync,
|
||||
unlinkSync: fs.unlinkSync, statSync: fs.statSync, appendFileSync: fs.appendFileSync };
|
||||
|
||||
let ROOT = null, pool = null, ME = crypto.randomBytes(8).toString('hex'), ready = false, writer = true;
|
||||
const cache = new Map(); // name -> { body: string, at: ms }
|
||||
const pending = new Map(); // name -> body string | null (delete)
|
||||
let flushing = false, timer = null;
|
||||
const stats = { writes: 0, deletes: 0, refused: 0, errors: 0, imported: 0, lastError: null };
|
||||
|
||||
function nameOf(p) {
|
||||
if (!ROOT || typeof p !== 'string' || !/\.jsonl?$/i.test(p)) return null;
|
||||
const abs = path.resolve(p); if (!abs.startsWith(ROOT + path.sep)) return null;
|
||||
const rel = abs.slice(ROOT.length + 1).split(path.sep).join('/');
|
||||
if (KEEP_FILES.has(rel) || KEEP_DIRS.some(d => rel === d || rel.startsWith(d + '/'))) return null;
|
||||
return rel;
|
||||
}
|
||||
const enoent = p => { const e = new Error("ENOENT: no such file or directory, open '" + p + "'"); e.code = 'ENOENT'; e.errno = -2; e.path = p; return e; };
|
||||
const enc = o => (typeof o === 'string' ? o : o && o.encoding) || null;
|
||||
|
||||
function put(name, body) { cache.set(name, { body, at: Date.now() }); pending.set(name, body); kick(); }
|
||||
function drop(name) { cache.delete(name); pending.set(name, null); kick(); }
|
||||
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}); }, 300); }
|
||||
|
||||
async function flush() {
|
||||
if (!pool || flushing || !pending.size) return;
|
||||
flushing = true;
|
||||
try {
|
||||
for (const [name, body] of [...pending]) {
|
||||
if (pending.get(name) !== body) continue; // replaced while we were busy: the newer body goes next round
|
||||
if (!writer) { pending.delete(name); stats.refused++; continue; }
|
||||
const c = await pool.getConnection();
|
||||
try {
|
||||
await c.beginTransaction();
|
||||
const [[w]] = await c.query('SELECT owner FROM docs_writer WHERE id = 1 FOR UPDATE');
|
||||
if (!w || w.owner !== ME) { await c.rollback(); writer = false; pending.delete(name); stats.refused++; console.error('docstore: another app copy took over writing; this copy stops writing'); continue; }
|
||||
if (body === null) { await c.query('DELETE FROM docs WHERE name = ?', [name]); stats.deletes++; }
|
||||
else { await c.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = VALUES(updated_at)', [name, body, Date.now()]); stats.writes++; }
|
||||
await c.commit();
|
||||
if (pending.get(name) === body) pending.delete(name);
|
||||
} catch (e) { try { await c.rollback(); } catch (x) {} stats.errors++; stats.lastError = String(e.message).slice(0, 200); console.error('docstore write', name, e.message); }
|
||||
finally { c.release(); }
|
||||
}
|
||||
} finally { flushing = false; if (pending.size) setTimeout(() => flush().catch(() => {}), 1000); }
|
||||
}
|
||||
|
||||
// Route the fs *Sync calls on data documents. Installed before any module runs; until init() the documents read from disk.
|
||||
function install(dataDir) {
|
||||
if (ROOT) return; ROOT = path.resolve(dataDir);
|
||||
fs.readFileSync = function (p, o) {
|
||||
if (!ready && process.env.DOCSTORE_URL && nameOf(p)) console.error('docstore: read before init', p, new Error().stack.split('\n')[2]);
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.readFileSync.apply(fs, arguments);
|
||||
const d = cache.get(n); if (!d) throw enoent(p);
|
||||
return enc(o) ? d.body : Buffer.from(d.body, 'utf8');
|
||||
};
|
||||
fs.existsSync = function (p) { const n = ready ? nameOf(p) : null; return n ? cache.has(n) : O.existsSync.apply(fs, arguments); };
|
||||
fs.writeFileSync = function (p, data, o) {
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.writeFileSync.apply(fs, arguments);
|
||||
const flag = o && typeof o === 'object' ? o.flag : null;
|
||||
const s = Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
|
||||
put(n, flag && flag[0] === 'a' ? ((cache.get(n) || {}).body || '') + s : s);
|
||||
};
|
||||
fs.appendFileSync = function (p, data) {
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.appendFileSync.apply(fs, arguments);
|
||||
put(n, ((cache.get(n) || {}).body || '') + (Buffer.isBuffer(data) ? data.toString('utf8') : String(data)));
|
||||
};
|
||||
fs.renameSync = function (a, b) {
|
||||
const nb = ready ? nameOf(b) : null; const na = ready ? nameOf(a) : null;
|
||||
if (!nb && !na) return O.renameSync.apply(fs, arguments);
|
||||
let body;
|
||||
if (na) { const d = cache.get(na); if (!d) throw enoent(a); body = d.body; drop(na); }
|
||||
else { body = O.readFileSync.call(fs, a, 'utf8'); try { O.unlinkSync.call(fs, a); } catch (e) {} }
|
||||
if (nb) put(nb, body); else O.writeFileSync.call(fs, b, body);
|
||||
};
|
||||
fs.unlinkSync = function (p) { const n = ready ? nameOf(p) : null; if (!n) return O.unlinkSync.apply(fs, arguments); if (!cache.has(n)) throw enoent(p); drop(n); };
|
||||
fs.statSync = function (p, o) {
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.statSync.apply(fs, arguments);
|
||||
const d = cache.get(n); if (!d) { if (o && o.throwIfNoEntry === false) return undefined; throw enoent(p); }
|
||||
const size = Buffer.byteLength(d.body, 'utf8'); const t = new Date(d.at);
|
||||
return { size, mtimeMs: d.at, mtime: t, ctime: t, birthtime: t, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false };
|
||||
};
|
||||
}
|
||||
|
||||
// Connect, claim writing, load every document, import files MySQL does not have yet. Throws if MySQL is unreachable: the app
|
||||
// must not run on an empty copy.
|
||||
async function init(opts) {
|
||||
const url = String(process.env.DOCSTORE_URL || '').trim();
|
||||
if (!url) { console.log('docstore: no DOCSTORE_URL, documents stay files (prototype mode)'); return false; }
|
||||
const mysql = require('mysql2/promise');
|
||||
pool = mysql.createPool({ uri: url, connectionLimit: 6, charset: 'utf8mb4' });
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS docs (name VARCHAR(190) PRIMARY KEY, body LONGTEXT NOT NULL, updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS docs_writer (id TINYINT PRIMARY KEY, owner VARCHAR(40) NOT NULL, at BIGINT NOT NULL) ENGINE=InnoDB');
|
||||
await pool.query('INSERT INTO docs_writer (id, owner, at) VALUES (1, ?, ?) ON DUPLICATE KEY UPDATE owner = VALUES(owner), at = VALUES(at)', [ME, Date.now()]);
|
||||
const [rows] = await pool.query('SELECT name, body, updated_at FROM docs');
|
||||
for (const r of rows) cache.set(r.name, { body: r.body, at: Number(r.updated_at) });
|
||||
for (const sp of (opts && opts.splits) || []) await openSplit(sp);
|
||||
// first boot for any document: import its file, then set the file aside
|
||||
const stamp = new Date().toISOString().slice(0, 10);
|
||||
const walk = dir => { let out = []; let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) {} for (const e of ents) { const p = path.join(dir, e.name); if (e.isDirectory()) out = out.concat(walk(p)); else out.push(p); } return out; };
|
||||
for (const p of walk(ROOT)) {
|
||||
const n = nameOf(p); if (!n || cache.has(n)) continue;
|
||||
const body = O.readFileSync.call(fs, p, 'utf8');
|
||||
if (/\.json$/i.test(n) && body.trim()) { try { JSON.parse(body); } catch (e) { throw new Error('docstore: ' + n + ' is not valid JSON; fix or move it before switching to MySQL'); } }
|
||||
await pool.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [n, body, Date.now()]);
|
||||
const [[got]] = await pool.query('SELECT body FROM docs WHERE name = ?', [n]);
|
||||
cache.set(n, { body: got.body, at: Date.now() }); stats.imported++;
|
||||
O.renameSync.call(fs, p, p + '.imported-' + stamp);
|
||||
}
|
||||
for (const sp of (opts && opts.splits) || []) await migrateSplit(sp);
|
||||
ready = true;
|
||||
console.log('docstore: MySQL documents ready,', cache.size, 'documents,', stats.imported, 'imported from files this boot');
|
||||
const shut = () => { flush().catch(() => {}).finally(() => {}); };
|
||||
process.once('beforeExit', shut);
|
||||
return true;
|
||||
}
|
||||
// ---- row tables: an ever-growing array (spin-link clicks) is one row per item, never a rewrite of the whole document ----
|
||||
// spec { doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }. rows(table) gives the loaded items (oldest
|
||||
// first); the module inserts / deletes rows itself and saves its document WITHOUT the field.
|
||||
const ROWS = new Map(); const rowQ = []; let rowBusy = false;
|
||||
async function openSplit(sp) {
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS `' + sp.table + '` (id VARCHAR(64) PRIMARY KEY, ts BIGINT NOT NULL, body MEDIUMTEXT NOT NULL, KEY ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||
const [r] = await pool.query('SELECT body FROM `' + sp.table + '` ORDER BY ts, id');
|
||||
ROWS.set(sp.table, r.map(x => JSON.parse(x.body)));
|
||||
}
|
||||
async function insertMany(table, items, key, ts) {
|
||||
for (let i = 0; i < items.length; i += 500) {
|
||||
const part = items.slice(i, i + 500);
|
||||
await pool.query('INSERT INTO `' + table + '` (id, ts, body) VALUES ? ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [part.map(x => [String(x[key]), Number(x[ts]) || 0, JSON.stringify(x)])]);
|
||||
}
|
||||
}
|
||||
// first boot: the array still inside the document moves to its table, then the document is saved without it
|
||||
async function migrateSplit(sp) {
|
||||
const d = cache.get(sp.doc); if (!d) return;
|
||||
let obj; try { obj = JSON.parse(d.body); } catch (e) { return; }
|
||||
const arr = Array.isArray(obj[sp.field]) ? obj[sp.field] : null; if (!arr || !arr.length) return;
|
||||
await insertMany(sp.table, arr, sp.key, sp.ts);
|
||||
const [[{ n }]] = await pool.query('SELECT COUNT(*) n FROM `' + sp.table + '`');
|
||||
if (n < arr.length) throw new Error('docstore: ' + sp.table + ' holds ' + n + ' rows after moving ' + arr.length + '; stopping before the document is changed');
|
||||
const seen = new Set((ROWS.get(sp.table) || []).map(x => String(x[sp.key]))); const merged = (ROWS.get(sp.table) || []).concat(arr.filter(x => !seen.has(String(x[sp.key]))));
|
||||
merged.sort((a, b) => (Number(a[sp.ts]) || 0) - (Number(b[sp.ts]) || 0)); ROWS.set(sp.table, merged);
|
||||
obj[sp.field] = []; const body = JSON.stringify(obj);
|
||||
await pool.query('UPDATE docs SET body = ?, updated_at = ? WHERE name = ?', [body, Date.now(), sp.doc]); cache.set(sp.doc, { body, at: Date.now() });
|
||||
console.log('docstore:', arr.length, sp.field, 'moved from', sp.doc, 'to table', sp.table);
|
||||
}
|
||||
function rows(table) { return ROWS.get(table) || null; }
|
||||
function rowOp(op) { if (!pool || !writer) return; rowQ.push(op); if (!rowBusy) runRows(); }
|
||||
async function runRows() {
|
||||
rowBusy = true;
|
||||
try {
|
||||
while (rowQ.length && writer) {
|
||||
const op = rowQ[0];
|
||||
try {
|
||||
if (op.del) await pool.query('DELETE FROM `' + op.table + '` WHERE id IN (?)', [op.ids]);
|
||||
else await pool.query('INSERT INTO `' + op.table + '` (id, ts, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [op.id, op.ts, op.body]);
|
||||
rowQ.shift();
|
||||
} catch (e) { stats.errors++; stats.lastError = String(e.message).slice(0, 200); await new Promise(r => setTimeout(r, 1000)); }
|
||||
}
|
||||
} finally { rowBusy = false; }
|
||||
}
|
||||
const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) });
|
||||
const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); };
|
||||
function isOn() { return ready && !!pool; }
|
||||
// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true.
|
||||
async function claim(key) {
|
||||
if (!pool) return true;
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB');
|
||||
const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]);
|
||||
return r.affectedRows === 1;
|
||||
}
|
||||
|
||||
// SIGTERM during a deploy: write what is pending, then exit
|
||||
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
|
||||
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
|
||||
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
'use strict';
|
||||
// 5xYourTeam "The Draft" partner side (Marty approved the rules 2026-11-15). The network holding tank lives HERE (tank.js);
|
||||
// 5xYourTeam coaches draft from it through four signed calls, and every pick is a real tank adoption through tank.adopt():
|
||||
//
|
||||
// POST /api/partner/draft/pool {} -> { ok, rules, pool: [card], excluded: {why: n} }
|
||||
// POST /api/partner/draft/adopt { rid, coach, person, kind, week?, slot?, note? } -> { ok, ref, person, adoptionId, at, expires, holdUntil }
|
||||
// POST /api/partner/draft/release { rid, coach, ref | person, why: 'coach' | 'return' } -> { ok, outcome: 'returned' | 'kept' | 'done' | <closed status>, already? }
|
||||
// POST /api/partner/draft/status { ids: [person id] } -> { ok, people: { id: milestones | null } }
|
||||
// coach = { wallet, hubId?, username?, positions } (the 5xYourTeam claim: positions = 5x positions this wallet holds)
|
||||
// card = { id, username, door, joinedAt, lastSeen, wallet (bool), ready, holdUntil, opensAt, adoptions (outside 5x), adoptionsTotal, games, surfWei, surfCredits }
|
||||
//
|
||||
// Signature: X-Draft-Ts (ms) + X-Draft-Sig = hex HMAC-SHA256(DRAFT_PARTNER_SECRET, 'draft.v1.' + ts + '\n' + raw body), 5-minute
|
||||
// window. A dedicated secret (not NETWORK_SSO_SECRET): this one can move sponsors. adopt and release carry a request id (rid): a
|
||||
// retried or replayed call answers what the first one did and changes nothing.
|
||||
//
|
||||
// The rules (project-5xyourteam-draft, 11-15):
|
||||
// - only 5xYourTeam position holders draft and coach: the signed claim (positions >= 1) REPLACES InstantAdPay's own-$20-buy rule
|
||||
// for these calls only (the member's own tank button keeps its $20 rule); a coach needs an account here with a wallet linked,
|
||||
// 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)
|
||||
// - 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
|
||||
// - 24-hour sign-up grace (tank.adopt refuses it; the card carries opensAt); coaches never see contact data: no email, phone or
|
||||
// address leaves this module, person ids are hub ids (or an opaque i_ id the hub does not know)
|
||||
// - the only mail: tank.adopt's normal "X is now your sponsor" adoption email. No switch-on-payouts reminders for picks, no
|
||||
// payments-topic post (5xYourTeam posts its own Draft Day card)
|
||||
//
|
||||
// Auto-assign vs the 3-day window (the conflict the 5x build flagged), the rule implemented:
|
||||
// - a drafted person is an open adoption with a sponsor, so they are out of the tank: no 24-hour activation hold, no auto-assign,
|
||||
// no sign-up announcement, no dormant-lead rescue while the pick window runs
|
||||
// - the pick's adoption row expires at +3 days (not IAP's 7), and tank.sweep leaves it alone (hooks.isDraftPick): this module
|
||||
// closes it at 3 days with the pick's rule (started = payouts on or a purchase, a wallet alone is not started)
|
||||
// - a returned pick goes back with their ORIGINAL join time (account `created` is never touched, so no new sign-up grace) and,
|
||||
// with a wallet linked, a fresh 24-hour activation hold like anyone back in the tank (never the company)
|
||||
// - sponsor moves go through tank.js setSponsor (sponsorfollow + the hub's /v1/sponsor-change with by 'adopt' / 'release')
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const db = require('./db');
|
||||
|
||||
const H = 3600000, D = 86400000;
|
||||
const RULES = { returnMs: 3 * D, holdMs: 48 * H, maxOpen: 10, maxAdoptions: 2 };
|
||||
const ADDR = /^0x[0-9a-f]{40}$/;
|
||||
const lc = v => String(v || '').trim().toLowerCase();
|
||||
// throwaway / disposable inboxes: the adoption email would go nowhere. Plus a mistyped big-provider domain (emailcheck.js).
|
||||
const THROWAWAY = new Set(['mailinator.com', 'guerrillamail.com', 'guerrillamail.net', 'sharklasers.com', 'grr.la', '10minutemail.com', 'tempmail.com', 'temp-mail.org',
|
||||
'yopmail.com', 'trashmail.com', 'getnada.com', 'maildrop.cc', 'dispostable.com', 'throwawaymail.com', 'fakeinbox.com', 'mintemail.com', 'mohmal.com', 'emailondeck.com',
|
||||
'tempail.com', 'tempr.email', 'discard.email', 'spamgourmet.com', 'mailnesia.com', 'mytemp.email', 'tempmailo.com', 'burnermail.io', 'example.com', 'test.com']);
|
||||
const DOORS = { iap: 'InstantAdPay', instantadpay: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', dlb: 'Downline Banners', vbb: 'Viral Banner Blitz',
|
||||
ctb: 'CryptoTeamBuild', fivex: '5xYourTeam', vab: 'ViralAdBlitz', viraladblitz: 'ViralAdBlitz', dh: 'DownlineHydra', btc4hits: 'BTC4Hits', stackpol: 'Stack POL' };
|
||||
|
||||
let R = null; // { dataDir, accounts, chain, tank, ads, hooks: { hubInfo, resolvePerson, excluded, spamEmails, networkOn, suggestDomain }, requireHub, clock }
|
||||
const clock = () => (R && R.clock ? R.clock() : Date.now());
|
||||
const SECRET = () => String((R && R.secret) || process.env.DRAFT_PARTNER_SECRET || '').trim();
|
||||
const enabled = () => SECRET().length >= 32;
|
||||
|
||||
// ---- storage: MySQL (draft_picks, draft_log) when DATABASE_URL is set, else a JSON document (local QA) ----
|
||||
const J = {
|
||||
st: null, FILE: () => path.join(R.dataDir, 'draft-partner.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.log = this.st.log || []; 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 put(p) { const s = this.load(); const i = s.picks.findIndex(x => x.id === p.id); if (i >= 0) s.picks[i] = Object.assign({}, p); this.save(); },
|
||||
async byId(id) { const x = this.load().picks.find(r => r.id === Number(id)); return x ? Object.assign({}, x) : null; },
|
||||
async byRid(rid) { const x = this.load().picks.find(r => r.rid === rid); return x ? Object.assign({}, x) : null; },
|
||||
async byAdoption(aid) { const x = this.load().picks.find(r => r.adoptionId === Number(aid)); return x ? Object.assign({}, x) : null; },
|
||||
async ofPerson(pid) { return this.load().picks.filter(r => r.personId === pid).map(x => Object.assign({}, x)); },
|
||||
async open() { return this.load().picks.filter(r => r.status === 'open').map(x => Object.assign({}, x)); },
|
||||
async openOfCoach(w) { return this.load().picks.filter(r => r.status === 'open' && r.coachWallet === w).map(x => Object.assign({}, x)); },
|
||||
async recent(n) { return this.load().picks.slice(-(n || 100)).reverse().map(x => Object.assign({}, x)); },
|
||||
async countsByAdoptee() { const m = new Map(); for (const r of this.load().picks) m.set(r.adoptee, (m.get(r.adoptee) || 0) + 1); return m; },
|
||||
async log(row) { const s = this.load(); s.log.push(row); if (s.log.length > 2000) s.log = s.log.slice(-2000); this.save(); },
|
||||
async logs(n) { return this.load().log.slice(-(n || 100)).reverse(); }
|
||||
};
|
||||
const COLS = ['rid', 'adoptionId', 'adoptee', 'personId', 'coachEmail', 'coachWallet', 'coachHubId', 'kind', 'week', 'slot', 'ts', 'expires', 'holdUntil', 'status', 'closed', 'outcomeWhy', 'walletAt', 'payoutsAt', 'purchaseAt'];
|
||||
const SQLC = { rid: 'rid', adoptionId: 'adoption_id', adoptee: 'adoptee', personId: 'person_id', coachEmail: 'coach_email', coachWallet: 'coach_wallet', coachHubId: 'coach_hub_id', kind: 'kind', week: 'week', slot: 'slot', ts: 'ts', expires: 'expires', holdUntil: 'hold_until', status: 'status', closed: 'closed', outcomeWhy: 'outcome_why', walletAt: 'wallet_at', payoutsAt: 'payouts_at', purchaseAt: 'purchase_at' };
|
||||
const NUM = new Set(['adoptionId', 'ts', 'expires', 'holdUntil', 'closed', 'walletAt', 'payoutsAt', 'purchaseAt']);
|
||||
const rowP = r => { if (!r) return null; const o = { id: Number(r.id) }; for (const k of COLS) { const v = r[SQLC[k]]; o[k] = NUM.has(k) ? Number(v || 0) : (v == null ? null : String(v)); } return o; };
|
||||
const Q = {
|
||||
async add(p) { const r = await db.q('INSERT INTO draft_picks (' + COLS.map(k => SQLC[k]).join(',') + ') VALUES (' + COLS.map(() => '?').join(',') + ')', COLS.map(k => p[k] == null ? null : p[k])); return Object.assign({ id: r.insertId }, p); },
|
||||
async put(p) { await db.q('UPDATE draft_picks SET ' + COLS.map(k => SQLC[k] + '=?').join(',') + ' WHERE id=?', COLS.map(k => p[k] == null ? null : p[k]).concat([p.id])); },
|
||||
async byId(id) { return rowP((await db.q('SELECT * FROM draft_picks WHERE id=?', [Number(id)]))[0]); },
|
||||
async byRid(rid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE rid=?', [rid]))[0]); },
|
||||
async byAdoption(aid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE adoption_id=?', [Number(aid)]))[0]); },
|
||||
async ofPerson(pid) { return (await db.q('SELECT * FROM draft_picks WHERE person_id=? ORDER BY id', [pid])).map(rowP); },
|
||||
async open() { return (await db.q("SELECT * FROM draft_picks WHERE status='open' ORDER BY id")).map(rowP); },
|
||||
async openOfCoach(w) { return (await db.q("SELECT * FROM draft_picks WHERE status='open' AND coach_wallet=?", [w])).map(rowP); },
|
||||
async recent(n) { return (await db.q('SELECT * FROM draft_picks ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); },
|
||||
async countsByAdoptee() { return new Map((await db.q('SELECT adoptee, COUNT(*) n FROM draft_picks GROUP BY adoptee')).map(r => [r.adoptee, Number(r.n)])); },
|
||||
async log(x) { await db.q('INSERT INTO draft_log (ts,op,ok,code,reason,coach,person,ref,rid) VALUES (?,?,?,?,?,?,?,?,?)', [x.ts, x.op, x.ok ? 1 : 0, x.code || null, String(x.reason || '').slice(0, 400), x.coach || null, x.person || null, x.ref || null, x.rid || null]); },
|
||||
async logs(n) { return (await db.q('SELECT * FROM draft_log ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(r => ({ ts: Number(r.ts), op: r.op, ok: !!r.ok, code: r.code, reason: r.reason, coach: r.coach, person: r.person, ref: r.ref, rid: r.rid })); }
|
||||
};
|
||||
const S = () => (db.enabled() ? Q : J);
|
||||
async function ensureTables() {
|
||||
if (!db.enabled()) return;
|
||||
await db.q(`CREATE TABLE IF NOT EXISTS draft_picks (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY, rid VARCHAR(80) NOT NULL, adoption_id INT NOT NULL, adoptee VARCHAR(190) NOT NULL, person_id VARCHAR(40) NOT NULL,
|
||||
coach_email VARCHAR(190) NOT NULL, coach_wallet VARCHAR(42) NOT NULL, coach_hub_id VARCHAR(40) NULL, kind VARCHAR(16) NULL, week VARCHAR(16) NULL, slot VARCHAR(16) NULL,
|
||||
ts BIGINT NOT NULL, expires BIGINT NOT NULL, hold_until BIGINT NOT NULL, status VARCHAR(16) NOT NULL, closed BIGINT NULL, outcome_why VARCHAR(200) NULL,
|
||||
wallet_at BIGINT NULL, payouts_at BIGINT NULL, purchase_at BIGINT NULL,
|
||||
UNIQUE KEY rid (rid), KEY adoption (adoption_id), KEY person (person_id), KEY coach (coach_wallet, status), KEY st (status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // 5xYourTeam draft picks (each one a tank adoption)
|
||||
await db.q(`CREATE TABLE IF NOT EXISTS draft_log (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY, ts BIGINT NOT NULL, op VARCHAR(16) NOT NULL, ok TINYINT NOT NULL, code VARCHAR(40) NULL, reason VARCHAR(400) NULL,
|
||||
coach VARCHAR(42) NULL, person VARCHAR(40) NULL, ref VARCHAR(40) NULL, rid VARCHAR(80) NULL, KEY t (ts)
|
||||
) 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(); }
|
||||
|
||||
// ---- signature ----
|
||||
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('draft.v1.' + ts + '\n' + raw).digest('hex'); }
|
||||
function verify(headers, raw) {
|
||||
if (!enabled()) return { status: 503, error: 'draft partner not configured' };
|
||||
const ts = String(headers['x-draft-ts'] || ''), sig = String(headers['x-draft-sig'] || '');
|
||||
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return { status: 401, error: 'stale' };
|
||||
const want = sign(ts, raw);
|
||||
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' };
|
||||
try { const b = JSON.parse(raw || '{}'); return b && typeof b === 'object' ? { body: b } : { status: 400, error: 'bad json' }; } catch (e) { return { status: 400, error: 'bad json' }; }
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
const idOf = email => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; return hi && /^h_[0-9a-f]{16}$/.test(hi.id) ? hi.id : 'i_' + crypto.createHmac('sha256', SECRET() || 'local').update('pid:' + lc(email)).digest('hex').slice(0, 16); };
|
||||
const doorOf = (email, via) => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; const k = lc((hi && hi.door) || via); return DOORS[k] || (k === 'hub' ? 'Network' : 'InstantAdPay'); };
|
||||
function throwaway(email) {
|
||||
const d = lc(email).split('@')[1] || ''; if (!d) return true;
|
||||
if (THROWAWAY.has(d)) return true;
|
||||
const fix = R.hooks && R.hooks.suggestDomain ? R.hooks.suggestDomain(d) : null; return !!(fix && fix !== d); // a mistyped provider: the mail bounces
|
||||
}
|
||||
function spamSet() { try { return new Set((R.hooks && R.hooks.spamEmails ? R.hooks.spamEmails() : []).map(lc)); } catch (e) { return new Set(); } }
|
||||
const hubOff = () => R.requireHub !== false && !(R.hooks && R.hooks.networkOn && R.hooks.networkOn());
|
||||
async function logCall(op, x) { const row = Object.assign({ ts: clock(), op }, x); try { await S().log(row); } catch (e) { console.error('draft log', e.message); } if (!x.ok) console.log('draft', op, 'refused', x.code || '', String(x.reason || '').slice(0, 120)); return row; }
|
||||
const fail = async (op, code, reason, x) => { await logCall(op, Object.assign({ ok: false, code, reason }, x || {})); return { error: reason, code }; };
|
||||
function purchasers() { const s = new Set(); for (const ev of R.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.buyerId) s.add(Number(ev.buyerId)); return s; }
|
||||
|
||||
// a coach: the wallet that holds the 5x position, then a position wallet here, then the hub's person for the hub id
|
||||
async function coachAccount(c) {
|
||||
const w = lc(c && c.wallet); if (!ADDR.test(w)) return { code: 'bad_coach', reason: 'Which coach? (wallet missing)' };
|
||||
let a = await R.accounts.byAddress(w).catch(() => null);
|
||||
if (!a && R.accounts.positionOwner) { const po = await R.accounts.positionOwner(w).catch(() => null); if (po && po.email) a = await R.accounts.byEmail(po.email); }
|
||||
if (!a && c.hubId && R.hooks && R.hooks.resolvePerson) { try { const p = await R.hooks.resolvePerson({ id: String(c.hubId) }); if (p && p.email && !p.blocked) a = await R.accounts.byEmail(lc(p.email)); } catch (e) {} }
|
||||
if (!a) return { code: 'coach_unknown', reason: 'This coach has no InstantAdPay account yet. Sign in on InstantAdPay once (network sign-in) and link a wallet.' };
|
||||
return { account: a, wallet: w };
|
||||
}
|
||||
|
||||
// ---- the pool ----
|
||||
let poolCache = null;
|
||||
async function poolRows(fresh) {
|
||||
if (!fresh && poolCache && clock() - poolCache.at < 30000) return poolCache;
|
||||
const list = await R.tank.waiting(); const spam = spamSet(); const ex = { spam: 0, throwaway: 0, adoptedTwice: 0 };
|
||||
const local = await R.tank.summaryMap(); const mine = await S().countsByAdoptee(); const rows = [];
|
||||
for (const w of list) {
|
||||
if ((R.hooks.excluded && R.hooks.excluded(w.email)) || spam.has(lc(w.email))) { ex.spam++; continue; }
|
||||
if (throwaway(w.email)) { ex.throwaway++; continue; }
|
||||
const n = ((local.get(w.email) || {}).count || 0) + (R.tank.remoteCount ? R.tank.remoteCount(w.email) : 0);
|
||||
if (n >= RULES.maxAdoptions) { ex.adoptedTwice++; continue; }
|
||||
rows.push({ email: w.email, card: { id: idOf(w.email), username: w.username || null, door: doorOf(w.email, w.via), joinedAt: Number(w.joined) || 0, lastSeen: Number(w.lastSeen) || 0,
|
||||
// adoptions = OUTSIDE 5xYourTeam (5xYourTeam adds its own picks; counting them here too would double them); adoptionsTotal = all
|
||||
wallet: !!w.wallet, ready: !!w.ready, holdUntil: w.holdUntil || 0, opensAt: w.opensAt || 0, adoptions: Math.max(0, n - (mine.get(w.email) || 0)), adoptionsTotal: n,
|
||||
games: null, surfWei: null, surfCredits: Number(w.earned) || 0 } }); // games: InstantAdPay keeps no per-member game record (never invented)
|
||||
}
|
||||
poolCache = { at: clock(), rows, excluded: ex }; return poolCache;
|
||||
}
|
||||
async function pool() {
|
||||
if (hubOff()) { await logCall('pool', { ok: false, code: 'hub_off', reason: 'the network hub is off, so locked people cannot be ruled out' }); return { ok: true, rules: rulesView(), pool: [], excluded: {}, hubOff: true }; }
|
||||
const p = await poolRows(false);
|
||||
return { ok: true, rules: rulesView(), pool: p.rows.map(r => r.card), excluded: p.excluded };
|
||||
}
|
||||
const rulesView = () => ({ returnHours: RULES.returnMs / H, holdHours: RULES.holdMs / H, maxOpen: RULES.maxOpen, maxAdoptions: RULES.maxAdoptions, graceHours: (RULES.graceMs || D) / H });
|
||||
|
||||
// ---- adopt ----
|
||||
async function adopt(b) {
|
||||
const rid = String(b.rid || '').slice(0, 80); const c = b.coach || {}; const pid = String(b.person || '').slice(0, 40); const kind = /^(draft|instant)$/.test(b.kind) ? b.kind : 'draft';
|
||||
const x = { coach: lc(c.wallet) || null, person: pid || null, rid };
|
||||
if (!/^[A-Za-z0-9_.:-]{8,80}$/.test(rid)) return fail('adopt', 'bad_rid', 'A request id (rid) is required.', x);
|
||||
const prev = await S().byRid(rid);
|
||||
if (prev) return { ok: true, repeat: true, ref: 'iap:' + prev.id, person: prev.personId, adoptionId: prev.adoptionId, at: prev.ts, expires: prev.expires, holdUntil: prev.holdUntil };
|
||||
if (!(Number(c.positions) >= 1)) return fail('adopt', 'not_vested', 'Only 5xYourTeam position holders can draft and coach.', x);
|
||||
if (hubOff()) return fail('adopt', 'hub_off', 'The network hub is off, so nobody can be drafted right now.', x);
|
||||
const co = await coachAccount(c); if (!co.account) return fail('adopt', co.code, co.reason, x);
|
||||
if ((await S().openOfCoach(co.wallet)).length >= RULES.maxOpen) return fail('adopt', 'full', 'Your team is full (' + RULES.maxOpen + ' open picks). Help one get started first.', x);
|
||||
const hit = (await poolRows(true)).rows.find(r => r.card.id === pid);
|
||||
if (!hit) return fail('adopt', 'gone', 'That player is no longer in the holding tank.', x);
|
||||
const r = await R.tank.adopt(co.account.email, hit.email, String(b.note || ''), { partner: { positions: Number(c.positions), ttlMs: RULES.returnMs, maxOpen: RULES.maxOpen }, recordNote: '5xYourTeam draft pick (' + kind + (b.week ? ', week ' + String(b.week).slice(0, 10) : '') + (b.slot ? ', slot ' + String(b.slot).slice(0, 10) : '') + ')' });
|
||||
if (!r || !r.ok) return fail('adopt', (r && r.code) || 'refused', (r && r.error) || 'The tank refused.', x);
|
||||
poolCache = null;
|
||||
const now = clock(); const acct = await R.accounts.byEmail(hit.email);
|
||||
const pick = await S().add({ rid, adoptionId: Number(r.adoption.id), adoptee: hit.email, personId: pid, coachEmail: co.account.email, coachWallet: co.wallet, coachHubId: c.hubId ? String(c.hubId).slice(0, 40) : null,
|
||||
kind, week: b.week ? String(b.week).slice(0, 16) : null, slot: b.slot ? String(b.slot).slice(0, 16) : null, ts: now, expires: now + RULES.returnMs, holdUntil: now + RULES.holdMs, status: 'open', closed: 0, outcomeWhy: null,
|
||||
walletAt: acct && acct.address ? now : 0, payoutsAt: 0, purchaseAt: 0 });
|
||||
await logCall('adopt', Object.assign(x, { ok: true, ref: 'iap:' + pick.id, reason: kind + ' pick by ' + (c.username ? '@' + String(c.username).slice(0, 40) : x.coach) }));
|
||||
return { ok: true, ref: 'iap:' + pick.id, person: pid, adoptionId: pick.adoptionId, at: pick.ts, expires: pick.expires, holdUntil: pick.holdUntil };
|
||||
}
|
||||
|
||||
// is the pick's adoption still the open one? (released on InstantAdPay itself, moved by a LinkSpin follow, ...) -> closed here too
|
||||
async function reconcile(p) {
|
||||
if (p.status !== 'open') return p;
|
||||
const open = await R.tank.openOf(p.adoptee);
|
||||
if (open.some(ad => Number(ad.id) === p.adoptionId)) return p;
|
||||
p.status = 'moved'; p.closed = clock(); p.outcomeWhy = 'the adoption was closed on InstantAdPay (released, moved or followed from LinkSpin)'; await S().put(p);
|
||||
await logCall('reconcile', { ok: true, code: 'moved', reason: p.outcomeWhy, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
|
||||
return p;
|
||||
}
|
||||
// milestones seen so far (first-seen times; the chain events carry no timestamps here)
|
||||
async function observe(p, a, buyers) {
|
||||
if (!a) return p; const now = clock(); let ch = false;
|
||||
if (a.address && !p.walletAt) { p.walletAt = now; ch = true; }
|
||||
if (Number(a.memberId) > 0 && !p.payoutsAt) { p.payoutsAt = now; ch = true; }
|
||||
if (Number(a.memberId) > 0 && !p.purchaseAt && buyers && buyers.has(Number(a.memberId))) { p.purchaseAt = now; ch = true; }
|
||||
if (ch) await S().put(p); return p;
|
||||
}
|
||||
const started = (p, a) => !!(a && Number(a.memberId) > 0) || !!(p.payoutsAt || p.purchaseAt);
|
||||
|
||||
// close one open pick: 'coach' (released after the 48 h hold) or 'return' (3 days, not started). Shared by release() and sweep().
|
||||
async function closePick(p, why, now) {
|
||||
const a = await R.accounts.byEmail(p.adoptee);
|
||||
await observe(p, a, purchasers());
|
||||
if (started(p, a)) { p.status = 'done'; p.closed = now; p.outcomeWhy = 'started (payouts on or a purchase)'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'done'); return { outcome: 'done', why: p.outcomeWhy }; }
|
||||
if (why === 'coach' && now < p.holdUntil) return { code: 'hold', reason: 'You picked them less than ' + (RULES.holdMs / H) + ' hours ago. Give them a little time first (' + Math.ceil((p.holdUntil - now) / H) + ' h left).' };
|
||||
if (why === 'return' && now < p.expires) return { code: 'too_early', reason: 'The pick window runs until ' + new Date(p.expires).toISOString() + '.' };
|
||||
const count = await R.tank.countAll(p.adoptee);
|
||||
if (count >= RULES.maxAdoptions) { // their second adoption: they stay with this coach (the tank sweep rule, never back to nobody)
|
||||
p.status = 'kept'; p.closed = now; p.outcomeWhy = 'adopted twice: stays with this coach'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired');
|
||||
return { outcome: 'kept', why: p.outcomeWhy };
|
||||
}
|
||||
const lk = await R.tank.lockedWhy(p.adoptee);
|
||||
if (lk === 'unknown') return { code: 'hub_unknown', reason: 'The network record cannot be checked right now. Try again later.' };
|
||||
if (lk === 'locked') { p.status = 'kept'; p.closed = now; p.outcomeWhy = 'locked on a network contract: never moved'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired'); return { outcome: 'kept', why: p.outcomeWhy }; }
|
||||
const note = why === 'return' ? '5xYourTeam pick returned: not started in ' + (RULES.returnMs / D) + ' days' : '5xYourTeam pick released by the coach';
|
||||
const r = await R.tank.setSponsorDeliberate(p.adoptee, '', 'release', note);
|
||||
if (r && r.error) return { code: 'refused', reason: r.error };
|
||||
await R.tank.closeAdoption(p.adoptionId, why === 'return' ? 'expired' : 'dropped'); // both still count toward their two adoptions
|
||||
p.status = 'returned'; p.closed = now; p.outcomeWhy = note; await S().put(p); poolCache = null;
|
||||
return { outcome: 'returned', why: note };
|
||||
}
|
||||
|
||||
async function findPick(b) {
|
||||
const ref = String(b.ref || ''); const m = /^iap:(\d+)$/.exec(ref);
|
||||
if (m) return S().byId(Number(m[1]));
|
||||
const pid = String(b.person || ''); const w = lc(b.coach && b.coach.wallet);
|
||||
const rows = (await S().ofPerson(pid)).filter(p => p.coachWallet === w); return rows.find(p => p.status === 'open') || rows[rows.length - 1] || null;
|
||||
}
|
||||
async function release(b) {
|
||||
const why = b.why === 'return' ? 'return' : 'coach'; const w = lc(b.coach && b.coach.wallet); const rid = String(b.rid || '').slice(0, 80);
|
||||
const x = { coach: w || null, person: b.person ? String(b.person).slice(0, 40) : null, rid, ref: b.ref ? String(b.ref).slice(0, 40) : null };
|
||||
let p = await findPick(b);
|
||||
if (!p) return fail('release', 'no_pick', 'No such pick.', x);
|
||||
if (p.coachWallet !== w) return fail('release', 'not_yours', 'Not your pick.', x);
|
||||
x.person = p.personId; x.ref = 'iap:' + p.id;
|
||||
p = await reconcile(p);
|
||||
if (p.status !== 'open') { await logCall('release', Object.assign(x, { ok: true, code: 'already', reason: why + ': already ' + p.status })); return { ok: true, already: true, outcome: p.status }; }
|
||||
const r = await closePick(p, why, clock());
|
||||
if (!r.outcome) return fail('release', r.code, r.reason, x);
|
||||
await logCall('release', Object.assign(x, { ok: true, code: r.outcome, reason: why + ': ' + r.why }));
|
||||
return { ok: true, outcome: r.outcome };
|
||||
}
|
||||
|
||||
// ---- status: milestones for the people 5xYourTeam holds picks for (anyone else answers null) ----
|
||||
async function status(b) {
|
||||
const ids = [...new Set((Array.isArray(b.ids) ? b.ids : []).map(v => String(v || '').slice(0, 40)).filter(Boolean))].slice(0, 500);
|
||||
const buyers = purchasers(); const out = {};
|
||||
const emails = []; const picksBy = {};
|
||||
for (const id of ids) { const rows = await S().ofPerson(id); if (!rows.length) { out[id] = null; continue; } picksBy[id] = rows; emails.push(rows[0].adoptee); }
|
||||
const tot = R.ads && R.ads.earnedTotals ? await R.ads.earnedTotals(emails).catch(() => ({})) : {};
|
||||
for (const id of Object.keys(picksBy)) {
|
||||
const rows = picksBy[id]; let last = rows[rows.length - 1]; const email = last.adoptee;
|
||||
const a = await R.accounts.byEmail(email); if (!a) { out[id] = null; continue; }
|
||||
last = await reconcile(last); last = await observe(last, a, buyers);
|
||||
const count = await R.tank.countAll(email);
|
||||
out[id] = { username: a.username || null, door: doorOf(email, a.joinedVia), lastSeen: Number(a.lastSeen) || 0,
|
||||
wallet: a.address ? (rows.map(r => r.walletAt).filter(Boolean).sort((x, y) => x - y)[0] || clock()) : 0,
|
||||
payouts: Number(a.memberId) > 0 ? (last.payoutsAt || clock()) : 0, purchase: Number(a.memberId) > 0 && buyers.has(Number(a.memberId)) ? (last.purchaseAt || clock()) : 0,
|
||||
adoptions: Math.max(0, count - rows.length), // adoptions outside 5xYourTeam (5x counts its own picks itself)
|
||||
games: null, surfWei: null, surfCredits: (tot[email] || {}).earned || 0,
|
||||
pick: { ref: 'iap:' + last.id, status: last.status, coachWallet: last.coachWallet, expires: last.expires, holdUntil: last.holdUntil } };
|
||||
}
|
||||
return { ok: true, people: out };
|
||||
}
|
||||
|
||||
// ---- the hourly sweep (server.js, beside tank.sweep): started picks close as done, unstarted ones past 3 days go back ----
|
||||
let sweeping = null;
|
||||
function sweep() { if (!sweeping) sweeping = sweepRun().finally(() => { sweeping = null; }); return sweeping; }
|
||||
async function sweepRun() {
|
||||
const now = clock(); const out = { done: 0, returned: 0, kept: 0, moved: 0, waiting: 0 }; const buyers = purchasers();
|
||||
for (let p of await S().open()) {
|
||||
p = await reconcile(p); if (p.status !== 'open') { out.moved++; continue; }
|
||||
const a = await R.accounts.byEmail(p.adoptee); await observe(p, a, buyers);
|
||||
if (!started(p, a) && now < p.expires) continue;
|
||||
const r = await closePick(p, 'return', now);
|
||||
if (!r.outcome) { out.waiting++; continue; }
|
||||
out[r.outcome] = (out[r.outcome] || 0) + 1;
|
||||
await logCall('sweep', { ok: true, code: r.outcome, reason: r.why, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// tank.sweep asks this before closing an expired adoption (the pick's own rule decides)
|
||||
async function isDraftPick(adoptionId) { if (!R) return false; const p = await S().byAdoption(adoptionId); return !!(p && p.status === 'open'); }
|
||||
|
||||
async function adminView() { return { enabled: enabled(), rules: rulesView(), hubOff: hubOff(), picks: (await S().recent(200)).map(p => Object.assign({}, p, { adoptee: undefined, coachEmail: undefined })), log: await S().logs(200) }; }
|
||||
|
||||
// one entry for the HTTP routes (server.js) and the cross-repo test: op = pool | adopt | release | status
|
||||
async function handle(op, body) {
|
||||
if (op === 'pool') return pool();
|
||||
if (op === 'adopt') return adopt(body);
|
||||
if (op === 'release') return release(body);
|
||||
if (op === 'status') return status(body);
|
||||
return { error: 'unknown op', code: 'unknown_op' };
|
||||
}
|
||||
|
||||
module.exports = { init, enabled, verify, sign, handle, pool, adopt, release, status, sweep, isDraftPick, adminView, RULES, _poolReset: () => { poolCache = null; } };
|
||||
+2
-1
@@ -34,7 +34,8 @@ function redirectFor(v, acct, site) {
|
||||
const p = new URLSearchParams({ nonce: v.nonce, email, external_id: email, require_activation: 'false', suppress_welcome_message: 'false' });
|
||||
if (acct.username) { p.set('username', acct.username); p.set('name', acct.username); }
|
||||
if (acct.avatarUrl) p.set('avatar_url', /^https?:/.test(acct.avatarUrl) ? acct.avatarUrl : site + acct.avatarUrl);
|
||||
if (acct.username) p.set('website', 'https://stackpol.com/' + acct.username);
|
||||
// no website on sign-in (Marty 2026-11-14): Discourse holds a new user who "entered profile information without reading" for
|
||||
// approval, and the stackpol.com link we filled in put every new member in the review queue. Members add their own.
|
||||
if (groups.length) p.set('add_groups', groups.join(','));
|
||||
const remove = ['network_members', 'wallet_linked'].filter(g => !groups.includes(g)); if (remove.length) p.set('remove_groups', remove.join(','));
|
||||
const out = Buffer.from(p.toString()).toString('base64');
|
||||
|
||||
+20
-7
@@ -71,14 +71,19 @@ const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6;
|
||||
// three). Settings (Admin > Settings, no deploy): heroSales (sale switch, default OFF), heroPrice<Set>Cents per hero (0 = free for
|
||||
// every account, granted like a base hero), heroBundlePriceCents, heroBundleHeroes, heroBundleCap (a level the bundle would raise the
|
||||
// cap to; UNSET = no cap change, Marty has not approved one). key = the wire value Shards of Valor reads (classes.json paid buy).
|
||||
// 2026-11-14 (Marty approved, "Yes make it free"; Dallas: "The Archer should be free to everyone at level 20"): Kestrel is FREE for every
|
||||
// player once a hero in their party reaches level 20 (the game decides, Shards of Valor classes.json freeAt) and is NOT SOLD here any more
|
||||
// (freeAt): no buy, not in any bundle, waiting Kestrel orders are cancelled unpaid. A member who bought her keeps her (record.heroes.kestrel);
|
||||
// nothing refunded. Valda, Morag and Roland, the $50 bundle and every price are unchanged.
|
||||
const HERO_DEFS = [
|
||||
{ key: 'kestrel', set: 'Kestrel', name: 'Kestrel the Archer', price: 2000, blurb: 'Quick and sharp-eyed: arrows on every foe.' },
|
||||
{ key: 'kestrel', set: 'Kestrel', name: 'Kestrel the Archer', price: 2000, freeAt: 20, blurb: 'Quick and sharp-eyed: arrows on every foe.' },
|
||||
{ key: 'valda', set: 'Valda', name: 'Valda the Barbarian', price: 2000, blurb: 'A berserker: hits harder the more she is hurt, light on armour.' },
|
||||
{ key: 'morag', set: 'Morag', name: 'Morag the Druid', price: 2000, blurb: 'A healer of the wild: heals the whole party.' },
|
||||
{ key: 'roland', set: 'Roland', name: 'Roland the Paladin', price: 2000, blurb: 'A holy knight: sword and shield, heals one hero at a time.' },
|
||||
];
|
||||
const HERO_KEYS = HERO_DEFS.map(d => d.key);
|
||||
const HERO_DEF = Object.fromEntries(HERO_DEFS.map(d => [d.key, d]));
|
||||
const HERO_SOLD = HERO_DEFS.filter(d => !d.freeAt).map(d => d.key); // free at a level in the game (Kestrel at 20): never sold, never in a bundle
|
||||
const HERO_BUNDLE_DEFAULT = 'valda,morag,roland';
|
||||
|
||||
let R = null; // deps from server.js
|
||||
@@ -129,7 +134,7 @@ function cfg() {
|
||||
heroes: (() => {
|
||||
const price = Object.fromEntries(HERO_DEFS.map(d => [d.key, Math.max(0, Math.round(n('heroPrice' + d.set + 'Cents', d.price)))]));
|
||||
const raw = sc.heroBundleHeroes == null || String(sc.heroBundleHeroes).trim() === '' ? HERO_BUNDLE_DEFAULT : String(sc.heroBundleHeroes);
|
||||
const list = [...new Set(raw.split(',').map(x => x.trim().toLowerCase()).filter(k => HERO_KEYS.includes(k) && price[k] > 0))];
|
||||
const list = [...new Set(raw.split(',').map(x => x.trim().toLowerCase()).filter(k => HERO_SOLD.includes(k) && price[k] > 0))];
|
||||
const capRaw = String(sc.heroBundleCap == null ? '' : sc.heroBundleCap).trim(), cap = capRaw === '' ? NaN : Number(capRaw);
|
||||
return { sale: on('heroSales'), price, free: HERO_KEYS.filter(k => price[k] === 0), bundle: { heroes: list.length >= 2 ? list : [], price: Math.max(1, Math.round(n('heroBundlePriceCents', 5000))) },
|
||||
cap: Number.isInteger(cap) && cap > 0 ? cap : null };
|
||||
@@ -362,12 +367,19 @@ async function onEvent(ev) {
|
||||
// ---- bonus heroes (2026-11-05) ----
|
||||
// owned for good: record.heroes = { kestrel: { ts, via, tx, order, cents, usd, bundle? } }, record.heroBundle = { ts, via, heroes, tx, order }
|
||||
// (in the passes map, the same durable record as the passes). A hero is never in `bought`, so hero sales never feed the Pass Tournament pool.
|
||||
function heroOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind === 'hero') out.push(Object.assign({ order: k }, o)); return out; }
|
||||
function heroOrders(e) {
|
||||
const out = [];
|
||||
for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind === 'hero') {
|
||||
if (HERO_DEF[o.hero] && HERO_DEF[o.hero].freeAt) { orders.set(k, Object.assign({}, o, { status: 'cancelled', cancelledAt: Date.now(), why: 'free at level ' + HERO_DEF[o.hero].freeAt + ' in the game' })); continue; } // never paid: she is free now
|
||||
out.push(Object.assign({ order: k }, o));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function heroOrder(e, key) { return heroOrders(e).find(o => o.hero === key) || null; }
|
||||
const heroOrderPrice = (c, key) => key === 'bundle' ? c.heroes.bundle.price : (c.heroes.price[key] || 0);
|
||||
const heroOrderPrices = c => [c.heroes.bundle.price].concat(Object.values(c.heroes.price).filter(x => x > 0));
|
||||
const heroOrderPrices = c => [c.heroes.bundle.price].concat(HERO_SOLD.map(k => c.heroes.price[k]).filter(x => x > 0));
|
||||
// a waiting hero order still worth fulfilling: nothing in it is owned yet (a bundle also needs its list set)
|
||||
function heroOrderOpen(e, key) { const c = cfg(), own = new Set(heroesOwned(e).owned); if (key === 'bundle') return c.heroes.bundle.heroes.length > 0 && !c.heroes.bundle.heroes.some(k => own.has(k)); return HERO_KEYS.includes(key) && !own.has(key); }
|
||||
function heroOrderOpen(e, key) { const c = cfg(), own = new Set(heroesOwned(e).owned); if (key === 'bundle') return c.heroes.bundle.heroes.length > 0 && !c.heroes.bundle.heroes.some(k => own.has(k)); return HERO_SOLD.includes(key) && !own.has(key); }
|
||||
// -> { owned: bought, comped and free heroes; bought: on the record; bundle: bought as the bundle }
|
||||
function heroesOwned(email) {
|
||||
const p = rec(String(email || '').toLowerCase()), c = cfg(), H = (p && p.heroes) || {};
|
||||
@@ -393,7 +405,7 @@ function grantHeroes(e, key, via, extra, now) {
|
||||
// the member card part: every hero, its price and state, and the bundle. open = on sale (heroSales) or the admin portal's test (opts.preview)
|
||||
function heroView(email, now, opts) {
|
||||
const e = String(email || '').toLowerCase(), c = cfg(), h = heroesOwned(e), own = new Set(h.owned), preview = !!(opts && opts.preview), open = c.heroes.sale || preview;
|
||||
const items = HERO_DEFS.map(d => { const price = c.heroes.price[d.key]; return { key: d.key, name: d.name, blurb: d.blurb, price, usd: price / 100, package: packageFor(price / 100), free: price === 0, owned: own.has(d.key), waiting: !!heroOrder(e, d.key), open: open && price > 0 && !own.has(d.key) }; });
|
||||
const items = HERO_DEFS.map(d => { const price = c.heroes.price[d.key], fa = d.freeAt || null; return { key: d.key, name: d.name, blurb: d.blurb, price, usd: price / 100, package: packageFor(price / 100), free: price === 0, freeAt: fa, owned: own.has(d.key), waiting: !fa && !!heroOrder(e, d.key), open: !fa && open && price > 0 && !own.has(d.key) }; });
|
||||
const B = c.heroes.bundle, bOwn = B.heroes.filter(k => own.has(k));
|
||||
const bundle = B.heroes.length ? { key: 'bundle', names: B.heroes.map(k => HERO_DEF[k].name), heroes: B.heroes, price: B.price, usd: B.price / 100, package: packageFor(B.price / 100), owned: bOwn.length === B.heroes.length, some: bOwn.length > 0, waiting: !!heroOrder(e, 'bundle'), open: open && !bOwn.length } : null;
|
||||
return { sale: c.heroes.sale, preview: preview && !c.heroes.sale, show: c.heroes.sale || preview || h.bought.length > 0, items, bundle, owned: h.owned, bundleOwned: h.bundle };
|
||||
@@ -410,6 +422,7 @@ function buyHero(email, now, key, opts) {
|
||||
const B = c.heroes.bundle; if (!B.heroes.length) return { error: 'There is no hero bundle right now.' };
|
||||
const have = B.heroes.filter(k => own.has(k)); if (have.length) return { error: 'You already have ' + have.map(k => HERO_DEF[k].name).join(' and ') + ', so the bundle is not for you: get the others one at a time.' };
|
||||
} else {
|
||||
if (HERO_DEF[key].freeAt) return { error: HERO_DEF[key].name + ' is free for every player at level ' + HERO_DEF[key].freeAt + ' in Shards of Valor, so she is not for sale.' };
|
||||
if (c.heroes.price[key] === 0) return { error: HERO_DEF[key].name + ' is free for everyone.' };
|
||||
if (own.has(key)) return { error: 'You already have ' + HERO_DEF[key].name + '. Heroes are yours for good.' };
|
||||
}
|
||||
@@ -444,7 +457,7 @@ function heroStats() {
|
||||
for (const [k, h] of Object.entries(p.heroes || {})) { if (!(k in out.sold)) continue; if (h.via === 'admin') { out.comped += 1; continue; } out.sold[k] += 1; if (!h.bundle) out.usd += Number(h.usd) || 0; }
|
||||
if (p.heroBundle && p.heroBundle.via !== 'admin') { out.bundles += 1; out.usd += Number(p.heroBundle.usd) || 0; }
|
||||
}
|
||||
for (const [, o] of orders) if (o.status === 'waiting' && o.kind === 'hero') out.waiting += 1;
|
||||
for (const [, o] of orders) if (o.status === 'waiting' && o.kind === 'hero' && !(HERO_DEF[o.hero] && HERO_DEF[o.hero].freeAt)) out.waiting += 1;
|
||||
out.usd = Math.round(out.usd * 100) / 100; return out;
|
||||
}
|
||||
|
||||
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
// Network hub sync (2026-11-12, Marty 2026-11-06: one membership from any door; the hub is the single identity).
|
||||
// Everything here sleeps unless HUB_ENABLED is on: server.js does not even init this module without it, so no file is
|
||||
// written, no route answers and no hook is wired. The InstantAdPay <-> LinkSpin direct sync (lssync.js / lsinbound.js)
|
||||
// keeps running exactly as before either way.
|
||||
//
|
||||
// Inbound (POST /api/hub/events, signed by the hub with HUB_SECRET: X-Hub-Ts + X-Hub-Sig = hex HMAC-SHA256(ts + newline +
|
||||
// raw body), 5-minute window). The hub only moves its cursor after a 2xx and may send an event twice:
|
||||
// member.joined someone joined at another door: /v1/resolve the person (and, climbing, any sponsor not here yet) and
|
||||
// hand the rows to lsinbound.receive, the same waiting-account path LinkSpin-first members take, with
|
||||
// joinedVia 'hub' and joinedRef 'hub:<door>'. First-platform rule as there: an account that already
|
||||
// exists here keeps its sponsor and only gets empty fields filled. Joins from this site are skipped.
|
||||
// wallet.connected filled only on a waiting account that still has no wallet (lsinbound fill rules). A claimed account
|
||||
// links its own wallet here; the hub's wallet is not proof of ownership on InstantAdPay.
|
||||
// sponsor.changed ignored on purpose (2026-11-14): lsinbound's follow rule needs sponsorSetAt / By / PrevEmail, which the
|
||||
// hub view does not expose, and someone the InstantAdPay contract holds never moves anyway.
|
||||
// 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).
|
||||
// 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.
|
||||
//
|
||||
// Outbound (/v1/join, /v1/wallet, signed as HUB_SITE): new accounts made here since the flag first went on and every main
|
||||
// wallet linked here go into a persisted outbox (DATA_DIR/hubsync.json) and are sent in order, never in the way of a
|
||||
// sign-up. Retried with backoff on 5xx / network / 404-before-join; a 400/409 refusal is final and logged.
|
||||
// Gaps closed 2026-11-13 (Marty: "let's get the gaps report built"), all still one way:
|
||||
// - any later change to a member's username or sponsor goes to /v1/join again (names them; a sponsor only lands where the
|
||||
// hub has none), old members included, not only accounts made since the flag went on;
|
||||
// - a DELIBERATE sponsor change (sponsorfollow: adopt, rescue, release, expire->expiry, admin) goes to /v1/sponsor-change;
|
||||
// - every MemberActivated on the InstantAdPay contract goes to /v1/contract-bind (contract 'iap', the sponsor by wallet),
|
||||
// by email when the wallet belongs to an account here, else by wallet alone.
|
||||
// - every paid Purchase goes to /v1/contract-spend (2026-11-14, rule 2: the contract with money spent decides the network
|
||||
// sponsor when two contracts hold different ones).
|
||||
// Where the hub and InstantAdPay name different sponsors, nothing is forced on either side: the case goes to `disagree`
|
||||
// (Admin > /api/admin/hub) for Marty, since an InstantAdPay member bound on our contract cannot move anyway.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let R = null, st = null, chain_ = Promise.resolve(), timer = null, sending = false, interval = null;
|
||||
const MAX_UP = 25, EVENT_TRIES = 5, OUT_TRIES = 20, KEEP_DONE = 5000;
|
||||
const SHELL_ORIGINS = new Set(['linkspin', 'btc4hits', 'hub']);
|
||||
const DELIBERATE = new Set(['adopt', 'rescue', 'release', 'expire', 'expiry', 'admin']); // sponsorfollow.js kinds the hub accepts // came here from another site: that site tells the hub itself
|
||||
const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim());
|
||||
const URL_ = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
|
||||
const SITE = () => String(process.env.HUB_SITE || 'iap').trim().toLowerCase();
|
||||
const on = () => enabled() && !!URL_() && SECRET().length >= 32;
|
||||
const norm = v => String(v || '').trim().toLowerCase();
|
||||
const FILE = () => path.join(R.dataDir, 'hubsync.json');
|
||||
function load() {
|
||||
if (st) return st;
|
||||
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
||||
if (!st || typeof st !== 'object') st = {};
|
||||
st.since = Number(st.since) || Date.now(); // only accounts made after the flag first went on are reported as joins
|
||||
st.done = st.done || {}; st.tries = st.tries || {}; st.outbox = st.outbox || []; st.reported = st.reported || {};
|
||||
st.disagree = st.disagree || {}; st.log = st.log || [];
|
||||
st.stats = Object.assign({ batches: 0, events: 0, applied: 0, skipped: 0, ignored: 0, gaveUp: 0, sent: 0, refused: 0, sendErrors: 0 }, st.stats || {});
|
||||
return st;
|
||||
}
|
||||
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('hubsync save', e.message); } }
|
||||
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
|
||||
// deps: { dataDir, accounts, lsinbound }
|
||||
function init(deps) { R = deps; load(); save(); }
|
||||
|
||||
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
|
||||
function verify(headers, raw) {
|
||||
if (SECRET().length < 32) return false;
|
||||
const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || '');
|
||||
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return false;
|
||||
const want = sign(ts, raw);
|
||||
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
|
||||
}
|
||||
async function hubPost(p, body, timeout) {
|
||||
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||
const r = await fetch(URL_() + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(timeout || 15000) });
|
||||
let j = null; try { j = await r.json(); } catch (e) {}
|
||||
return { status: r.status, body: j };
|
||||
}
|
||||
async function resolve(q) {
|
||||
const r = await hubPost('/v1/resolve', q);
|
||||
if (r.status !== 200) throw new Error('hub resolve ' + r.status);
|
||||
return (r.body && r.body.person) || null;
|
||||
}
|
||||
const doorOf = p => norm(p && p.firstDoor && p.firstDoor.site).replace(/[^a-z0-9_-]/g, '').slice(0, 30) || 'network';
|
||||
// Rule 2 (Marty 2026-11-14): the sponsor written here is the one the InstantAdPay CONTRACT holds for them when it holds them
|
||||
// (person.locks.iap), never the plain network sponsor, which may come from another contract where they spent money
|
||||
const CONTRACT = 'iap';
|
||||
const sponsorFor = p => { const l = p && p.locks && p.locks[CONTRACT]; if (l) return (l.sponsor && l.sponsor.email) || null; return (p && p.sponsor && p.sponsor.email) || null; };
|
||||
const rowOf = p => ({ email: norm(p.email), username: p.username || null, wallet: p.wallet || null, sponsorEmail: sponsorFor(p), joinedAt: Number(p.firstDoor && p.firstDoor.at) || null, profile: null });
|
||||
|
||||
// what InstantAdPay and the hub each say the sponsor is; a difference is recorded, never forced
|
||||
async function compare(email, hubSponsorEmail, how) {
|
||||
const sp = await R.accounts.sponsorOf(email); const here = sp ? norm(sp.email) : null; const there = norm(hubSponsorEmail) || null;
|
||||
const s = load();
|
||||
if (here === there) { delete s.disagree[email]; return; }
|
||||
s.disagree[email] = { at: Date.now(), iap: here, hub: there, how };
|
||||
}
|
||||
|
||||
async function memberJoined(ev) {
|
||||
if (norm(ev.data && ev.data.site) === SITE()) return 'own';
|
||||
const first = await resolve({ id: ev.personId });
|
||||
if (!first || !first.email) return first ? 'no-email' : 'unknown'; // the hub must give this site seeEmails
|
||||
if (first.blocked) return 'blocked';
|
||||
const email = norm(first.email); const A = R.accounts;
|
||||
const existing = await A.byEmail(email);
|
||||
const rows = [rowOf(first)]; const doors = { [email]: doorOf(first) }; const seen = new Set([email]);
|
||||
if (existing && !A.isUnclaimedShell(existing)) rows[0].wallet = null; // a real account links its own wallet here
|
||||
// sponsors not on InstantAdPay yet come along as waiting accounts too (lsinbound builds them from rows in the same batch)
|
||||
let p = first;
|
||||
for (let i = 0; i < MAX_UP && sponsorFor(p); i++) {
|
||||
const se = norm(sponsorFor(p)); if (seen.has(se) || await A.byEmail(se)) break;
|
||||
const up = await resolve({ email: se }); if (!up || !up.email || up.blocked) break;
|
||||
seen.add(se); rows.push(rowOf(up)); doors[se] = doorOf(up); p = up;
|
||||
}
|
||||
const sum = await R.lsinbound.receive(rows, { via: 'hub', refOf: e => 'hub:' + (doors[e] || 'network') });
|
||||
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
|
||||
await compare(email, rows[0].sponsorEmail, 'hub-join');
|
||||
note({ type: 'joined', email, door: doors[email], created: sum ? sum.created : 0, existed: !!existing });
|
||||
return 'applied';
|
||||
}
|
||||
async function walletConnected(ev) {
|
||||
const p = await resolve({ id: ev.personId });
|
||||
if (!p || !p.email || !p.wallet || p.blocked) return 'skip';
|
||||
const a = await R.accounts.byEmail(p.email);
|
||||
if (!a) return 'not-here'; // member.joined makes the account; a wallet alone does not
|
||||
if (!R.accounts.isUnclaimedShell(a) || a.address) return 'kept'; // claimed accounts link their own wallet here
|
||||
const sum = await R.lsinbound.receive([rowOf(p)], { via: 'hub', refOf: () => 'hub:' + doorOf(p) });
|
||||
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
|
||||
return 'applied';
|
||||
}
|
||||
async function apply(ev) {
|
||||
if (ev.type === 'member.joined') return memberJoined(ev);
|
||||
if (ev.type === 'wallet.connected') return walletConnected(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.
|
||||
return 'ignored';
|
||||
}
|
||||
function prune() {
|
||||
const s = load(); const seqs = Object.keys(s.done).map(Number).sort((a, b) => a - b);
|
||||
for (const q of seqs.slice(0, Math.max(0, seqs.length - KEEP_DONE))) delete s.done[q];
|
||||
}
|
||||
async function handle(events) {
|
||||
const s = load(); s.stats.batches++; let failed = null;
|
||||
for (const ev of Array.isArray(events) ? events : []) {
|
||||
const seq = Number(ev && ev.seq); if (!seq) continue;
|
||||
if (s.done[seq]) { s.stats.skipped++; continue; } // delivered twice: already applied
|
||||
s.stats.events++;
|
||||
try {
|
||||
const r = await apply(ev);
|
||||
s.done[seq] = Date.now(); delete s.tries[seq];
|
||||
if (r === 'applied') s.stats.applied++; else s.stats.ignored++;
|
||||
} catch (e) {
|
||||
s.tries[seq] = (s.tries[seq] || 0) + 1;
|
||||
console.error('hubsync event', seq, ev.type, e.message);
|
||||
if (s.tries[seq] >= EVENT_TRIES) { s.done[seq] = Date.now(); delete s.tries[seq]; s.stats.gaveUp++; note({ type: 'gave-up', seq, event: ev.type, error: String(e.message).slice(0, 160) }); continue; }
|
||||
failed = e; break; // answer 503: the hub sends this one (and everything after it) again
|
||||
}
|
||||
}
|
||||
prune(); save();
|
||||
return failed ? { status: 503, body: { error: 'retry' } } : { status: 200, body: { ok: true } };
|
||||
}
|
||||
// the POST /api/hub/events handler: { status, body }. Batches run one at a time.
|
||||
function receive(headers, raw) {
|
||||
if (!R || !enabled()) return Promise.resolve({ status: 404, body: { error: 'not found' } });
|
||||
if (!verify(headers, raw)) return Promise.resolve({ status: 401, body: { error: 'unauthorized' } });
|
||||
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return Promise.resolve({ status: 400, body: { error: 'bad json' } }); }
|
||||
const run = chain_.then(() => handle(b.events)); chain_ = run.catch(() => {}); return run;
|
||||
}
|
||||
|
||||
// ---------- outbound ----------
|
||||
function enqueue(kind, email) {
|
||||
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
||||
s.outbox.push({ kind, email, at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
||||
}
|
||||
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(e => console.error('hubsync flush', e.message)); }, 2000); }
|
||||
// accounts.onChange: a new account made here, or a later username / sponsor change on any account, goes to /v1/join;
|
||||
// a deliberate sponsor change also goes to /v1/sponsor-change
|
||||
function touch(email) {
|
||||
if (!R || !on() || !email) return;
|
||||
(async () => {
|
||||
const e = norm(email); const a = await R.accounts.byEmail(e); const s = load();
|
||||
if (!a || SHELL_ORIGINS.has(a.joinedVia)) return;
|
||||
const sp = await R.accounts.sponsorOf(e); const spE = sp ? norm(sp.email) : '';
|
||||
const key = (a.username || '') + '|' + spE;
|
||||
const rep = s.reported[e];
|
||||
if (!rep) { s.reported[e] = { u: a.username || null, k: key }; enqueue('join', e); } // new here, or an older member's first change since the flag
|
||||
else if (rep.k !== key) { rep.u = a.username || null; rep.k = key; enqueue('join', e); }
|
||||
const rec = R.follow && R.follow.get ? R.follow.get(e) : null;
|
||||
if (rec && DELIBERATE.has(rec.by) && norm(rec.sponsorEmail) === spE && Number(rec.at) > 0 && s.reported[e].sc !== Number(rec.at)) {
|
||||
s.reported[e].sc = Number(rec.at); enqueue('sponsor', e);
|
||||
}
|
||||
save();
|
||||
})().catch(err => console.error('hubsync touch', err.message));
|
||||
}
|
||||
// chain.onEvent (once across copies): a payout switch-on on the InstantAdPay contract goes to /v1/contract-bind
|
||||
function onChain(ev) {
|
||||
if (ev && ev.type === 'Purchase') return onPurchase(ev);
|
||||
if (!R || !on() || !ev || ev.type !== 'MemberActivated' || !ev.account) return;
|
||||
(async () => {
|
||||
let spW = null; try { const m = ev.sponsorId ? await R.chain.member(ev.sponsorId) : null; spW = m && m.account ? norm(m.account) : null; } catch (e) {}
|
||||
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
||||
s.outbox.push({ kind: 'bind', email: norm(ev.account), wallet: norm(ev.account), sponsorWallet: spW, at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
||||
})().catch(err => console.error('hubsync onChain', err.message));
|
||||
}
|
||||
// chain.onEvent: money paid into the InstantAdPay contract (Purchase with POL in) goes to /v1/contract-spend (Marty 2026-11-14,
|
||||
// rule 2: when two contracts hold different sponsors, the one with money spent decides the network sponsor). Keyed by the
|
||||
// buyer's position wallet, the same key as its bind, so the bind is always sent first; the tx hash makes a resend count once.
|
||||
// A 404 (bind not there yet, or a linked extra position the hub does not know) is retried like any other miss.
|
||||
function onPurchase(ev) {
|
||||
if (!R || !on() || !ev.buyerId || !(Number(ev.priceCents) > 0)) return;
|
||||
try { if (BigInt(ev.paidWei || '0') <= 0n) return; } catch (e) { return; } // nothing paid in: not a spend
|
||||
(async () => {
|
||||
const m = await R.chain.member(ev.buyerId); const w = m && m.account ? norm(m.account) : null; if (!w) return;
|
||||
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
||||
s.outbox.push({ kind: 'spend', email: w, wallet: w, cents: Number(ev.priceCents), tx: ev.tx || null, paidAt: Number(ev.ts) || Date.now(), at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
||||
})().catch(err => console.error('hubsync onPurchase', err.message));
|
||||
}
|
||||
// accounts.onWalletLinked: a main wallet linked here goes to /v1/wallet
|
||||
function wallet(email) {
|
||||
if (!R || !on() || !email) return;
|
||||
(async () => {
|
||||
const a = await R.accounts.byEmail(email);
|
||||
if (a && a.address && !R.accounts.isUnclaimedShell(a)) enqueue('wallet', norm(email)); // a waiting account's wallet came from a sync
|
||||
})().catch(err => console.error('hubsync wallet', err.message));
|
||||
}
|
||||
// sponsorfollow / tank.js label a window expiry 'expire'; the hub (and its DELIBERATE list) calls it 'expiry' (fixed 2026-11-15:
|
||||
// before, IAP window-expiry moves never reached the hub as a sponsor change)
|
||||
const HUB_BY = { expire: 'expiry' };
|
||||
const hubBy = by => HUB_BY[by] || by;
|
||||
const ROUTE = { join: '/v1/join', wallet: '/v1/wallet', sponsor: '/v1/sponsor-change', bind: '/v1/contract-bind', spend: '/v1/contract-spend' };
|
||||
async function bodyFor(item) {
|
||||
if (item.kind === 'spend') {
|
||||
let owner = null; try { owner = (await R.accounts.byAddress(item.wallet)) || (R.accounts.positionOwner ? await R.accounts.positionOwner(item.wallet) : null); } catch (e) {}
|
||||
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, cents: item.cents, tx: item.tx || undefined, at: item.paidAt };
|
||||
}
|
||||
if (item.kind === 'bind') {
|
||||
let owner = null; try { owner = await R.accounts.byAddress(item.wallet); } catch (e) {}
|
||||
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, sponsorRef: item.sponsorWallet || '' };
|
||||
}
|
||||
const a = await R.accounts.byEmail(item.email); if (!a) return null;
|
||||
if (item.kind === 'sponsor') {
|
||||
const sp = await R.accounts.sponsorOf(a.email); const rec = R.follow && R.follow.get ? R.follow.get(a.email) : null;
|
||||
if (!rec || !DELIBERATE.has(rec.by) || norm(rec.sponsorEmail) !== (sp ? norm(sp.email) : '')) return null; // superseded since
|
||||
return { email: a.email, sponsorEmail: sp ? sp.email : null, by: hubBy(rec.by) };
|
||||
}
|
||||
if (item.kind === 'wallet') return a.address ? { email: a.email, wallet: a.address } : null;
|
||||
const sp = await R.accounts.sponsorOf(a.email);
|
||||
return { email: a.email, ref: sp ? sp.email : (a.sponsorRef || undefined), username: a.username || undefined };
|
||||
}
|
||||
async function flush(force) { // force (tests, admin): ignore the backoff wait
|
||||
if (!R || !on() || sending) return { skipped: true };
|
||||
sending = true; const s = load(); const now = Date.now(); const held = new Set(); let sent = 0;
|
||||
try {
|
||||
for (const item of s.outbox.slice()) {
|
||||
if (held.has(item.email)) continue; // keep each member's calls in order (join before wallet)
|
||||
if (item.next > now && !force) { held.add(item.email); continue; }
|
||||
const drop = (why, code) => { s.outbox.splice(s.outbox.indexOf(item), 1); if (why) note({ type: 'out-' + why, kind: item.kind, email: item.email, code: code || null }); };
|
||||
let r = null;
|
||||
try {
|
||||
const body = await bodyFor(item); if (!body) { drop('gone'); save(); continue; }
|
||||
r = await hubPost(ROUTE[item.kind] || '/v1/wallet', body);
|
||||
} catch (e) { r = { status: 0, body: { error: e.message } }; }
|
||||
const code = (r.body && r.body.error) || null;
|
||||
if (r.status >= 200 && r.status < 300) {
|
||||
drop(null); s.stats.sent++; sent++;
|
||||
if (item.kind === 'join' && r.body && r.body.person) await compare(item.email, r.body.person.sponsor && r.body.person.sponsor.email, 'iap-join');
|
||||
} else if ((r.status === 400 || r.status === 409) || (r.status === 403 && code === 'blocked') || (item.kind === 'sponsor' && r.status === 404)) {
|
||||
drop('refused', code); s.stats.refused++;
|
||||
} else {
|
||||
item.tries++; s.stats.sendErrors++;
|
||||
if (item.tries >= OUT_TRIES) drop('gave-up', code || String(r.status));
|
||||
else { item.next = now + Math.min(3600000, 30000 * Math.pow(2, item.tries)); held.add(item.email); }
|
||||
}
|
||||
save();
|
||||
}
|
||||
} finally { sending = false; }
|
||||
return { sent, waiting: s.outbox.length };
|
||||
}
|
||||
// password sign-ups do not fire accounts.onChange until they pick a username: every 10 minutes, any account made here since
|
||||
// the flag went on that the hub has not heard about yet is queued
|
||||
async function reconcile() {
|
||||
if (!R || !on()) return { skipped: true };
|
||||
const s = load(); let queued = 0;
|
||||
for (const a of await R.accounts.listAll(1e6)) {
|
||||
const e = norm(a.email);
|
||||
if (!e || s.reported[e] || SHELL_ORIGINS.has(a.joinedVia) || Number(a.created) < s.since) continue;
|
||||
s.reported[e] = { u: a.username || null }; s.outbox.push({ kind: 'join', email: e, at: Date.now(), tries: 0, next: 0 }); queued++;
|
||||
}
|
||||
if (queued) { save(); kick(); }
|
||||
return { queued };
|
||||
}
|
||||
function start() {
|
||||
if (interval) return;
|
||||
interval = setInterval(() => flush().catch(e => console.error('hubsync flush', e.message)), 30000);
|
||||
const rec = setInterval(() => reconcile().catch(e => console.error('hubsync reconcile', e.message)), 10 * 60000);
|
||||
for (const t of [interval, rec]) if (t.unref) t.unref();
|
||||
}
|
||||
// ---------- rule 3: the holding tank asks the hub (Marty 2026-11-14) ----------
|
||||
// The tank never offers anyone locked on ANY network contract, or anyone the hub already knows a sponsor for. tank.js asks
|
||||
// through its hooks (networkHeld, networkLocked, network); server.js wires them only with HUB_ENABLED, so with the flag off
|
||||
// the tank works exactly as before. One /v1/locked {emails, detail} call per 2,000 emails, cached per email: fresh for 10
|
||||
// minutes. CONSERVATIVE when the hub cannot be reached: the last answer stands for up to 1 hour, after that the person is
|
||||
// held ('unknown', not offered, not moved to the tank, not auto-assigned) until the hub answers again. A held tank for a
|
||||
// while is the safe side; offering someone a contract already holds is not. After a failed call the hub is left alone
|
||||
// for 2 minutes (page views must not each wait for a timeout).
|
||||
const HELD_FRESH_MS = 10 * 60000, HELD_STALE_MS = 60 * 60000, HELD_DOWN_MS = 2 * 60000, HELD_CHUNK = 2000;
|
||||
const held = new Map(); let heldDownUntil = 0, heldBusy = Promise.resolve();
|
||||
async function refreshHeld(emails, timeout) {
|
||||
const run = heldBusy.then(async () => {
|
||||
const now = Date.now(); const miss = emails.filter(e => { const c = held.get(e); return !c || now - c.at > HELD_FRESH_MS; });
|
||||
if (!miss.length || now < heldDownUntil) return;
|
||||
try {
|
||||
for (let i = 0; i < miss.length; i += HELD_CHUNK) {
|
||||
const part = miss.slice(i, i + HELD_CHUNK);
|
||||
const r = await hubPost('/v1/locked', { emails: part, detail: true, ids: true }, timeout || 5000); // ids: hub id + door per row (a hub without it ignores the flag)
|
||||
if (r.status !== 200 || !r.body || !r.body.found || typeof r.body.found !== 'object') throw new Error('hub locked ' + r.status);
|
||||
if (held.size > 60000) held.clear();
|
||||
const at = Date.now(); for (const e of part) held.set(e, { at, row: r.body.found[e] || null });
|
||||
}
|
||||
} catch (e) { heldDownUntil = Date.now() + HELD_DOWN_MS; load().stats.heldErrors = (load().stats.heldErrors || 0) + 1; console.log('hubsync: hub /v1/locked unreachable:', e.message); }
|
||||
});
|
||||
heldBusy = run.catch(() => {}); return run;
|
||||
}
|
||||
const whyHeld = (c, now) => (!c || now - c.at > HELD_STALE_MS ? 'unknown' : c.row && c.row.locked ? 'locked' : c.row && c.row.sponsored ? 'sponsored' : null);
|
||||
// accounts -> Map email -> 'locked' | 'sponsored' | 'unknown' for the ones the tank must not offer
|
||||
async function heldAmong(accts, opts) {
|
||||
const out = new Map(); if (!R || !on()) return out;
|
||||
const emails = [...new Set((accts || []).map(a => norm(a && a.email)).filter(Boolean))]; if (!emails.length) return out;
|
||||
await refreshHeld(emails, opts && opts.timeout);
|
||||
const now = Date.now(); for (const e of emails) { const w = whyHeld(held.get(e), now); if (w) out.set(e, w); }
|
||||
return out;
|
||||
}
|
||||
// release, rescue and expiry moves: 'locked' (on any network contract) | 'unknown' (hub not answering) | null
|
||||
async function lockedAnywhere(email) {
|
||||
if (!R || !on()) return null; const e = norm(email); if (!e) return null;
|
||||
await refreshHeld([e]); const w = whyHeld(held.get(e), Date.now());
|
||||
return w === 'locked' || w === 'unknown' ? w : null;
|
||||
}
|
||||
// the sponsor the hub knows for a tank member, for tank.alignToNetwork: this contract's lock first, else the network sponsor
|
||||
// OFF unless HUB_TANK_ALIGN=on: aligning moves sponsors (and on LinkSpin a linked wallet then has its payouts switched on, which
|
||||
// locks that sponsor on the contract), so the first run over a full tank is Marty's deliberate step, not a side effect of the
|
||||
// deploy. While it is off the people the hub knows a sponsor for are simply held out of the tank (rule 3).
|
||||
const alignOn = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_TANK_ALIGN || '').trim());
|
||||
async function hubSponsor(email) {
|
||||
if (!R || !on() || !alignOn()) return null; const e = norm(email); if (!e) return null;
|
||||
await refreshHeld([e]); const c = held.get(e); if (!c || !c.row || Date.now() - c.at > HELD_STALE_MS) return null;
|
||||
const l = c.row.locks && Object.prototype.hasOwnProperty.call(c.row.locks, CONTRACT) ? c.row.locks[CONTRACT] : undefined;
|
||||
const sp = norm(l !== undefined ? l : c.row.sponsorEmail);
|
||||
return sp && sp !== e ? { sponsorEmail: sp, via: l !== undefined ? 'network hub, InstantAdPay contract' : 'network hub' } : null;
|
||||
}
|
||||
|
||||
// the hub id and first door of a person the tank cache holds (5xYourTeam draft pool, 2026-11-15): { id, door } | null. Read-only, no call.
|
||||
function hubInfo(email) { const c = held.get(norm(email)); return c && c.row && c.row.id ? { id: c.row.id, door: c.row.door || null } : null; }
|
||||
function adminView() {
|
||||
const s = load();
|
||||
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; } };
|
||||
+2
-2
@@ -133,7 +133,7 @@ async function renderPage() {
|
||||
const fmtD = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, month: 'short', day: 'numeric' });
|
||||
const desc = 'Who is selling the most ad packages on InstantAdPay this week and this month. Weekly and monthly referral contest standings, read from the chain.';
|
||||
let h = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leaderboard | InstantAdPay</title><meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="https://instantadpay.com/leaderboard"><meta property="og:title" content="InstantAdPay leaderboard"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:image" content="https://instantadpay.com/banners/iap-hero-1200x630.png"><meta name="twitter:card" content="summary_large_image">'
|
||||
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261101th">'
|
||||
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln">'
|
||||
+ '<style>.lbw{max-width:860px}.lb{width:100%;border-collapse:collapse;margin:8px 0 26px;font-variant-numeric:tabular-nums}.lb th{text-align:left;color:var(--muted);font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--line)}.lb td{padding:10px;border-bottom:1px solid var(--line)}.lb tr:first-child + tr td:first-child{color:var(--gold);font-weight:800}.prize{border-left:4px solid var(--mint);background:var(--mint-soft);padding:12px 16px;border-radius:0 12px 12px 0;margin:0 0 18px}.win{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px;margin:0 0 10px}</style></head><body><div class="wrap lbw">'
|
||||
+ '<section class="hero" style="padding:56px 0 8px"><p class="eyebrow">Referral contest</p><h1>Leaderboard: <em>who is selling</em>.</h1><p class="lead">Ranked by ad packages sold to other people (your own positions never count, and the company account is not a contestant). Read from the chain, updated live. Weeks run Monday to Sunday, Central time.</p></section>';
|
||||
h += '<h2 style="font-size:24px;margin:0 0 4px">' + week.label + ' <span class="muted small">' + fmtD(week.start) + ' to Sunday</span></h2>' + (week.prize ? '<div class="prize"><b>Weekly prizes:</b> ' + esc(week.prize) + '</div>' : '') + table(week);
|
||||
@@ -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=20261023ov"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
h += '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
return h;
|
||||
}
|
||||
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
|
||||
|
||||
+5
-4
@@ -127,7 +127,7 @@ async function place(email, depth, ctx) {
|
||||
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
|
||||
if (sp) tok = tokenOf(sp); else { s.pending[email] = r.sponsorEmail; ctx.sum.pendingSponsor++; }
|
||||
}
|
||||
const x = await A.ensure(email, tok, 'linkspin', 'linkspin');
|
||||
const x = await A.ensure(email, tok, ctx.via || 'linkspin', ctx.refOf ? ctx.refOf(email) : 'linkspin'); // hubsync.js passes its own via (2026-11-12)
|
||||
if (!x || x.error) { conflict(ctx.sum, email, 'create', x && x.error); return null; }
|
||||
a = x.account;
|
||||
if (x.created) { ctx.sum.created++; wrote = true; note({ type: 'shell', email, sponsor: tok || null, pending: tok ? null : (r.sponsorEmail || null) }); }
|
||||
@@ -156,10 +156,10 @@ async function resolvePending(ctx) {
|
||||
note({ type: 'sponsored', email, sponsor: tokenOf(sp) });
|
||||
}
|
||||
}
|
||||
async function handle(rows) {
|
||||
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() }; const batch = [];
|
||||
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); }
|
||||
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 {
|
||||
@@ -176,7 +176,8 @@ async function handle(rows) {
|
||||
return Object.assign({ proto: SF.PROTO }, sum); // proto 2: this side understands sponsor follow + network tank facts
|
||||
}
|
||||
// batches are applied one at a time (two overlapping posts must not both create the same sponsor shell)
|
||||
function receive(rows) { const run = chain_.then(() => handle(rows)); chain_ = run.catch(() => {}); return run; }
|
||||
// opts (hubsync.js only): { via, refOf(email) } names where a new waiting account came from; LinkSpin's posts pass none
|
||||
function receive(rows, opts) { const run = chain_.then(() => handle(rows, opts)); chain_ = run.catch(() => {}); return run; }
|
||||
function adminView() {
|
||||
const s = load();
|
||||
return Object.assign({}, s.stats, { knownRows: Object.keys(s.rows).length, pendingSponsors: Object.keys(s.pending).length, last: s.last || null, lastError: s.stats.lastError || null, recent: s.log.slice(-25).reverse() });
|
||||
|
||||
@@ -32,6 +32,7 @@ async function rowFor(acct, byRef, tankMap) {
|
||||
const ref = String(acct.sponsorRef || '').toLowerCase(); let sponsorEmail = null;
|
||||
if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; }
|
||||
const row = { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
|
||||
if (acct.joinedVia === 'btc4hits') row.origin = 'btc4hits'; // BTC4Hits import (2026-11-11): LinkSpin words its holding-tank mail for them
|
||||
if (R.follow) Object.assign(row, SF.rowFields(R.follow.get(acct.email), sponsorEmail) || {});
|
||||
const T = R.tank && R.tank();
|
||||
if (T) { try { row.tank = (tankMap ? tankMap.get(String(acct.email).toLowerCase()) : await T.summaryFor(acct.email)) || null; } catch (e) {} }
|
||||
@@ -74,10 +75,14 @@ async function push(rows) {
|
||||
}
|
||||
st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent;
|
||||
}
|
||||
// QUIET (Marty 2026-11-14, "join one = join all"): a waiting account the network hub made here (joinedVia 'hub', never signed
|
||||
// in) is never pushed to LinkSpin. The hub tells LinkSpin itself, quietly; pushed from here, LinkSpin's registry route would
|
||||
// link the wallet and its engine would switch payouts on and email them. Once they sign in here they sync like anyone.
|
||||
const hubShell = a => !!a && a.joinedVia === 'hub' && R.accounts.isUnclaimedShell && R.accounts.isUnclaimedShell(a);
|
||||
// an account just changed: send its row shortly (debounced so a join + username + wallet in a row go as one)
|
||||
function touch(email) {
|
||||
if (!on() || !email) return; pending.set(String(email).toLowerCase(), Date.now());
|
||||
if (!timer) timer = setTimeout(async () => { timer = null; const st = load(); const emails = [...pending.keys()].filter(e => !muted.has(e)); for (const e of emails) pending.delete(e); try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a) { const r = await rowFor(a); if (st.hashes[r.email] !== hashOf(r)) rows.push(r); } } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000);
|
||||
if (!timer) timer = setTimeout(async () => { timer = null; const st = load(); const emails = [...pending.keys()].filter(e => !muted.has(e)); for (const e of emails) pending.delete(e); try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a && !hubShell(a)) { const r = await rowFor(a); if (st.hashes[r.email] !== hashOf(r)) rows.push(r); } } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000);
|
||||
}
|
||||
// the reconcile pass: only rows whose hash changed since the last push
|
||||
async function tick(force) {
|
||||
@@ -87,7 +92,7 @@ async function tick(force) {
|
||||
const all = await R.accounts.listAll(50000, { shells: true }); const st = load();
|
||||
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); }
|
||||
const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } }
|
||||
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
|
||||
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email) || hubShell(a)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
|
||||
const sent = rows.length ? await push(rows) : 0;
|
||||
return { accounts: all.length, changed: rows.length, sent };
|
||||
} catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; }
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
// The network sites list for the footer's "Part of the network" line (Marty 2026-11-14 trust pack).
|
||||
// One source: the hub's public GET /v1/network-sites (HUB_URL). Cached 10 minutes, refreshed in the background, never waits on a
|
||||
// slow hub (2.5 s timeout), and falls back to the same built-in list. Never RM Circle, never the games.
|
||||
// The same file lives in every network site (InstantAdPay, LinkSpin, Downline Banners, VBB, Stack POL).
|
||||
const FALLBACK = [
|
||||
{ id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' },
|
||||
{ id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' },
|
||||
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' },
|
||||
{ id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' },
|
||||
{ id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
|
||||
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }
|
||||
];
|
||||
const TTL = 10 * 60 * 1000;
|
||||
let cache = { at: 0, list: FALLBACK, from: 'fallback' };
|
||||
let inflight = null;
|
||||
|
||||
const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, '');
|
||||
function clean(list) {
|
||||
if (!Array.isArray(list)) return null;
|
||||
const ok = list.filter(s => s && typeof s.name === 'string' && /^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(s.url || '')))
|
||||
.slice(0, 30).map(s => ({ id: String(s.id || s.name).toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 30), name: String(s.name).slice(0, 60), url: String(s.url).replace(/\/+$/, '') }));
|
||||
return ok.length ? ok : null;
|
||||
}
|
||||
function refresh() {
|
||||
if (inflight || process.env.NETWORK_SITES_HUB === '0') return inflight;
|
||||
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500);
|
||||
inflight = fetch(hubUrl() + '/v1/network-sites', { signal: ac.signal })
|
||||
.then(r => (r.ok ? r.json() : null))
|
||||
.then(j => { const l = clean(j); if (l) cache = { at: Date.now(), list: l, from: 'hub' }; else cache.at = Date.now(); })
|
||||
.catch(() => { cache.at = Date.now() - TTL + 60 * 1000; }) // hub down: try again in a minute, keep the last good list
|
||||
.finally(() => { clearTimeout(t); inflight = null; });
|
||||
return inflight;
|
||||
}
|
||||
function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list; }
|
||||
// Tracked links (Marty 2026-11-14: "make sure each of these sites is its own traffic source and link spun so we can track it"): each
|
||||
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
|
||||
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
|
||||
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
|
||||
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
||||
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
|
||||
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||
function selfId(req, l) {
|
||||
const env = String(process.env.NETWORK_SITE_ID || '').trim().toLowerCase(); if (env) return env;
|
||||
const h = String((req && req.headers && (req.headers['x-forwarded-host'] || req.headers.host)) || '').split(',')[0].trim().toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '');
|
||||
const m = h && (l || list()).find(s => hostOf(s.url) === h); return m ? m.id : '';
|
||||
}
|
||||
// the LinkSpin-tracked link to site `id` sent from site `from` (from = id: the site's own promo kit); extra = { s1: member username, s2: one path segment }
|
||||
function tracked(id, from, extra) {
|
||||
const code = CODES[id]; if (!code || !from) return '';
|
||||
const q = new URLSearchParams({ src: from }); for (const [k, v] of Object.entries(extra || {})) if (v) q.set(k, String(v));
|
||||
return linksBase() + '/r/' + code + '?' + q.toString();
|
||||
}
|
||||
function withGo(l, me) { return l.map(s => { const go = me && s.id !== me ? tracked(s.id, me) : ''; return go ? Object.assign({}, s, { go }) : s; }); }
|
||||
// GET /api/network-sites: public, cacheable, the same answer on every page
|
||||
function handle(req, res) {
|
||||
const l = list();
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' });
|
||||
res.end(JSON.stringify(withGo(l, selfId(req, l))));
|
||||
}
|
||||
module.exports = { list, handle, refresh, tracked, selfId, withGo, CODES, FALLBACK, _state: () => cache };
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each
|
||||
// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes.
|
||||
//
|
||||
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
|
||||
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
|
||||
// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P.
|
||||
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
|
||||
// P mints a token bound to R, the state and the email, and sends the browser
|
||||
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
|
||||
// 3. R GET /sso/in?t=<token> R checks signature, audience, expiry (60 s), the state against its cookie
|
||||
// (so nobody can push their own token into someone else's browser), and spends
|
||||
// the nonce (a second use is refused). The email must already be a member
|
||||
// here; then R makes an ordinary session and redirects to the relative path.
|
||||
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
|
||||
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
|
||||
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
|
||||
// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
|
||||
// bots and non-page fetches never bounce.
|
||||
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
|
||||
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
|
||||
//
|
||||
// Wallet sites (Downline Banners, 2026-11-13, Marty: "sign in once and be logged into all these sites"). Downline Banners has no email
|
||||
// accounts; its members are wallets. IAP and LinkSpin list it under `wallets: { bannerline: base }` and vouch one way: /go/bannerline
|
||||
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
|
||||
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
|
||||
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim();
|
||||
const enabled = () => SECRET().length >= 32;
|
||||
const TTL = 60 * 1000; // token life
|
||||
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
||||
const STATE_AGE = 300; // seconds: the state cookie
|
||||
const GO_STATE_AGE = 1200; // seconds: the state cookie on a deliberate tap (time to sign in on the provider first, 2026-11-14)
|
||||
const BACK_AGE = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in
|
||||
const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes
|
||||
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 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,
|
||||
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } }
|
||||
|
||||
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||
const mac = s => crypto.createHmac('sha256', SECRET()).update('nsso.v1.' + s).digest();
|
||||
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
||||
const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || '');
|
||||
|
||||
// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters.
|
||||
function safePath(to, dflt) {
|
||||
const d = dflt == null ? '/' : dflt;
|
||||
const s = String(to == null ? '' : to);
|
||||
if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d;
|
||||
try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; }
|
||||
}
|
||||
|
||||
function mint(o) {
|
||||
const now = o.now || Date.now();
|
||||
const t = { iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
|
||||
if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
|
||||
if (o.name) t.name = String(o.name).slice(0, 40);
|
||||
const body = b64u(JSON.stringify(t));
|
||||
return 'v1.' + body + '.' + b64u(mac(body));
|
||||
}
|
||||
|
||||
// -> { ok, email, to, n, exp } or { error: reason }
|
||||
function verify(tok, o) {
|
||||
if (!enabled()) return { error: 'off' };
|
||||
const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
|
||||
if (!m) return { error: 'malformed' };
|
||||
const want = mac(m[1]), got = unb64u(m[2]);
|
||||
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
|
||||
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
|
||||
const now = (o && o.now) || Date.now();
|
||||
if (!p || p.aud !== o.aud || ![].concat(o.iss).includes(p.iss)) return { error: 'audience' };
|
||||
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
|
||||
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
|
||||
const st = String((o && o.st) || '');
|
||||
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
|
||||
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
|
||||
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
|
||||
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||
}
|
||||
|
||||
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
|
||||
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
|
||||
const used = new Map(); let fileLoaded = false, tableReady = null;
|
||||
const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null;
|
||||
function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); }
|
||||
function loadFile() {
|
||||
if (fileLoaded) return; fileLoaded = true;
|
||||
try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {}
|
||||
}
|
||||
function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } }
|
||||
async function spend(n, exp) {
|
||||
const now = Date.now(); loadFile(); prune(now);
|
||||
if (used.has(n)) return false;
|
||||
used.set(n, Number(exp) + SKEW); saveFile();
|
||||
const db = C && C.db;
|
||||
if (db && db.enabled && db.enabled()) {
|
||||
try {
|
||||
if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; });
|
||||
await tableReady;
|
||||
await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]);
|
||||
if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {});
|
||||
} catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// crawlers, link previews and headless browsers never bounce
|
||||
const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i;
|
||||
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); };
|
||||
// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser)
|
||||
const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; };
|
||||
|
||||
function cookies(req) {
|
||||
const out = {};
|
||||
for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } }
|
||||
return out;
|
||||
}
|
||||
const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : '');
|
||||
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
|
||||
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
|
||||
|
||||
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); }
|
||||
|
||||
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
|
||||
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
||||
|
||||
// -> true when the request was one of ours and has been answered
|
||||
async function handle(req, res, u) {
|
||||
if (!C || req.method !== 'GET') return false;
|
||||
const p = u.pathname;
|
||||
const peerName = NAMES[C.peer] || C.peer;
|
||||
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
|
||||
const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
|
||||
if (goTo && (goTo === C.peer || walletBase(goTo))) {
|
||||
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
|
||||
const to = safePath(u.searchParams.get('to'), '/');
|
||||
const plain = base + to;
|
||||
if (!enabled() || isBot(req)) return go(res, plain);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (!s || !s.email) return go(res, plain);
|
||||
if (goTo !== C.peer) { let w = null; try { w = await C.wallet(s); } catch (e) {} if (!w || !w.address) return go(res, plain); } // no wallet to vouch for: a plain link
|
||||
return go(res, base + '/sso/start?mode=go' + (goTo === C.peer ? '' : '&via=' + C.self) + '&to=' + encodeURIComponent(to));
|
||||
}
|
||||
if (p === '/sso/start') {
|
||||
const to = safePath(u.searchParams.get('to'), C.defaultPath);
|
||||
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
|
||||
const via = String(u.searchParams.get('via') || '');
|
||||
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
|
||||
if (!enabled() || isBot(req) || notPage(req)) return go(res, to);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (s && (s.email || s.address)) return go(res, to); // already signed in here
|
||||
const c = cookies(req);
|
||||
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
|
||||
const st = crypto.randomBytes(16).toString('hex');
|
||||
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
||||
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
||||
}
|
||||
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
|
||||
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
|
||||
const clear = [ck('nsso.back', '', 0, true)];
|
||||
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
|
||||
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')), clear);
|
||||
}
|
||||
if (p === '/sso/check') {
|
||||
const st = String(u.searchParams.get('st') || '');
|
||||
const to = safePath(u.searchParams.get('to'), '/');
|
||||
const r = String(u.searchParams.get('r') || '');
|
||||
const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
|
||||
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud;
|
||||
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
||||
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (!s || !s.email) {
|
||||
if (u.searchParams.get('m') === 'go' && !isBot(req)) { // a deliberate tap: sign in here first, then /sso/resume finishes the trip
|
||||
log('check: not signed in here, asking to sign in', null, 'for ' + forName);
|
||||
const back = new URLSearchParams({ st, to }); if (r) back.set('r', r);
|
||||
return go(res, C.signinPath(C.defaultPath), [ck('nsso.back', back.toString(), BACK_AGE, true)]);
|
||||
}
|
||||
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
|
||||
}
|
||||
let w = null;
|
||||
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
|
||||
log('token issued', s.email, 'for ' + forName);
|
||||
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
|
||||
}
|
||||
if (p === '/sso/in') {
|
||||
const c = cookies(req);
|
||||
const set = [ck('nsso.st', '', 0, true)];
|
||||
if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); }
|
||||
const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
|
||||
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
|
||||
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
|
||||
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
|
||||
if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in
|
||||
log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email);
|
||||
set.push(ck('nsso.hint', v.email, HINT_AGE, true));
|
||||
return go(res, C.signinPath(v.to), set);
|
||||
}
|
||||
let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); }
|
||||
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
|
||||
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||
log('signed in from ' + (NAMES[v.iss] || peerName), v.email);
|
||||
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
|
||||
}
|
||||
if (p === '/api/sso/status') {
|
||||
const c = cookies(req); const set = [];
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
const signedIn = !!(s && (s.email || s.address));
|
||||
const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
||||
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
|
||||
return sendJson(res, out, set);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
|
||||
const pendingBack = req => !!cookies(req)['nsso.back'];
|
||||
|
||||
module.exports = { init, handle, enabled, pendingBack, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
|
||||
+4
-3
@@ -7,7 +7,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.adm-table{width:100%;table-layout:auto}
|
||||
.adm-table th{cursor:pointer;user-select:none;white-space:nowrap}
|
||||
@@ -270,6 +270,7 @@
|
||||
<button type="button" class="btn small sec" data-mcact="sponsor">Set sponsor</button>
|
||||
<button type="button" class="btn small sec" data-mcact="wallet">Swap main wallet</button>
|
||||
<button type="button" class="btn small sec" data-mcact="credits">Grant credits</button>
|
||||
<button type="button" class="btn small sec" data-mcact="message">Message (inbox + email)</button>
|
||||
<a class="btn small sec" id="mcWall" href="#" target="_blank" rel="noopener">Public wall</a>
|
||||
<button type="button" class="btn small sec" data-mcact="delete" style="margin-left:auto">Delete account</button>
|
||||
</div>
|
||||
@@ -651,8 +652,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/assets/common.js?v=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
||||
<script src="/assets/admin.js?v=20261107tg"></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=20261112txt"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-kits.js?v=20261101th"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+10
-1
@@ -544,6 +544,14 @@
|
||||
if (act === 'sponsor') { const v = await IAP.ask({ title: 'Sponsor for ' + (a.username ? '@' + a.username : a.email), text: 'Username, share code or member #. Blank = no sponsor (company). Re-points free referrals and future purchases; on-chain sponsorship never changes.', value: a.sponsorRef || '', ok: 'Save' }); if (v === null || v === undefined) return; body = { sponsorRef: v }; }
|
||||
if (act === 'wallet') { const v = await IAP.ask({ title: 'Main wallet for ' + a.email, text: 'Paste the 0x address that should be their main wallet (the one that paid, if a purchase came from an unlinked account). The member number is re-read from the chain. Blank = unlink.', value: a.address || '', ok: 'Swap' }); if (v === null || v === undefined) return; if (!await IAP.confirmBox('Swap the main wallet for ' + a.email + ' to ' + (v.trim() || 'nothing') + '?', { title: 'Sure?', ok: 'Swap it', cancel: 'Cancel' })) return; body = { address: v }; }
|
||||
if (act === 'credits') { const v = await IAP.ask({ title: 'Grant credits to ' + (a.username ? '@' + a.username : a.email), text: 'Whole number of earned-pool credits (1 credit = 1 cent of delivery). They can spend them on campaigns right away.', type: 'number', value: '', placeholder: '250', ok: 'Grant' }); if (!v) return; const note = await IAP.ask({ title: 'Reason (kept in the server log)', value: '', placeholder: 'e.g. refund for broken banner', ok: 'Grant' }); body = { grantCredits: v, note: note || '' }; }
|
||||
// message the member (Marty 2026-11-12): lands in their member inbox AND emails them (opt-outs honoured by the mailer)
|
||||
if (act === 'message') {
|
||||
const who = a.username ? '@' + a.username : a.email;
|
||||
const subject = await IAP.ask({ title: 'Message ' + who, text: 'Subject line. The message goes to their member inbox and is emailed to them (unless they unsubscribed from email).', value: '', placeholder: 'A quick note from Marty', ok: 'Next' }); if (!subject) return;
|
||||
const text = await IAP.ask({ title: subject, text: 'Your message. Plain text; blank lines start new paragraphs.', type: 'textarea', value: '', ok: 'Send' }); if (!text || !text.trim()) return;
|
||||
const r = await api('/api/admin/member/message', { email: a.email, subject, text }, 'POST');
|
||||
IAP.status('Sent to ' + who + "'s inbox" + (r.emailed ? ' and emailed.' : r.emailSkipped ? '. Email skipped: ' + r.emailSkipped + '.' : '.'), r.emailed ? 'ok' : 'warn'); return;
|
||||
}
|
||||
if (act === 'delete') {
|
||||
if (a.memberId) { IAP.status('Registered members cannot be deleted; their position is on-chain.', 'bad'); return; }
|
||||
if (!await IAP.confirmBox('Delete the free account ' + a.email + '? Their sign-in, referrals link and credits go away. There is no undo.', { title: 'Delete account', ok: 'Delete', cancel: 'Keep it' })) return;
|
||||
@@ -1137,7 +1145,8 @@
|
||||
loginCreditsPerDay: ['Login ad: credits per day', 'flat daily charge while active'],
|
||||
loginDwellSeconds: ['Login ad: seconds shown', 'full-screen interstitial after sign-in'],
|
||||
burnBatchMin: ['On-chain burn batch (credits)', 'accrued spend is burned once it reaches this'],
|
||||
synRateDivisor: ['Network rate divisor (N)', 'Network Ad Space views and PassiveDrip visits cost 1/N of the on-site rate; 1 = same rate as on-site; whole numbers'],
|
||||
synRateDivisor: ['Network rate divisor (N)', 'Network Ad Space banner views and PassiveDrip visits cost 1/N of the on-site rate; 1 = same rate as on-site; whole numbers'],
|
||||
synRateDivisorText: ['Network rate divisor for TEXT ads (N)', 'Network Ad Space text-ad views cost 1/N of the on-site text rate (10 = 1 credit per 100 network views); whole numbers'],
|
||||
welcomeCredits: ['Welcome credits', 'granted after the welcome tour'],
|
||||
dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'],
|
||||
dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'],
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 212 KiB |
@@ -0,0 +1,122 @@
|
||||
// Chasing Unicorns (Marty, 2026-11-12): a promo-tool lead magnet. A fake earnings dashboard where every button, tile and popup
|
||||
// is one of the classic scam warning signs; clicking one reveals it and scores the visitor's "scam radar", and the ending
|
||||
// contrasts the unicorn with how InstantAdPay works. Shared as /chasing-unicorns?ref=<username> (the viral ?ref= link sets the
|
||||
// sponsor cookie server-side). Nothing here touches an account: it is all made up on the page.
|
||||
(function () {
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
var usd = function (n) { return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); };
|
||||
var calm = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
var FLAGS = {
|
||||
daily: { name: 'A fixed daily return', short: 'Guaranteed % a day on your deposit',
|
||||
h: 'Nobody pays a fixed 3% a day.', p: 'That is over 4 million percent a year, compounded. No business earns that. The only way to pay a fixed daily return is with the next person\'s deposit.',
|
||||
tell: 'Your "interest" is a line of code adding to a number. Watch it: it goes up even though nothing happened.', do: 'Ask what the product is and who buys it. If the answer is "the return", walk away.' },
|
||||
withdraw: { name: 'Withdrawals that never arrive', short: 'Always "processing"',
|
||||
h: 'Withdrawal processing... forever.', p: 'Deposits are instant. Withdrawals need "verification", a "maintenance window", a new minimum. That is how a site with no money buys time.',
|
||||
tell: 'The balance on screen is not money. Money is what lands in your own wallet or bank.', do: 'Withdraw a small amount early. If $20 is a hostage negotiation, you have your answer.' },
|
||||
vip: { name: 'Pay to unlock your own money', short: 'Upgrade or "release fee" first',
|
||||
h: 'Pay $199 to unlock your own $25,000?', p: 'The "upgrade", the "tax", the "release fee", a "small miner fee" or "gas fee". It always sounds minor next to the balance waiting for you. It is the oldest trick: the balance is bait, and the fee is the real product. Some sites are free right up until the countdown ends, then everybody gets the fee at once.',
|
||||
tell: 'If the money were there, they would take the fee out of it. They want new money from you instead.', do: 'Never pay to withdraw. A real balance pays its own fees.' },
|
||||
team: { name: 'The product is recruiting', short: 'Paid mainly for sign-ups',
|
||||
h: '+$500 per sign-up. Paid with what?', p: 'If you earn for bringing people in and nobody is buying anything real, the money for your bonus comes from the people you brought in.',
|
||||
tell: 'A team bonus with no product is your friends\' deposits with your name on them.', do: 'Ask: if nobody new joined tomorrow, where would the money come from?' },
|
||||
clock: { name: 'The clock is always ticking', short: 'Countdowns and "spots left"',
|
||||
h: 'The countdown resets. It always does.', p: 'Urgency is there to stop you thinking and to get you recruiting before you check anything. Watch the timer: when it hits zero, it starts over.',
|
||||
tell: 'A good opportunity is still there after you sleep on it. A bad one needs you not to.', do: 'Wait 48 hours and search the name plus "withdrawal" and "scam" first.' },
|
||||
coin: { name: 'Paid in their own coin', short: 'Tokens you cannot sell anywhere real',
|
||||
h: '48,000 UYP, worth whatever they say.', p: 'A token you can only "sell" back on their own site is Monopoly money with better branding. They print it, they price it, they decide when you can sell.',
|
||||
tell: '"Soon x100" is a promise from the people holding all the supply.', do: 'Check whether it trades anywhere real, with real volume, and who holds most of it.' },
|
||||
keys: { name: 'Anything that touches your keys', short: '"Connect wallet to claim"',
|
||||
h: 'Connect wallet to claim? That is the scam.', p: 'Claim pages ask you to sign an approval that lets them spend your tokens. Some ask for your seed phrase outright. Nobody legit ever needs either.',
|
||||
tell: 'One signature can empty a wallet. The "airdrop" is the bait.', do: 'Never type a seed phrase into a website. Read what a signature approves before you sign it.' },
|
||||
proof: { name: 'Fake social proof', short: 'People "cashing out" every few seconds',
|
||||
h: '"Dave from Denver just withdrew $19,350."', p: 'These popups are a few lines of code picking a random name and a random amount. They are on scam sites because they work on all of us.',
|
||||
tell: 'A popup is not a receipt. A transaction you can look up is.', do: 'Ask for a payment you can verify yourself, on a public ledger, not a screenshot.' }
|
||||
};
|
||||
var ORDER = ['daily', 'withdraw', 'vip', 'team', 'clock', 'coin', 'keys', 'proof'];
|
||||
var seen = [];
|
||||
|
||||
// the visitor's sponsor rides the share link (?ref=), so the join button and the share line keep it
|
||||
var ref = (new URLSearchParams(location.search).get('ref') || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
|
||||
// where the page link was posted (?src=massifly, ?src=leasedadspace...) rides into the join, so a sign-up says which channel
|
||||
var chan = (new URLSearchParams(location.search).get('src') || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 18);
|
||||
var srcTag = chan ? 'unicorns-' + chan : 'chasing-unicorns';
|
||||
$('joinBtn').href = '/join?src=' + srcTag;
|
||||
if (ref) {
|
||||
$('joinBtn').href = '/join/' + ref + '?src=' + srcTag;
|
||||
$('ledgerBtn').href = '/ledger?ref=' + ref;
|
||||
$('shareLink').textContent = 'https://instantadpay.com/chasing-unicorns?ref=' + ref;
|
||||
}
|
||||
|
||||
// radar
|
||||
var dots = $('dots'); ORDER.forEach(function () { dots.appendChild(document.createElement('i')); });
|
||||
function renderRadar() {
|
||||
[].forEach.call(dots.children, function (d, i) { d.className = i < seen.length ? 'on' : ''; });
|
||||
$('score').textContent = seen.length + ' of 8';
|
||||
$('endH').textContent = seen.length === 8 ? 'Scam radar: 8 of 8. You are a unicorn hunter.' : 'Your scam radar: ' + seen.length + ' of 8 red flags spotted';
|
||||
$('flags').innerHTML = ORDER.map(function (k) { var f = FLAGS[k]; return '<li class="' + (seen.indexOf(k) >= 0 ? 'on' : '') + '"><b>' + f.name + '</b><span class="fine">' + f.short + '</span></li>'; }).join('');
|
||||
document.querySelectorAll('[data-flag]').forEach(function (b) { b.classList.toggle('done', seen.indexOf(b.getAttribute('data-flag')) >= 0); });
|
||||
if (seen.length >= 3) $('after').hidden = false;
|
||||
}
|
||||
renderRadar();
|
||||
|
||||
// the reveal card
|
||||
var lastFocus = null;
|
||||
function reveal(k) {
|
||||
var f = FLAGS[k]; if (!f) return;
|
||||
if (seen.indexOf(k) < 0) seen.push(k);
|
||||
renderRadar();
|
||||
$('cardK').textContent = 'Red flag ' + seen.length + ' of 8 spotted: ' + f.name;
|
||||
$('cardH').textContent = f.h; $('cardP').textContent = f.p;
|
||||
$('cardTell').textContent = f.tell; $('cardDo').textContent = 'What to do: ' + f.do;
|
||||
$('cardNext').textContent = seen.length === 8 ? 'See my result' : 'Keep hunting';
|
||||
lastFocus = document.activeElement; $('veil').hidden = false; $('cardNext').focus();
|
||||
}
|
||||
function closeCard(toEnd) {
|
||||
$('veil').hidden = true;
|
||||
if (toEnd || seen.length === 8) $('end').scrollIntoView({ behavior: calm ? 'auto' : 'smooth', block: 'start' });
|
||||
else if (lastFocus) lastFocus.focus();
|
||||
}
|
||||
document.querySelectorAll('[data-flag]').forEach(function (b) { b.addEventListener('click', function () { reveal(b.getAttribute('data-flag')); }); });
|
||||
$('cardNext').addEventListener('click', function () { closeCard(false); });
|
||||
$('cardEnd').addEventListener('click', function () { closeCard(true); });
|
||||
$('veil').addEventListener('click', function (e) { if (e.target === $('veil')) closeCard(false); });
|
||||
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !$('veil').hidden) closeCard(false); });
|
||||
$('showAll').addEventListener('click', function () { ORDER.forEach(function (k) { if (seen.indexOf(k) < 0) seen.push(k); }); renderRadar(); $('after').scrollIntoView({ behavior: calm ? 'auto' : 'smooth', block: 'start' }); });
|
||||
$('copyShare').addEventListener('click', function () {
|
||||
var t = $('shareLink').textContent, b = $('copyShare');
|
||||
navigator.clipboard.writeText(t).then(function () { b.textContent = 'Copied'; }, function () { var r = document.createRange(); r.selectNodeContents($('shareLink')); var s = getSelection(); s.removeAllRanges(); s.addRange(r); b.textContent = 'Press Ctrl+C'; });
|
||||
});
|
||||
|
||||
// the ticking balance: 3% a day of $25,000, out of thin air
|
||||
var START = 25000, perSec = START * 0.03 / 86400, t0 = performance.now(), midnight = new Date(); midnight.setHours(0, 0, 0, 0);
|
||||
function tick() {
|
||||
var gain = (performance.now() - t0) / 1000 * perSec;
|
||||
$('bal').textContent = usd(START + gain);
|
||||
$('rate').textContent = '+3.00% daily compound interest · +' + usd(gain) + ' since you opened this page';
|
||||
$('today').textContent = usd((Date.now() - midnight.getTime()) / 1000 * perSec);
|
||||
}
|
||||
tick(); setInterval(tick, calm ? 1000 : 100);
|
||||
|
||||
// the countdown that starts over at zero, and spots that never run out
|
||||
var LEN = 600, end = Date.now() + LEN * 1000, spots = 3;
|
||||
setInterval(function () {
|
||||
var left = Math.round((end - Date.now()) / 1000);
|
||||
if (left <= 0) { end = Date.now() + LEN * 1000; left = LEN; spots = 3; }
|
||||
else if (left % 89 === 0 && spots > 1) spots--;
|
||||
$('clock').textContent = String(Math.floor(left / 60)).padStart(2, '0') + ':' + String(left % 60).padStart(2, '0');
|
||||
$('spots').textContent = 'Only ' + spots + ' VIP spot' + (spots === 1 ? '' : 's') + ' left';
|
||||
}, 1000);
|
||||
|
||||
// fake "cash out" popups every few seconds: random made-up names and amounts
|
||||
var who = ['Jessica from Ohio', 'Mike in Texas', 'Priya from London', 'Carlos in Miami', 'Ahmed from Dubai', 'Linda in Phoenix', 'Tom from Sydney', 'Grace in Toronto', 'Dave from Denver', 'Nina in Berlin', 'Kwame from Accra', 'Rosa in Manila'];
|
||||
var what = ['just withdrew', 'just cashed out', 'just earned', 'just got a team bonus of'];
|
||||
function pop() {
|
||||
var n = who[Math.floor(Math.random() * who.length)], amt = Math.round((Math.random() * 40000 + 1500) / 10) * 10;
|
||||
$('pAv').textContent = n.charAt(0);
|
||||
$('pT').innerHTML = n + ' ' + what[Math.floor(Math.random() * what.length)] + ' <b>' + usd(amt) + '</b> ' + (1 + Math.floor(Math.random() * 9)) + ' min ago';
|
||||
$('proof').classList.add('on');
|
||||
setTimeout(function () { $('proof').classList.remove('on'); }, 4500);
|
||||
}
|
||||
setTimeout(function () { pop(); setInterval(pop, 8000); }, 3000);
|
||||
})();
|
||||
+43
-1
@@ -57,9 +57,36 @@ window.IAP = (function () {
|
||||
f.innerHTML = '<div>© ' + new Date().getFullYear() + ' InstantAdPay</div>'
|
||||
+ '<div style="margin-top:8px;display:flex;gap:16px;justify-content:center;flex-wrap:wrap">'
|
||||
+ '<a href="/">How it works</a><a href="/presentation">Presentation</a><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/blog">Blog</a><a href="/leaderboard">Leaderboard</a><a href="/whats-new">What\'s new</a>'
|
||||
+ '<a href="/facts">Platform facts</a><a href="/support">Support</a><a href="/terms">Terms</a><a href="/privacy">Privacy</a><a href="/disclaimer">Disclaimer</a></div>';
|
||||
+ '<a href="/facts">Platform facts</a><a href="/support">Support</a><a href="/terms">Terms</a><a href="/disclaimer">Earnings Disclaimer</a><a href="/privacy">Privacy</a></div>'
|
||||
+ '<div style="margin-top:10px">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</div>';
|
||||
document.body.appendChild(f);
|
||||
renderNetworkLine(f);
|
||||
}
|
||||
// "Part of the network" (Marty 2026-11-14 trust pack): the list comes from the hub through /api/network-sites, built-in copy if not
|
||||
const NET_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(a => ({ id: a[0], name: a[1], url: a[2] }));
|
||||
let netList = null;
|
||||
async function networkSites() {
|
||||
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;
|
||||
}
|
||||
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 => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[ch]);
|
||||
const paint = list => {
|
||||
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('');
|
||||
};
|
||||
paint(NET_FALLBACK);
|
||||
networkSites().then(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); }); }
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', decorateFooters); else decorateFooters();
|
||||
async function refreshNavWallet() {
|
||||
try {
|
||||
const me = await (await fetch('/api/me')).json();
|
||||
@@ -308,3 +335,18 @@ window.IAP = (function () {
|
||||
els.forEach(function (e) { e.hidden = false; });
|
||||
}).catch(function () {});
|
||||
})();
|
||||
|
||||
// Network links (2026-11-13): a click on a link to LinkSpin goes through /go/linkspin, which signs a signed-in member in over there and is a
|
||||
// plain redirect for everyone else. Rewritten at click time only, so links people copy to share stay clean. data-nogo opts a link out.
|
||||
(function () {
|
||||
if (window.__netlinks) return; window.__netlinks = 1;
|
||||
const HOSTS = ['linkspin.app', 'www.linkspin.app'];
|
||||
document.addEventListener('click', e => {
|
||||
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||
const a = e.target && e.target.closest ? e.target.closest('a[href]') : null;
|
||||
if (!a || a.hasAttribute('download') || a.hasAttribute('data-nogo')) return;
|
||||
let u; try { u = new URL(a.href); } catch (x) { return; }
|
||||
if (u.protocol !== 'https:' || !HOSTS.includes(u.hostname)) return;
|
||||
a.href = '/go/linkspin?to=' + encodeURIComponent(u.pathname + u.search + u.hash);
|
||||
}, true);
|
||||
})();
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
const TASK = { tracking: 'conversions', start: 'refuel', refuel: 'refuel', pitstop: 'refuel', bannerspin: 'bannerspin', testing: 'testing', relaunch: 'ads', topup: 'ads', cut: 'ads', cruise: 'ads' };
|
||||
let FROM = 'iap';
|
||||
const siteOf = u => /linkspin/i.test(u.host) ? 'linkspin' : 'iap'; // which site a link belongs to, by its host (also right on a local copy)
|
||||
const go = (url, task) => { try { const u = new URL(url); if (u.host === location.host || siteOf(u) === FROM) return u.pathname + u.search + u.hash; if (task) { u.searchParams.set('from', FROM); u.searchParams.set('task', task); } return u.href; } catch (e) { return url; } };
|
||||
// a link to the other site goes through this site's /go/<other> hop (network sign-in, 2026-11-12): the member arrives signed in
|
||||
const go = (url, task) => { try { const u = new URL(url); if (u.host === location.host || siteOf(u) === FROM) return u.pathname + u.search + u.hash; if (task) { u.searchParams.set('from', FROM); u.searchParams.set('task', task); } return '/go/' + (FROM === 'iap' ? 'linkspin' : 'iap') + '?to=' + encodeURIComponent(u.pathname + u.search + u.hash); } catch (e) { return url; } };
|
||||
// "Refuel LinkSpin this cycle..." gets a way there (2026-10-25): the other site's buy screen, tagged for its arrival strip
|
||||
const otherBuy = note => { const m = /^Refuel (LinkSpin|InstantAdPay) /.exec(note || ''); if (!m) return '';
|
||||
const url = m[1] === 'LinkSpin' ? 'https://linkspin.app/credits#refuel' : 'https://instantadpay.com/my#buy';
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
let twin = '';
|
||||
if (!v.windowOpen && c.month && !c.both) twin = '<p class="small">Refuel ' + (c.iap && c.iap.refueled ? 'LinkSpin ($' + v.minUsd.linkspin + '+)' : 'InstantAdPay ($' + v.minUsd.iap + '+)') + ' before ' + esc(v.opensLabel) + ' and both sites move to <b>+' + v.next.secondEngine + '%</b>; the one you already refueled is topped up to match.'
|
||||
// the second engine is on the other site: a direct way there (2026-10-25), landing on LinkSpin's Refuel panel with an arrival strip
|
||||
+ (c.iap && c.iap.refueled ? ' <a href="https://linkspin.app/credits?from=iap&task=refuel#refuel" target="_blank" rel="noopener">Refuel LinkSpin ↗</a> (same email signs you in)' : '') + '</p>';
|
||||
+ (c.iap && c.iap.refueled ? ' <a href="/go/linkspin?to=%2Fcredits%3Ffrom%3Diap%26task%3Drefuel%23refuel" target="_blank" rel="noopener">Refuel LinkSpin ↗</a> (same email signs you in)' : '') + '</p>';
|
||||
let pit = '';
|
||||
if (v.pitStop) {
|
||||
const here = v.pitStop.iap ? 'available here (+' + v.pitStop.pct + '% on a $' + v.minUsd.iap + '+ top-up, once this cycle)' : v.pitStop.usedIap ? 'used here this cycle' : null;
|
||||
|
||||
+46
-14
@@ -345,20 +345,30 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
{ k: 'payouts', label: 'Payouts on', t: m => !!m.activated },
|
||||
{ k: 'nowallet', label: 'No wallet', t: m => !m.wallet },
|
||||
];
|
||||
const listState = key => LIST_UI[key] || (LIST_UI[key] = { sort: 'seen', dir: -1, on: new Set() });
|
||||
const listState = key => LIST_UI[key] || (LIST_UI[key] = { sort: 'seen', dir: -1, on: new Set(), q: '' });
|
||||
// search box (Marty, 2026-11-12: "a user can find their member in the list"): name, username, email or member number
|
||||
const listHay = m => [m.name, m.username, m.email, m.ref, m.src, m.memberId ? '#' + m.memberId : ''].filter(Boolean).join(' ').toLowerCase();
|
||||
function listApply(key, rows) {
|
||||
const st = listState(key); const s = LIST_SORTS.find(x => x.k === st.sort) || LIST_SORTS[0];
|
||||
const out = (rows || []).filter(m => m.own || [...st.on].every(k => { const f = LIST_FILTERS.find(x => x.k === k); return !f || f.t(m); }));
|
||||
const q = String(st.q || '').trim().toLowerCase().replace(/^@/, '');
|
||||
const out = (rows || []).filter(m => (!q || listHay(m).includes(q))
|
||||
&& (m.own || [...st.on].every(k => { const f = LIST_FILTERS.find(x => x.k === k); return !f || f.t(m); })));
|
||||
out.sort((a, b) => { const x = s.v(a), y = s.v(b); return (s.str ? String(x).localeCompare(String(y)) : x - y) * st.dir; });
|
||||
return out;
|
||||
}
|
||||
function listBar(key, total, shown, rerender, opts) {
|
||||
const st = listState(key); const hide = (opts && opts.hide) || [];
|
||||
const bar = document.createElement('div'); bar.className = 'lst-bar';
|
||||
bar.innerHTML = '<label class="lst-sort">Sort <select aria-label="Sort by">' + LIST_SORTS.map(s => '<option value="' + s.k + '"' + (s.k === st.sort ? ' selected' : '') + '>' + s.label + '</option>').join('') + '</select></label>'
|
||||
bar.innerHTML = '<input type="search" class="lst-q" placeholder="Find a member: name, username or email" aria-label="Find a member in this list" autocomplete="off" spellcheck="false">'
|
||||
+ '<label class="lst-sort">Sort <select aria-label="Sort by">' + LIST_SORTS.map(s => '<option value="' + s.k + '"' + (s.k === st.sort ? ' selected' : '') + '>' + s.label + '</option>').join('') + '</select></label>'
|
||||
+ '<button type="button" class="lst-dir" title="Flip the order">' + (st.dir < 0 ? '↓ high to low' : '↑ low to high') + '</button>'
|
||||
+ '<span class="lst-chips">' + LIST_FILTERS.filter(f => !hide.includes(f.k)).map(f => '<button type="button" class="lst-chip' + (st.on.has(f.k) ? ' on' : '') + '" data-f="' + f.k + '" aria-pressed="' + (st.on.has(f.k) ? 'true' : 'false') + '">' + f.label + '</button>').join('') + '</span>'
|
||||
+ '<span class="lst-n">' + (shown === total ? total + (total === 1 ? ' person' : ' people') : shown + ' of ' + total) + '</span>';
|
||||
// the list (and this bar with it) is rebuilt on every keystroke, so the new box takes the focus and caret back
|
||||
const qi = bar.querySelector('.lst-q'); qi.value = st.q || '';
|
||||
if (Date.now() - (st.qAt || 0) < 1000) setTimeout(() => { qi.focus(); const n = qi.value.length; try { qi.setSelectionRange(n, n); } catch (e) {} }, 0);
|
||||
let qt = null;
|
||||
qi.addEventListener('input', () => { clearTimeout(qt); qt = setTimeout(() => { st.q = qi.value; st.qAt = Date.now(); Object.keys(PAGE_AT).forEach(k => { if (k === key || k.startsWith(key + '-')) delete PAGE_AT[k]; }); rerender(); }, 150); }); // a new search starts on page 1
|
||||
bar.querySelector('select').addEventListener('change', e => { st.sort = e.target.value; st.dir = st.sort === 'name' ? 1 : -1; rerender(); });
|
||||
bar.querySelector('.lst-dir').addEventListener('click', () => { st.dir = -st.dir; rerender(); });
|
||||
bar.querySelectorAll('[data-f]').forEach(b => b.addEventListener('click', () => { const k = b.dataset.f; if (st.on.has(k)) st.on.delete(k); else st.on.add(k); rerender(); }));
|
||||
@@ -622,18 +632,28 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
}).join('');
|
||||
} catch (e) {}
|
||||
}
|
||||
// where a direct came from + how they joined (Marty, 2026-11-12: "it was kind of buried in there"). src = the first-touch
|
||||
// referring site, with the link's ?src= tag since 2026-11-12 ("mailer.gold/mailergold", or just "mailergold"); via = the path.
|
||||
const VIA_LABEL = { btc4hits: 'moved over from BTC4Hits', linkspin: 'came over from LinkSpin', page: 'your bridge page', direct: 'your invite link',
|
||||
'fw-earn': 'FaucetWave', 't1-adv': 'Tier1Ads', polminer: 'POL Miner', seek: 'ClutterHunt', polhunter: 'PolHunter', driprunner: 'Drip Runner', gemkingdom: 'Gem Kingdom', tank: 'adopted from the holding tank' };
|
||||
const srcLabel = s => !s ? '' : s === 'direct' ? 'no referring site' : s === 'linkspin' ? 'LinkSpin' : /^legacy:/.test(s) ? s.split(':')[1] : s;
|
||||
const originText = m => { const a = srcLabel(m.src), b = m.via ? (VIA_LABEL[m.via] || ('link "' + m.via + '"')) : '';
|
||||
return (a ? 'from ' + a : '') + (a && b ? ' · ' : '') + (b ? 'via ' + b : ''); };
|
||||
// visual line tree on the Overview: YOU + three levels, qualified directs in gold
|
||||
function renderRoster(wrap, all) {
|
||||
const rows = listApply('roster', all);
|
||||
wrap.querySelectorAll(':scope > .lst-bar, :scope > table, :scope > .pgr, :scope > .lst-none').forEach(n => n.remove());
|
||||
wrap.appendChild(listBar('roster', all.length, rows.length, () => renderRoster(wrap, all)));
|
||||
if (!rows.length) { wrap.insertAdjacentHTML('beforeend', '<p class="muted small lst-none">Nobody in your line matches those filters.</p>'); return; }
|
||||
if (!rows.length) { wrap.insertAdjacentHTML('beforeend', '<p class="muted small lst-none">Nobody in your line matches your search or filters.</p>'); return; }
|
||||
const t = document.createElement('table'); t.className = 'roster';
|
||||
t.innerHTML = rows.map(r => '<tr><td>' + esc(r.name || r.email || '') + '</td>'
|
||||
t.innerHTML = rows.map(r => '<tr><td>' + (r.email && /\*\*\*/.test(r.name || '') ? '<span class="muted">no username yet</span>' : esc(r.name ? (/^@|\*\*\*/.test(r.name) ? r.name : '@' + r.name) : r.email || ''))
|
||||
+ (r.email ? '<div class="small mono roster-em">' + esc(r.email) + ' <button type="button" class="lst-copy" data-copy="' + esc(r.email) + '" title="Copy email">copy</button></div>' : '')
|
||||
+ (originText(r) ? '<div class="muted small">' + esc(originText(r)) + '</div>' : '') + '</td>'
|
||||
+ '<td><span class="muted">joined</span> ' + new Date(r.joined).toLocaleDateString() + '</td>'
|
||||
+ '<td>' + memberChips(r) + '</td>'
|
||||
+ '<td><span class="badge' + (r.status === 'joined free' ? ' amber' : '') + '">' + esc(r.status) + '</span></td></tr>').join('');
|
||||
wrap.appendChild(t);
|
||||
t.querySelectorAll('[data-copy]').forEach(b => b.addEventListener('click', async () => { try { await navigator.clipboard.writeText(b.dataset.copy); IAP.status('Email copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the address and copy it.', 'bad'); } }));
|
||||
pageList('roster', wrap, 'table.roster tr', { per: LINE_PER });
|
||||
}
|
||||
async function loadLineTree(buyerCount) {
|
||||
@@ -841,6 +861,10 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
{ const tokP = d.username || d.refCode || d.memberId; const ps = $('promoPresStrip');
|
||||
if (ps && tokP) { const pl = 'https://instantadpay.com/presentation?ref=' + encodeURIComponent(tokP); ps.hidden = false; $('promoPresLink').textContent = pl; $('promoPresOpen').href = '/presentation?ref=' + encodeURIComponent(tokP);
|
||||
$('promoPresCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); IAP.status('Presentation link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; } }
|
||||
// Chasing Unicorns (2026-11-12): the scam-spotting lead magnet, shared with the member's ?ref= (the viral link sets the sponsor)
|
||||
{ const tokU = d.username || d.refCode || d.memberId; const us = $('promoUniStrip');
|
||||
if (us && tokU) { const ul = 'https://instantadpay.com/chasing-unicorns?ref=' + encodeURIComponent(tokU); us.hidden = false; $('promoUniLink').textContent = ul; $('promoUniOpen').href = '/chasing-unicorns?ref=' + encodeURIComponent(tokU);
|
||||
$('promoUniCopy').onclick = async () => { try { await navigator.clipboard.writeText(ul); IAP.status('Chasing Unicorns link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; } }
|
||||
if (d.username) { // wall link rides the username
|
||||
const wl = location.origin + '/wall/' + d.username;
|
||||
$('wallLine').textContent = wl;
|
||||
@@ -965,6 +989,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; }
|
||||
if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02)
|
||||
if (me.returnTo === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13)
|
||||
if (me.returnTo === 'nsso' && !render.toGame) { render.toGame = true; location.href = '/sso/resume'; return; } // tapped "Sign in with InstantAdPay" on another network site while signed out here (2026-11-14)
|
||||
if (me.returnTo === 'forum' && !render.toGame) { render.toGame = true; location.href = '/api/my/forum'; return; } // Earners Corner forum sign-in (2026-11-10)
|
||||
if (me.returnTo === 'polminer' && !render.toGame) { render.toGame = true; location.href = '/api/my/polminer'; return; } // POL Miner sent them here to sign in (2026-10-28)
|
||||
if (me.returnTo === 'warpwares' && !render.toGame) { render.toGame = true; location.href = '/api/my/warpwares'; return; } // Warp & Wares sent them here to sign in (2026-10-29)
|
||||
@@ -1310,10 +1335,13 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
tbl.className = 'tablewrap';
|
||||
// syndicated rate (Marty, 2026-10-27, 4:1): network views and partner visits cost 1/N of a view or visit here
|
||||
const synN = Math.max(1, Math.floor(Number(r.rates && r.rates.synRateDivisor) || 1));
|
||||
const netCell = c => ['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() + (synN > 1 && c.impsNas ? ' <span class="muted small">at 1/' + synN + '</span>' : '')
|
||||
// text ads have their own network rate since 2026-11-12 (Marty: 1/10, text budgets were gone in about a week)
|
||||
const synT = Math.max(1, Math.floor(Number(r.rates && r.rates.synRateDivisorText != null ? r.rates.synRateDivisorText : synN) || 1));
|
||||
const nOf = c => c.type === 'text' ? synT : synN;
|
||||
const netCell = c => ['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() + (nOf(c) > 1 && c.impsNas ? ' <span class="muted small">at 1/' + nOf(c) + '</span>' : '')
|
||||
: (c.type === 'visits' && c.impsSyn) ? c.impsSyn.toLocaleString() + ' <span class="muted small">partner visits' + (synN > 1 ? ', ' + synN + ' = 1 visit' : '') + '</span>'
|
||||
: '<span class="muted small" title="only banner and text ads syndicate to the network">n/a</span>';
|
||||
if (synN > 1) { const n = document.createElement('p'); n.className = 'muted small'; n.textContent = 'Views and visits here on InstantAdPay use credits at the normal rate. Your ads also run on Network Ad Space and partner sites, and that delivery costs a ' + (synN === 4 ? 'quarter' : '1/' + synN) + ' of the rate: ' + synN + ' network views cost what 1 view here does, and ' + synN + ' partner visits use up 1 visit of your pack. Your budget goes further and every credit still buys real delivery.'; el.appendChild(n); }
|
||||
if (synN > 1) { const n = document.createElement('p'); n.className = 'muted small'; n.textContent = 'Views and visits here on InstantAdPay use credits at the normal rate. Your ads also run on Network Ad Space and partner sites, and that delivery costs a ' + (synN === 4 ? 'quarter' : '1/' + synN) + ' of the rate: ' + synN + ' network views of a banner cost what 1 view here does, and ' + synN + ' partner visits use up 1 visit of your pack.' + (synT !== synN ? ' Text ads go further still: ' + synT + ' network views of a text ad cost what 1 view here does.' : '') + ' Your budget goes further and every credit still buys real delivery.'; el.appendChild(n); }
|
||||
tbl.innerHTML = '<table class="camp-table"><thead><tr><th>Name</th><th>Type</th><th class="num">Views here</th><th class="num" title="Impressions delivered by Network Ad Space across the wider network (banner and text ads), and visits from partner sites (visit packs)' + (synN > 1 ? ', at 1/' + synN + ' of the rate here' : '') + '">Network views</th><th class="num">Clicks</th>'
|
||||
+ '<th class="num">Spent</th><th class="num">Budget</th><th>Status</th><th></th></tr></thead><tbody>'
|
||||
+ r.campaigns.map(c => '<tr><td data-l="Campaign"><b>' + c.name + '</b>' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '<div class="muted small conv-line" data-convcamp="' + c.id + '" hidden></div></td>'
|
||||
@@ -1946,7 +1974,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
+ '<span class="em">joined ' + ago(w.joined) + '<span class="sp wrap">' + memberChips(w) + '</span></span>'
|
||||
+ '<span class="dt">last sign-in: <b>' + ago(w.lastSeen) + '</b></span>'
|
||||
+ (r.eligible && !opens(w) ? '<button class="btn small" type="button" data-adopt="' + esc(w.username || w.email) + '" data-aname="' + esc(w.name) + '">Adopt</button>' : '') + '</div>').join('')
|
||||
: '<p class="muted small">Nobody in the tank matches those filters.</p>');
|
||||
: '<p class="muted small">Nobody in the tank matches your search or filters.</p>');
|
||||
pageList('tank', el, ':scope > .lin-row', { per: LINE_PER });
|
||||
el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => {
|
||||
const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the InstantAdPay holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' });
|
||||
@@ -2092,9 +2120,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
if (!H || !H.show) return '';
|
||||
const btn = (key, label, pkg) => '<button class="btn small" type="button" data-hero-buy="' + esc(key) + '">' + esc(label) + ' · $' + pkg + ' package</button>';
|
||||
const item = i => '<div class="gp-tier' + (i.owned ? ' on' : '') + '"><h4>' + esc(i.name) + '</h4>'
|
||||
+ '<p class="gp-price">' + (i.free ? 'Free for everyone' : '$' + i.usd + ' <span class="small muted">one time</span>') + '</p>'
|
||||
+ '<p class="gp-price">' + (i.free ? 'Free for everyone' : i.freeAt ? 'Free at level ' + i.freeAt : '$' + i.usd + ' <span class="small muted">one time</span>') + '</p>'
|
||||
+ '<p class="small muted" style="margin:0 0 6px">' + esc(i.blurb) + '</p>'
|
||||
+ (i.owned ? '<p class="small"><b>Yours for good</b></p>' : i.waiting ? '<button class="btn small" type="button" data-gp-go="1">Buy a $' + i.package + ' package</button>' : i.open ? btn(i.key, 'Get ' + i.name.split(' ')[0], i.package) : '<span class="small muted">Not on sale right now.</span>') + '</div>';
|
||||
+ (i.owned ? '<p class="small"><b>Yours for good</b></p>' : i.freeAt ? '<span class="small muted">Not for sale: joins every player free in the game once a hero reaches level ' + i.freeAt + '.</span>' : i.waiting ? '<button class="btn small" type="button" data-gp-go="1">Buy a $' + i.package + ' package</button>' : i.open ? btn(i.key, 'Get ' + i.name.split(' ')[0], i.package) : '<span class="small muted">Not on sale right now.</span>') + '</div>';
|
||||
const B = H.bundle;
|
||||
const bundle = !B ? '' : '<div class="gp-tier' + (B.owned ? ' on' : '') + '"><h4>Hero bundle</h4><p class="gp-price">$' + B.usd + ' <span class="small muted">one time</span></p>'
|
||||
+ '<p class="small muted" style="margin:0 0 6px">' + esc(B.names.join(', ')) + ', together.</p>'
|
||||
@@ -2553,10 +2581,10 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
const kept = shown.reduce((n, L) => n + L.members.length, 0);
|
||||
el.innerHTML = '';
|
||||
el.appendChild(listBar('line', all, kept, () => renderLineage(el)));
|
||||
el.insertAdjacentHTML('beforeend', !kept ? '<p class="muted small">Nobody in your downline matches those filters.</p>' : shown.map(L => !L.members.length ? '' :
|
||||
el.insertAdjacentHTML('beforeend', !kept ? '<p class="muted small">Nobody in your downline matches your search or filters.</p>' : shown.map(L => !L.members.length ? '' :
|
||||
'<div class="lin-lvl"><div class="cap">Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '</div>'
|
||||
+ L.members.map(m => '<div class="lin-row' + (m.own ? ' own' : '') + '"><span class="nm">' + esc(m.name) + (m.own ? ' <span class="badge">yours</span>' : '') + '</span>'
|
||||
+ '<span class="em">' + (m.email ? esc(m.email) : (m.memberId ? '<span class="id">#' + m.memberId + '</span>' : '')) + (m.sponsor ? '<span class="sp">sponsored by ' + esc(m.sponsor) + '</span>' : '') + (m.own ? '' : '<span class="sp">' + (m.bought ? '$20+ buy ✓' : 'no $20+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '</span><span class="sp wrap">' + memberChips(m) + '</span>') + '</span>'
|
||||
+ '<span class="em">' + (m.email ? esc(m.email) : (m.memberId ? '<span class="id">#' + m.memberId + '</span>' : '')) + (m.sponsor ? '<span class="sp">sponsored by ' + esc(m.sponsor) + '</span>' : '') + (!m.own && originText(m) ? '<span class="sp">' + esc(originText(m)) + '</span>' : '') + (m.own ? '' : '<span class="sp">' + (m.bought ? '$20+ buy ✓' : 'no $20+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '</span><span class="sp wrap">' + memberChips(m) + '</span>') + '</span>'
|
||||
+ '<span class="earn' + (m.earnedWei && m.earnedWei !== '0' ? ' on' : '') + '" title="POL this person has paid you so far">'
|
||||
+ (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '</span>'
|
||||
+ '<span class="dt">' + new Date(m.joined).toLocaleDateString() + '</span>'
|
||||
@@ -2591,7 +2619,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; return Math.round(d / 86400e3) + 'd ago'; };
|
||||
const chip = (label, val, cls) => '<span class="lin-chip' + (cls ? ' ' + cls : '') + '"><b>' + esc(label) + '</b>' + esc(val) + '</span>';
|
||||
const working = (a.viewsToday || 0) > 0 || (a.campaignsActive || 0) > 0 || (a.linkViews30 || 0) > 0 || (a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3);
|
||||
box.innerHTML = chip('Last seen', ago(a.lastSeen), a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3 ? 'on' : (a.quietDays >= 3 ? 'warn' : ''))
|
||||
box.innerHTML = (a.direct && a.email ? chip('Email', a.email) : '') // your own directs only (2026-11-12)
|
||||
+ (a.direct && originText(a) ? chip('Came', originText(a)) : '')
|
||||
+ chip('Last seen', ago(a.lastSeen), a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3 ? 'on' : (a.quietDays >= 3 ? 'warn' : ''))
|
||||
+ chip('Joined', new Date(a.joined).toLocaleDateString())
|
||||
+ chip('Stage', (a.rung || 'Joined') + (a.next ? ' · next: ' + a.next : ''), a.stalled ? 'warn' : '')
|
||||
+ chip('Ads today', (a.viewsToday || 0) + '/' + (a.target || 5) + (a.claimedToday ? ' claimed' : '') + (a.streakDay ? ' · streak day ' + a.streakDay : ''), (a.viewsToday || 0) > 0 ? 'on' : '')
|
||||
@@ -2783,10 +2813,11 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
if ($('tkGo')) { $('tkGo').addEventListener('click', tkGenerate); $('tkAgain').addEventListener('click', tkGenerate); $('tkCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('tkText').value); IAP.status('Copied.', 'ok'); } catch (e) { $('tkText').select(); } }); $('tkSendBc').addEventListener('click', tkSendBroadcast); }
|
||||
// promo tools: pill menu switches between posts / swipes / banners / wall / videos
|
||||
function setPromoSub(name) {
|
||||
const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos', 'viral', 'stackpol', 'games', 'bixpay']; // bixpay: the BixPay partner kit, pill hidden while bixpayLive is off (2026-10-29)
|
||||
const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos', 'viral', 'stackpol', 'games', 'network', 'bixpay']; // bixpay: the BixPay partner kit, pill hidden while bixpayLive is off (2026-10-29)
|
||||
if (['polhunter', 'spookydoors', 'gamebanners'].includes(name)) name = 'games'; // those tabs live inside Games now (2026-10-06)
|
||||
if (name === 'toolkit') loadToolkit();
|
||||
if (name === 'stackpol') loadStackPol();
|
||||
if (name === 'network' && window.IAPNetKits) IAPNetKits.load(); // Network sites kits (2026-11-14), loaded when the tab opens
|
||||
const pill = document.querySelector('.promo-pills [data-promo="' + name + '"]');
|
||||
if (!ids.includes(name) || !pill || pill.hidden) name = 'posts';
|
||||
ids.forEach(id => { const el = $('promo-' + id); if (el) el.hidden = id !== name; });
|
||||
@@ -2925,6 +2956,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
// ── promo tools: content + rendering live in promo.js (IAPPromo.fill) ──
|
||||
function fillPromo(link, me) {
|
||||
if (window.IAPPromo) IAPPromo.fill(link, me || {});
|
||||
if (window.IAPNetKits && me && me.username) { IAPNetKits.setUser(me.username); const ns = $('promo-network'); if (ns && !ns.hidden) IAPNetKits.load(); }
|
||||
// banner kit
|
||||
const bwrap = $('promoBanners');
|
||||
if (bwrap && !bwrap.dataset.filled) {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// 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
|
||||
// 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.' }
|
||||
];
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const $ = id => document.getElementById(id);
|
||||
let user = '', cur = '', cache = {}, txt = [];
|
||||
try { cur = localStorage.getItem('iap.netkit') || ''; } catch (e) {}
|
||||
if (!SITES.some(s => s.key === cur)) cur = SITES[0].key;
|
||||
function setUser(u) { if (u && u !== user) { user = u; cache = {}; } }
|
||||
async function copy(t, btn) {
|
||||
try { await navigator.clipboard.writeText(t); } catch (e) { const a = document.createElement('textarea'); a.value = t; document.body.appendChild(a); a.select(); try { document.execCommand('copy'); } catch (e2) {} a.remove(); }
|
||||
if (window.IAP && IAP.status) IAP.status('Copied.', 'ok');
|
||||
if (btn) { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => { btn.textContent = o; }, 1300); }
|
||||
}
|
||||
const cb = (t, label, cls) => { txt.push(t); return '<button type="button" class="btn small ' + (cls == null ? 'sec' : cls) + '" data-nkc="' + (txt.length - 1) + '">' + esc(label || 'Copy') + '</button>'; };
|
||||
function pick() {
|
||||
const p = $('nkPick'); if (!p) return;
|
||||
p.innerHTML = SITES.map(s => '<button type="button" class="chip-t' + (s.key === cur ? ' on' : '') + '" data-nk="' + s.key + '">' + esc(s.name) + '</button>').join('');
|
||||
p.querySelectorAll('[data-nk]').forEach(b => b.addEventListener('click', () => { cur = b.dataset.nk; try { localStorage.setItem('iap.netkit', cur); } catch (e) {} pick(); show(); }));
|
||||
}
|
||||
function render(site, k) {
|
||||
txt = [];
|
||||
const by = {}; const angles = [];
|
||||
(k.creatives || []).forEach(c => { if (!by[c.angle]) { by[c.angle] = []; angles.push(c); } by[c.angle].push(c); });
|
||||
let h = '<p class="muted small" style="margin:0 0 12px">' + esc(site.blurb) + '</p>';
|
||||
// tracked links (2026-11-14): the site's LinkSpin network link, credited here to InstantAdPay as the site that sent the visit
|
||||
const strip = (label, url, cls) => '<div class="promo-strip" style="padding:0 0 12px"><div><span class="eyebrow" style="margin:0 0 4px">' + esc(label) + '</span><div class="mono small" style="overflow-wrap:anywhere">' + esc(url) + '</div></div><span>' + cb(url, 'Copy link', cls) + '</span></div>';
|
||||
const fromHere = u => String(u).replace(/([?&]src=)[a-z0-9]+/i, '$1iap');
|
||||
h += k.links.map(l => strip(l.label, l.url, '') + (l.tracked ? strip(l.label + ', tracked', fromHere(l.tracked), 'sec') : '')).join('');
|
||||
if (k.links.some(l => l.tracked)) h += '<p class="muted small" style="margin:0 0 12px">A tracked link goes through LinkSpin first, so the network can see the visit came from InstantAdPay, then opens the same page with your username. Use either one.</p>';
|
||||
h += '<div class="card-head" style="margin-top:6px"><h3>Creatives</h3><span class="sub">every HTML snippet already links to you</span></div>';
|
||||
angles.forEach(a => {
|
||||
h += '<details class="promo-block nk-set"' + (a === angles[0] ? ' open' : '') + '><summary class="pb-head" style="cursor:pointer"><span class="lab"><b>' + esc(a.angleLabel) + '</b></span> <span class="muted small">' + by[a.angle].length + ' sizes</span></summary><div class="nk-grid">'
|
||||
+ by[a.angle].map(c => '<figure class="nk-fig"><a href="' + esc(c.url) + '" target="_blank" rel="noopener"><img src="' + esc(c.url) + '" alt="' + esc(k.name + ', ' + c.label) + '" width="' + c.w + '" height="' + c.h + '" loading="lazy" style="max-width:' + Math.min(c.w, c.w > 600 ? 420 : c.w) + 'px"></a>'
|
||||
+ '<figcaption class="small"><b>' + esc(c.label) + '</b> <span class="muted">' + c.w + '×' + c.h + '</span></figcaption><div class="pb-actions"><a class="btn small sec" href="' + esc(c.url) + '" target="_blank" rel="noopener" download>Download</a> ' + cb(c.url, 'Copy URL') + ' ' + cb(c.html, 'Copy HTML') + '</div></figure>').join('')
|
||||
+ '</div></details>';
|
||||
});
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Short lines</h3><span class="sub">chats, comments, text ads, signatures</span></div>'
|
||||
+ k.lines.map(t => '<div class="promo-block"><div class="pb-text">' + esc(t) + '</div><div class="pb-actions">' + cb(t) + '</div></div>').join('');
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Headlines</h3></div>' + k.headlines.map(t => '<div class="promo-block"><div class="pb-text"><b>' + esc(t) + '</b></div><div class="pb-actions">' + cb(t) + '</div></div>').join('');
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Email</h3><span class="sub">plain text, paste it into any mailer</span></div><div class="promo-block"><div class="pb-head"><span class="lab">Subject:</span> ' + esc(k.email.subject) + '</div><div class="pb-text">' + esc(k.email.body) + '</div><div class="pb-actions">' + cb(k.email.subject, 'Copy subject') + ' ' + cb(k.email.body, 'Copy email', '') + '</div></div>';
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Social posts</h3></div>' + k.posts.map(t => '<div class="promo-block"><div class="pb-text">' + esc(t) + '</div><div class="pb-actions">' + cb(t, 'Copy post') + '</div></div>').join('');
|
||||
if (k.note) h += '<p class="muted small" style="margin:12px 0 0">' + esc(k.note) + '</p>';
|
||||
if (k.promotePage) h += '<p class="small" style="margin:8px 0 0">The same kit is on <a href="' + esc(k.promotePage + '?u=' + encodeURIComponent(user)) + '" target="_blank" rel="noopener">' + esc(k.name) + ' › Promote</a>.</p>';
|
||||
return h;
|
||||
}
|
||||
async function show() {
|
||||
const box = $('nkBody'); if (!box) return;
|
||||
const site = SITES.find(s => s.key === cur);
|
||||
if (!user) { box.innerHTML = '<p class="muted">Pick a username first: it becomes your link on every network site.</p>'; return; }
|
||||
box.innerHTML = '<p class="muted small">Loading the ' + esc(site.name) + ' kit...</p>';
|
||||
try {
|
||||
if (!cache[cur]) {
|
||||
const r = await fetch(site.feed + '?u=' + encodeURIComponent(user), { cache: 'no-store' });
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
cache[cur] = await r.json();
|
||||
}
|
||||
if (cur !== site.key) return;
|
||||
box.innerHTML = render(site, cache[cur]);
|
||||
box.querySelectorAll('[data-nkc]').forEach(b => b.addEventListener('click', () => copy(txt[Number(b.dataset.nkc)], b)));
|
||||
} catch (e) { box.innerHTML = '<p class="muted">Could not load the ' + esc(site.name) + ' kit right now. Try again in a minute.</p>'; }
|
||||
}
|
||||
function load(u) { if (u) setUser(u); pick(); show(); }
|
||||
return { load, setUser, SITES };
|
||||
})();
|
||||
@@ -0,0 +1,24 @@
|
||||
// "Part of the network" footer line for pages that do not load common.js (Marty 2026-11-14 trust pack): company line + the network
|
||||
// list from the hub (/api/network-sites, built-in copy if it does not answer). The current site comes from data-site on this tag.
|
||||
(function () {
|
||||
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] }; });
|
||||
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
||||
function run() {
|
||||
var f = document.querySelector('footer'); if (!f || f.querySelector('.netline')) return;
|
||||
var hasLegal = !!f.querySelector('a[href="/terms"]'); // decided once, before this line adds its own links
|
||||
var host = f.querySelector('.wrap') || f;
|
||||
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) {
|
||||
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>';
|
||||
}).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 () {});
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
||||
})();
|
||||
@@ -0,0 +1,30 @@
|
||||
// Network sign-in, the sign-in page side (2026-11-12). The SAME file ships in InstantAdPay and LinkSpin (see networksso.js).
|
||||
// On a sign-in screen with no session: ask /api/sso/status once; { check: true } means bounce once through the other site,
|
||||
// which signs the member in here if they are signed in there (the server allows one try per browser per 30 minutes and none
|
||||
// after a sign-out). { hint } means they came from the other site but need the email code here the first time: fill it in.
|
||||
(function () {
|
||||
if (window.__netsso) return; window.__netsso = 1;
|
||||
const BOXES = '#mcEmail,#jnEmail,#siEmail';
|
||||
function fill(email, peer) {
|
||||
let n = 0;
|
||||
const t = setInterval(() => {
|
||||
const el = document.querySelector(BOXES);
|
||||
if (el && el.offsetParent !== null) {
|
||||
clearInterval(t);
|
||||
if (!el.value) el.value = email;
|
||||
if (!document.getElementById('nssoNote')) {
|
||||
const p = document.createElement('p'); p.id = 'nssoNote'; p.className = 'muted small'; p.setAttribute('role', 'note'); p.style.margin = '6px 0';
|
||||
p.textContent = 'Welcome over from ' + peer + '. The first time here, send yourself a code with the same email to finish signing in. After that, ' + peer + ' signs you in here.';
|
||||
(el.closest('label') || el).insertAdjacentElement('afterend', p);
|
||||
}
|
||||
try { el.focus(); } catch (e) {}
|
||||
} else if (++n > 60) clearInterval(t);
|
||||
}, 250);
|
||||
}
|
||||
fetch('/api/sso/status', { credentials: 'same-origin', headers: { Accept: 'application/json' }, cache: 'no-store' })
|
||||
.then(r => r.json()).then(d => {
|
||||
if (!d) return;
|
||||
if (d.check) { location.replace('/sso/start?mode=check&to=' + encodeURIComponent(location.pathname + location.search + location.hash)); return; }
|
||||
if (d.hint) fill(String(d.hint), String(d.peer || 'the other site'));
|
||||
}).catch(() => {});
|
||||
})();
|
||||
@@ -509,6 +509,7 @@ textarea{resize:vertical;font:inherit}
|
||||
.lin-row .sp.wrap{white-space:normal;line-height:1.7}
|
||||
/* list toolbar: sort + filter chips shared by the tank, roster and downline (2026-09-29) */
|
||||
.lst-bar{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;margin:4px 0 10px;padding:8px 10px;border:1px solid var(--line);border-radius:12px;background:var(--ink-faint)}
|
||||
.lst-q{flex:1 1 100%;min-width:0;background:var(--panel);color:var(--ink);border:1px solid var(--line-strong);border-radius:8px;padding:6px 10px;font-size:13px}
|
||||
.lst-sort{font-size:12px;color:var(--muted);display:inline-flex;align-items:center;gap:6px}
|
||||
.lst-sort select{background:var(--panel);color:var(--ink);border:1px solid var(--line-strong);border-radius:8px;padding:4px 8px;font-size:12.5px}
|
||||
.lst-dir{background:transparent;color:var(--ink);border:1px solid var(--line-strong);border-radius:8px;padding:4px 9px;font-size:12px;cursor:pointer;white-space:nowrap}
|
||||
@@ -516,6 +517,8 @@ textarea{resize:vertical;font:inherit}
|
||||
.lst-chip{font-size:12px;color:var(--muted);background:transparent;border:1px solid var(--line);border-radius:999px;padding:3px 10px;cursor:pointer;white-space:nowrap}
|
||||
.lst-chip.on{border-color:var(--mint);color:var(--ink);background:var(--mint-soft)}
|
||||
.lst-n{margin-left:auto;font-size:12px;color:var(--muted);font-variant-numeric:tabular-nums}
|
||||
.roster-em{color:var(--mint);word-break:break-all;margin-top:2px}
|
||||
.lst-copy{background:transparent;color:var(--muted);border:1px solid var(--line);border-radius:6px;padding:0 6px;font-size:11px;cursor:pointer;margin-left:4px}
|
||||
.lchip{display:inline-block;font-size:11.5px;color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:1px 8px;white-space:nowrap;vertical-align:middle}
|
||||
.lchip.on{border-color:var(--mint-line);color:var(--ink)} .lchip.warn{border-color:var(--gold-line);color:var(--gold)}
|
||||
.roster td:nth-child(3){white-space:normal;line-height:1.8}
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.rg{max-width:900px}
|
||||
.rg .hero{padding:44px 0 10px}
|
||||
@@ -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=20261107nc"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/bixpay-guide.js?v=20261029bz"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Chasing Unicorns: spot the scam before it spots you</title>
|
||||
<meta name="description" content="A fake earnings dashboard with a ticking balance, a countdown and people cashing out every few seconds. Click anything and see the red flag behind it. A free training simulation from InstantAdPay.">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="Chasing Unicorns: can you spot all 8 red flags?">
|
||||
<meta property="og:description" content="A fake earnings dashboard that looks like the real thing. Click anything on it and see the red flag behind it. Free, takes two minutes.">
|
||||
<meta property="og:url" content="https://instantadpay.com/chasing-unicorns">
|
||||
<meta property="og:image" content="https://instantadpay.com/assets/chasing-unicorns-og.png?v=20261112">
|
||||
<meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<link rel="canonical" href="https://instantadpay.com/chasing-unicorns">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||
<style>
|
||||
/* Layout: an honest frame (training bar, scam radar, the ending) wrapped around a deliberately over-the-top fake console. Single dark look. */
|
||||
:root {
|
||||
--bg: #090a12; --panel: #121527; --panel2: #191d35; --line: #262c4d; --ink: #f1f2fb; --muted: #969cbf;
|
||||
--uni: #c084fc; --uni2: #f472b6; --gold: #f8cf4f; --mint: #34e3a0; --warn: #ff5d6c; --warn-ink: #fff; --ok: #34e3a0;
|
||||
--display: 'Sora', 'Segoe UI', system-ui, sans-serif; --mono: 'JetBrains Mono', ui-monospace, Consolas, monospace;
|
||||
color-scheme: dark;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
html, body { margin: 0; }
|
||||
body { background: var(--bg); color: var(--ink); font-family: var(--display); font-size: 15px; line-height: 1.5; }
|
||||
a { color: var(--mint); }
|
||||
button { font-family: var(--display); cursor: pointer; }
|
||||
button:focus-visible, a:focus-visible { outline: 3px solid var(--mint); outline-offset: 3px; }
|
||||
.sim { position: sticky; top: 0; z-index: 30; background: #1b1030; border-bottom: 1px solid #3b2463; padding-block: 8px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); display: flex; flex-wrap: wrap; gap: 6px 14px; align-items: center; justify-content: space-between; font-size: 13px; }
|
||||
.sim b { color: var(--uni); }
|
||||
.radar { display: flex; align-items: center; gap: 8px; font-family: var(--mono); font-size: 12.5px; }
|
||||
.radar .dots { display: flex; gap: 4px; }
|
||||
.radar .dots i { width: 10px; height: 10px; border-radius: 50%; background: #3b3460; display: block; }
|
||||
.radar .dots i.on { background: var(--warn); box-shadow: 0 0 8px var(--warn); }
|
||||
.wrap { max-width: 1000px; margin: 0 auto; padding-block: 22px 48px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); display: grid; gap: 16px; }
|
||||
.intro { display: grid; gap: 6px; }
|
||||
.intro h1 { margin: 0; font-size: clamp(24px, 4.4vw, 38px); line-height: 1.15; text-wrap: balance; }
|
||||
.intro h1 span { background: linear-gradient(90deg, var(--uni), var(--uni2)); -webkit-background-clip: text; background-clip: text; color: transparent; }
|
||||
.intro p { margin: 0; color: var(--muted); max-width: 66ch; }
|
||||
/* the fake console */
|
||||
.console { border: 1px solid var(--line); border-radius: 20px; background: radial-gradient(140% 120% at 0% 0%, #22184a 0%, var(--panel) 50%); padding: 18px; display: grid; gap: 14px; }
|
||||
.ctop { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; }
|
||||
.brand { font-weight: 800; font-size: 19px; display: flex; align-items: center; gap: 8px; }
|
||||
.brand svg { width: 28px; height: 28px; }
|
||||
.brand em { font-style: normal; background: linear-gradient(90deg, var(--uni), var(--uni2)); -webkit-background-clip: text; background-clip: text; color: transparent; }
|
||||
.tier { font-family: var(--mono); font-size: 12px; color: var(--gold); border: 1px solid var(--gold); border-radius: 999px; padding: 3px 11px; }
|
||||
.bal { display: grid; gap: 4px; }
|
||||
.lbl { font-size: 11.5px; letter-spacing: .14em; text-transform: uppercase; color: var(--muted); }
|
||||
.big { font-family: var(--mono); font-weight: 700; font-size: clamp(30px, 7vw, 60px); color: var(--gold); font-variant-numeric: tabular-nums; line-height: 1.05; word-break: break-all; text-shadow: 0 0 26px rgba(248, 207, 79, .35); }
|
||||
.rate { font-family: var(--mono); color: var(--mint); font-size: 14px; font-variant-numeric: tabular-nums; }
|
||||
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 10px; }
|
||||
.tile { background: rgba(9, 10, 18, .55); border: 1px solid var(--line); border-radius: 14px; padding: 12px 14px; display: grid; gap: 4px; min-width: 0; text-align: left; color: var(--ink); }
|
||||
.tile .v { font-family: var(--mono); font-weight: 700; font-size: 19px; font-variant-numeric: tabular-nums; color: var(--mint); }
|
||||
.tile .s { font-size: 12px; color: var(--muted); }
|
||||
button.tile { cursor: pointer; }
|
||||
.timer { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px 16px; background: linear-gradient(90deg, #3b0d1c, #1e0b16); border: 1px solid var(--warn); border-radius: 14px; padding: 12px 14px; }
|
||||
.timer .m { font-weight: 800; min-width: 0; }
|
||||
.timer .m small { display: block; font-weight: 400; color: var(--muted); font-size: 12.5px; }
|
||||
.clock { font-family: var(--mono); font-weight: 700; font-size: 28px; color: var(--warn); font-variant-numeric: tabular-nums; }
|
||||
.acts { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 10px; }
|
||||
.act { border: 0; border-radius: 13px; padding: 13px 14px; font-weight: 800; font-size: 15px; text-align: left; display: grid; gap: 2px; color: #170f00; background: linear-gradient(180deg, #ffe07a, var(--gold)); }
|
||||
.act small { font-weight: 600; font-size: 12px; opacity: .75; }
|
||||
.act.alt { background: var(--panel2); color: var(--ink); border: 1px solid var(--uni); }
|
||||
.act.alt small { color: var(--muted); opacity: 1; }
|
||||
.act.hot { background: linear-gradient(180deg, #ff8fa0, var(--warn)); color: #fff; }
|
||||
.act.done, .tile.done { outline: 2px solid var(--warn); outline-offset: -2px; }
|
||||
/* fake social proof */
|
||||
.proof { position: fixed; left: max(16px, env(safe-area-inset-left, 0px)); bottom: calc(16px + env(safe-area-inset-bottom, 0px)); width: min(330px, calc(100vw - 32px)); background: #fff; color: #11131d; border-radius: 12px; padding: 11px 13px; box-shadow: 0 12px 30px rgba(0, 0, 0, .5); display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; align-items: center; transform: translateY(150%); opacity: 0; transition: transform .35s ease, opacity .35s ease; z-index: 25; border: 0; text-align: left; font-family: var(--display); }
|
||||
.proof.on { transform: none; opacity: 1; }
|
||||
.proof .av { width: 34px; height: 34px; border-radius: 50%; background: linear-gradient(135deg, var(--uni), var(--uni2)); color: #fff; display: grid; place-items: center; font-weight: 800; grid-row: span 2; }
|
||||
.proof .t { font-size: 13.5px; line-height: 1.35; }
|
||||
.proof .t b { color: #0a8f55; }
|
||||
.proof .f { font-size: 11px; color: #6b6f85; }
|
||||
/* the reveal */
|
||||
.veil { position: fixed; inset: 0; z-index: 40; background: rgba(5, 5, 12, .78); display: grid; place-items: center; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); padding-block: 16px; }
|
||||
.card { background: var(--panel); border: 1px solid var(--warn); border-radius: 18px; max-width: 560px; width: 100%; padding: 20px; display: grid; gap: 10px; max-height: calc(100vh - 32px); overflow: auto; }
|
||||
.card .k { font-family: var(--mono); font-size: 12px; color: var(--warn); letter-spacing: .1em; text-transform: uppercase; }
|
||||
.card h2 { margin: 0; font-size: 22px; line-height: 1.25; text-wrap: balance; }
|
||||
.card p { margin: 0; }
|
||||
.card .tell { background: rgba(255, 93, 108, .08); border-left: 3px solid var(--warn); padding: 8px 12px; border-radius: 6px; font-size: 14px; }
|
||||
.card .do { background: rgba(52, 227, 160, .08); border-left: 3px solid var(--ok); padding: 8px 12px; border-radius: 6px; font-size: 14px; }
|
||||
.card .row { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
|
||||
.btn { border: 0; border-radius: 11px; padding: 11px 16px; font-weight: 800; font-size: 14.5px; text-decoration: none; display: inline-block; }
|
||||
.btn.go { background: var(--mint); color: #04130d; }
|
||||
.btn.sec { background: transparent; color: var(--ink); border: 1px solid var(--line); }
|
||||
/* the ending */
|
||||
.end { display: grid; gap: 14px; border: 1px solid var(--line); border-radius: 20px; background: var(--panel); padding: 22px 18px; }
|
||||
.end h2 { margin: 0; font-size: clamp(22px, 3.6vw, 30px); text-wrap: balance; }
|
||||
.end p { margin: 0; max-width: 68ch; }
|
||||
.flags { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 8px; margin: 0; padding: 0; list-style: none; }
|
||||
.flags li { border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; font-size: 13.5px; display: grid; gap: 2px; background: var(--panel2); }
|
||||
.flags li b { font-size: 14px; }
|
||||
.flags li.on { border-color: var(--warn); }
|
||||
.flags li.on b::before { content: "SPOTTED "; color: var(--warn); font-family: var(--mono); font-size: 11px; }
|
||||
.flags li:not(.on) { opacity: .6; }
|
||||
.vs { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 10px; }
|
||||
.vs > div { border-radius: 14px; padding: 14px; display: grid; gap: 6px; align-content: start; }
|
||||
.vs .bad { background: rgba(255, 93, 108, .07); border: 1px solid rgba(255, 93, 108, .4); }
|
||||
.vs .good { background: rgba(52, 227, 160, .07); border: 1px solid rgba(52, 227, 160, .4); }
|
||||
.vs h3 { margin: 0; font-size: 16px; }
|
||||
.vs ul { margin: 0; padding-left: 18px; font-size: 14px; display: grid; gap: 4px; }
|
||||
.agit { display: grid; gap: 10px; border: 1px solid rgba(255, 93, 108, .45); background: linear-gradient(180deg, rgba(255, 93, 108, .08), transparent); border-radius: 16px; padding: 16px; }
|
||||
.agit ul { margin: 0; padding-left: 18px; display: grid; gap: 8px; max-width: 70ch; }
|
||||
.agit li b { color: var(--warn); }
|
||||
.cta { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
|
||||
.fine { font-size: 12.5px; color: var(--muted); }
|
||||
.share { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.share code { font-family: var(--mono); font-size: 12.5px; background: var(--panel2); border: 1px solid var(--line); border-radius: 8px; padding: 6px 9px; word-break: break-all; }
|
||||
.foot { font-size: 12px; color: var(--muted); text-align: center; }
|
||||
@media (prefers-reduced-motion: reduce) { .proof { transition: none; } .big { text-shadow: none; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="sim" role="note"><span><b>Training simulation.</b> Nothing on this dashboard is real. Click anything to see the red flag behind it.</span>
|
||||
<span class="radar" aria-label="Red flags spotted">Scam radar <span class="dots" id="dots"></span> <span id="score">0 of 8</span></span></div>
|
||||
|
||||
<main class="wrap">
|
||||
<div class="intro">
|
||||
<h1>Still waiting on a payout? <span>Let's go chasing unicorns.</span></h1>
|
||||
<p>You signed up, you watched the balance grow, you maybe even brought a friend. Then you hit Withdraw, and you are still waiting. Below is the kind of dashboard those sites show you: a balance that never stops climbing, a countdown, people cashing out every few seconds. It looks great. That is the point. Click anything on it, the way you would on the real thing, and see what is really going on.</p>
|
||||
</div>
|
||||
|
||||
<section class="console" aria-label="Fake earnings dashboard">
|
||||
<div class="ctop">
|
||||
<div class="brand"><svg viewBox="0 0 32 32" aria-hidden="true"><defs><linearGradient id="ug" x1="0" x2="1"><stop offset="0" stop-color="#c084fc"/><stop offset="1" stop-color="#f472b6"/></linearGradient></defs><path d="M6 26c2-7 6-11 11-12l3-9 2 8c3 1 5 4 5 7-2 0-4-1-5-2-1 4-4 7-9 8H6z" fill="url(#ug)"/></svg>Unicorn<em>Yield</em> Pro</div>
|
||||
<button type="button" class="tier" data-flag="vip">VIP DIAMOND · Upgrade</button>
|
||||
</div>
|
||||
<div class="bal">
|
||||
<div class="lbl">Your balance</div>
|
||||
<div class="big" id="bal">$25,000.00</div>
|
||||
<div class="rate" id="rate">+3.00% daily compound interest · +$0.00 since you opened this page</div>
|
||||
</div>
|
||||
<div class="tiles">
|
||||
<button type="button" class="tile" data-flag="daily"><span class="lbl">Interest today</span><span class="v" id="today">$0.00</span><span class="s">Fixed 3% a day, guaranteed</span></button>
|
||||
<button type="button" class="tile" data-flag="team"><span class="lbl">Team bonus</span><span class="v" id="team">$1,240.00</span><span class="s">12 people under you</span></button>
|
||||
<button type="button" class="tile" data-flag="coin"><span class="lbl">UYP token holdings</span><span class="v">48,000 UYP</span><span class="s">Value: $4,800.00 (soon x100)</span></button>
|
||||
</div>
|
||||
<div class="timer">
|
||||
<div class="m">BONUS DOUBLER ENDS SOON! Lock in 6% a day.<small><span id="spots">Only 3 VIP spots left</span> · tell your friends before it closes</small></div>
|
||||
<div class="clock" id="clock">09:59</div>
|
||||
<button type="button" class="act hot" data-flag="clock">Lock it in now<small>before the timer hits zero</small></button>
|
||||
</div>
|
||||
<div class="acts">
|
||||
<button type="button" class="act" data-flag="withdraw">Withdraw $25,000<small>Fast and easy</small></button>
|
||||
<button type="button" class="act alt" data-flag="vip">Unlock withdrawals<small>VIP upgrade, $199 one time</small></button>
|
||||
<button type="button" class="act alt" data-flag="team">Invite friends<small>+$500 per sign-up</small></button>
|
||||
<button type="button" class="act alt" data-flag="keys">Connect wallet to claim<small>Claim 48,000 UYP airdrop</small></button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="end" id="end" aria-label="Your scam radar">
|
||||
<h2 id="endH">Your scam radar: 0 of 8 red flags spotted</h2>
|
||||
<p id="endP">Every button, tile and popup on that dashboard is one of the classic warning signs. Find them all, or <button type="button" class="btn sec" id="showAll" style="padding:4px 10px;font-size:13px">show me all 8</button></p>
|
||||
<ul class="flags" id="flags"></ul>
|
||||
<div id="after" hidden style="display:grid;gap:14px">
|
||||
<div class="agit">
|
||||
<h2>Here is what chasing unicorns really costs you</h2>
|
||||
<ul>
|
||||
<li><b>The deposit.</b> The number on the screen was never your money. The money you sent in was, and it is already gone.</li>
|
||||
<li><b>The "free" ones.</b> Some never ask for a penny up front. Free to join, free to "earn", a big withdrawal promised for later, knowing it is never coming. Everybody piles in for free while the countdown runs, inviting friends to grow their balance. When the timer hits zero, the fee shows up, and now thousands of people are lined up to pay it.</li>
|
||||
<li><b>The "release fee".</b> When withdrawals stall, the next message asks you to pay something small to unlock the big balance: a miner fee, a gas fee, an admin fee, a tax, a verification fee, a VIP upgrade. It always sounds minor next to what is "waiting" for you. Pay it, and another one appears.</li>
|
||||
<li><b>Your friends.</b> Everyone you invited is now asking you where their money is. You did not mean to, but you sold them the unicorn.</li>
|
||||
<li><b>Your time.</b> Months of checking a dashboard, waiting on a Telegram admin, hoping this week is the week.</li>
|
||||
<li><b>The next one.</b> When this site goes dark, a "recovery service" shows up offering to get your money back, for a fee. Then a new unicorn with a new countdown.</li>
|
||||
</ul>
|
||||
<p>And the worst part: after enough of these, people stop trusting anything online, including the things that actually work.</p>
|
||||
</div>
|
||||
<h2>Quit chasing unicorns. Look for receipts.</h2>
|
||||
<p>A real program does not need a magic number on a screen. It needs a product people actually buy, and payments you can check yourself without asking anyone. That is how we built InstantAdPay.</p>
|
||||
<div class="vs">
|
||||
<div class="bad"><h3>The unicorn</h3><ul>
|
||||
<li>A fixed daily return on your deposit</li><li>Withdrawals always "processing"</li><li>Pay a fee to unlock your own money</li><li>Paid in their own coin</li><li>A countdown that never ends</li></ul></div>
|
||||
<div class="good"><h3>What InstantAdPay does instead</h3><ul>
|
||||
<li>Sells real advertising: ad packages from $5 buy text ads, banners, visits and more across the network</li>
|
||||
<li>When a package sells, the sponsor line is paid by smart contract in the same transaction. Nothing is held by the company.</li>
|
||||
<li>Every payment is on the Polygon blockchain, so you can look it up yourself</li>
|
||||
<li>Joining is free and starts with just your email. No card, no wallet needed to look around.</li>
|
||||
<li>No balance to "unlock" and no countdown</li></ul></div>
|
||||
</div>
|
||||
<div class="cta"><a class="btn go" id="joinBtn" href="/join?src=chasing-unicorns">Look around InstantAdPay free</a><a class="btn sec" href="/ledger" id="ledgerBtn">See the public payment ledger</a></div>
|
||||
<p class="fine">Ad credits buy advertising, not income. No income is promised: what you earn depends on the packages bought by people you bring in.</p>
|
||||
<div class="share" id="shareRow"><span class="fine">Know someone still waiting on a payout? Send them this:</span> <code id="shareLink">https://instantadpay.com/chasing-unicorns</code> <button type="button" class="btn sec" id="copyShare" style="padding:6px 12px;font-size:13px">Copy link</button></div>
|
||||
<p class="fine">The full checklist, with a 3 minute video: <a href="https://earnerscorner.com/t/what-do-you-check-before-joining-a-new-program/25/6" target="_blank" rel="noopener">Spot a scam before it spots you, on Earners Corner</a>.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p class="foot">Training simulation by InstantAdPay. UnicornYield Pro, its balance, token, team, countdown and every "withdrawal" popup are made up, and nothing on the dashboard can be deposited, earned or withdrawn.</p>
|
||||
</main>
|
||||
|
||||
<button type="button" class="proof" id="proof" data-flag="proof" aria-live="polite"><span class="av" id="pAv">J</span><span class="t" id="pT"></span><span class="f">Tap to check this one</span></button>
|
||||
|
||||
<div class="veil" id="veil" hidden><div class="card" role="dialog" aria-modal="true" aria-labelledby="cardH">
|
||||
<div class="k" id="cardK">Red flag 1 of 8</div>
|
||||
<h2 id="cardH"></h2>
|
||||
<p id="cardP"></p>
|
||||
<div class="tell" id="cardTell"></div>
|
||||
<div class="do" id="cardDo"></div>
|
||||
<div class="row"><button type="button" class="btn go" id="cardNext">Keep hunting</button><button type="button" class="btn sec" id="cardEnd">Show my scam radar</button></div>
|
||||
</div></div>
|
||||
|
||||
<script src="/assets/chasing-unicorns.js?v=20261112d"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -18,7 +18,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/contract.js?v=20260908p"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
</body>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.rg{max-width:900px}
|
||||
.rg .hero{padding:44px 0 10px}
|
||||
@@ -265,7 +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=20261107nc"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body>
|
||||
<div id="nav"></div>
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+3
-2
@@ -9,7 +9,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.eg{max-width:820px}
|
||||
.eg h2{font-size:23px;margin:40px 0 10px;padding-top:18px;border-top:1px solid var(--line)}
|
||||
@@ -97,6 +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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<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>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@
|
||||
<link rel="alternate" type="text/plain" href="/llms.txt" title="Plain-text summary for AI systems">
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.facts h3 { margin-top: 18px; }
|
||||
.facts table { width: 100%; border-collapse: collapse; font-size: 14px; margin: 8px 0 4px; }
|
||||
@@ -127,7 +127,7 @@
|
||||
</ul>
|
||||
</div>
|
||||
</div></section>
|
||||
<script src="/assets/common.js?v=20261107nc"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+3
-2
@@ -14,7 +14,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.fr{max-width:860px}
|
||||
.fr .hero{padding:44px 0 10px}
|
||||
@@ -72,6 +72,7 @@
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/friday.js?v=20260925a"></script>
|
||||
<script src="/assets/common.js?v=20261107nc"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+3
-2
@@ -15,7 +15,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.gp{max-width:1040px}
|
||||
.gp .hero{padding:56px 0 10px}
|
||||
@@ -79,6 +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=20261107nc"></script><script src="/assets/games-page.js?v=20261012b"></script>
|
||||
<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>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -22,7 +22,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -506,7 +506,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script src="/assets/common.js?v=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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>
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.jn-nav{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;padding:16px 0}
|
||||
.jn-nav>a{white-space:nowrap;flex:0 0 auto;padding-top:8px}
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/join.js?v=20261107nc"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.lw-rule{border-left:4px solid var(--gold-2);background:var(--gold-soft);padding:16px 20px;border-radius:0 12px 12px 0;margin:0 0 24px}
|
||||
.lw-rule b{font-family:var(--disp);font-size:17px;display:block;margin-bottom:6px}
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/launch.js?v=20260915b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -18,7 +18,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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>
|
||||
|
||||
+24
-5
@@ -6,7 +6,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body class="bo-body">
|
||||
|
||||
@@ -835,6 +835,10 @@
|
||||
<div><span class="eyebrow" style="margin:0 0 4px">Share the presentation</span><div class="small muted" style="margin:0 0 4px">The narrated Build Wide presentation, captions in six languages. Your name rides on the link, and the page shows you as the person who shared it.</div><div class="mono small" id="promoPresLink" style="overflow-wrap:anywhere">…</div></div>
|
||||
<span><button class="btn small" id="promoPresCopy" type="button">Copy link</button> <a class="btn small sec" id="promoPresOpen" href="/presentation" target="_blank" rel="noopener">Open</a></span>
|
||||
</div>
|
||||
<div class="card promo-strip" id="promoUniStrip" hidden>
|
||||
<div><span class="eyebrow" style="margin:0 0 4px">Chasing Unicorns: the scam-spotting game</span><div class="small muted" style="margin:0 0 4px">A fake earnings dashboard that looks like the real thing. Every button is a red flag, the visitor scores their "scam radar", then sees how InstantAdPay works instead. Made for people still waiting on a payout somewhere else. Your link carries your name, so a join counts for you.</div><div class="mono small" id="promoUniLink" style="overflow-wrap:anywhere">…</div></div>
|
||||
<span><button class="btn small" id="promoUniCopy" type="button">Copy link</button> <a class="btn small sec" id="promoUniOpen" href="/chasing-unicorns" target="_blank" rel="noopener">Open</a></span>
|
||||
</div>
|
||||
<div class="card promo-strip" id="promoWallStrip" hidden>
|
||||
<div><span class="eyebrow" style="margin:0 0 4px">Your banner wall</span><div class="mono small" id="promoWallLink" style="overflow-wrap:anywhere">…</div></div>
|
||||
<span><button class="btn small sec" id="promoWallCopy" type="button">Copy wall link</button> <a class="btn small sec" id="promoWallOpen" href="#" target="_blank" rel="noopener">Open</a></span>
|
||||
@@ -851,6 +855,7 @@
|
||||
<button class="chip-t" data-promo="viral" type="button" role="tab">Viral links</button>
|
||||
<button class="chip-t" data-promo="stackpol" type="button" role="tab">📈 Stack POL</button>
|
||||
<button class="chip-t" data-promo="games" type="button" role="tab">🎮 Games</button>
|
||||
<button class="chip-t" data-promo="network" type="button" role="tab">🌐 Network sites</button>
|
||||
<button class="chip-t" data-promo="bixpay" type="button" role="tab" hidden>💳 BixPay</button>
|
||||
</div>
|
||||
<!-- Stack POL page switch (2026-11-09): stackpol.com/<username> shows every POL payout to the member's wallets across the network -->
|
||||
@@ -882,6 +887,14 @@
|
||||
<div id="bixPromoBanners"></div>
|
||||
<p class="small muted" style="margin:12px 0 0">BixPay is a separate company. BIX issues the wallet and the card through its banking partners and sets its own fees, limits, eligibility and terms. InstantAdPay is not the card issuer and earns a referral commission when you sign up through a partner link. Card availability varies by country. Crypto assets can lose value.</p>
|
||||
</div>
|
||||
<!-- Network sites (2026-11-14): Downline Banners + Viral Banner Blitz kits, read live from each site's /api/promo-kit feed; netkits.js -->
|
||||
<div class="card promo-sec" id="promo-network" hidden>
|
||||
<div class="card-head"><h3>🌐 Network sites</h3><span class="sub">your username is your link on every network site</span></div>
|
||||
<p class="muted small" style="margin:0 0 10px">Your InstantAdPay username works as your sponsor link on the other network sites too, even if you have never visited them. Every link, creative and line below carries it. Each site keeps its own kit, so what you see here is always the current one.</p>
|
||||
<style>.nk-grid{display:flex;flex-wrap:wrap;gap:16px;align-items:flex-start;margin-top:10px}.nk-fig{margin:0;display:flex;flex-direction:column;gap:6px;max-width:100%}.nk-fig img{display:block;max-width:100%;height:auto;border-radius:6px}.nk-set{margin:10px 0}</style>
|
||||
<div class="chips" id="nkPick" style="margin:0 0 12px"></div>
|
||||
<div id="nkBody"></div>
|
||||
</div>
|
||||
<div class="card promo-sec" id="promo-games" hidden>
|
||||
<div class="card-head"><h3>🎮 Our games</h3><span class="sub">free to play, every link carries your username</span></div>
|
||||
<p class="muted small" style="margin:0 0 10px">Every game here is free to play and brings players into InstantAdPay. Your username is built into each link, post and banner, so anyone who joins through them lands on your line. Pick a game.</p>
|
||||
@@ -1265,7 +1278,11 @@
|
||||
<a href="/ledger">Live ledger</a>
|
||||
<a href="/contract">The contract</a>
|
||||
<a href="#help">Support</a>
|
||||
<a href="/terms">Terms</a>
|
||||
<a href="/disclaimer">Earnings Disclaimer</a>
|
||||
<a href="/privacy">Privacy</a>
|
||||
<a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>
|
||||
<span style="width:100%;text-align:center;color:var(--muted)">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</span>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1289,13 +1306,15 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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/my.js?v=20261110proown"></script>
|
||||
<script src="/assets/fuel.js?v=20261025ff"></script>
|
||||
<script src="/assets/engine-room.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/engine-room.js?v=20261113sso"></script>
|
||||
<script src="/assets/netsso.js?v=20261113sso"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.pk{max-width:820px}
|
||||
.pk h2{font-size:24px;margin:44px 0 12px;padding-top:20px;border-top:1px solid var(--line)}
|
||||
@@ -131,7 +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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/partners.js?v=20260914a"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.pl-rule{border-left:4px solid var(--gold-2);background:var(--gold-soft);padding:16px 20px;border-radius:0 12px 12px 0;margin:0 0 28px}
|
||||
.pl-rule b{font-family:var(--disp);font-size:17px;display:block;margin-bottom:6px}
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/plays.js?v=20260910b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.pr{max-width:1040px}
|
||||
.pr .hero{padding:44px 0 6px;text-align:center}
|
||||
@@ -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=20261107nc"></script><script src="/assets/presentation.js?v=20261015b"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/presentation.js?v=20261015b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body>
|
||||
<div id="nav"></div>
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.rg{max-width:900px}
|
||||
.rg .hero{padding:44px 0 10px}
|
||||
@@ -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=20261107nc"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
<meta name="robots" content="noindex,nofollow">
|
||||
<title>Refuel · InstantAdPay verified visit</title>
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
html,body{height:100%}
|
||||
body{margin:0;display:flex;flex-direction:column;background:#0b1020;color:#e6edf3}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
html,body{height:100%;margin:0;overflow:hidden;background:#000}
|
||||
/* the Shorts stage is a black video player in both themes, so its text keeps the dark ink set whatever data-theme says (2026-11-01) */
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body>
|
||||
<section><div class="wrap" style="max-width:720px">
|
||||
@@ -20,7 +20,7 @@
|
||||
<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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
<script src="/assets/support.js?v=20261101th"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body>
|
||||
<div id="nav"></div>
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body>
|
||||
<div id="nav"></div>
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/tx.js?v=20260906m"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
<title>Viewing ad — InstantAdPay</title>
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
html,body{height:100%;margin:0;overflow:hidden}
|
||||
.vw{display:flex;flex-direction:column;height:100vh;height:100dvh;background:var(--ground);color:var(--ink,#e8fff7)}
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
</head>
|
||||
<body>
|
||||
<div id="nav"></div>
|
||||
@@ -48,7 +48,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<script src="/assets/common.js?v=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/wall.js?v=20261030pp"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.wl-rule{border-left:4px solid var(--gold-2);background:var(--gold-soft);padding:16px 20px;border-radius:0 12px 12px 0;margin:0 0 28px}
|
||||
.wl-rule b{font-family:var(--disp);font-size:17px;display:block;margin-bottom:6px}
|
||||
@@ -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=20261107nc"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/wallets.js?v=20260911b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261101th">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.fr{max-width:860px}
|
||||
.fr .hero{padding:44px 0 10px}
|
||||
@@ -65,6 +65,7 @@
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/wednesday.js?v=20260929c"></script>
|
||||
<script src="/assets/common.js?v=20261107nc"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// Chasing Unicorns promo page (Marty, 2026-11-12). Boots a throwaway server, opens /chasing-unicorns?ref=<a real member> and checks:
|
||||
// the viral ?ref= sets the sponsor cookie, every red-flag button opens its card and lights the radar, the ending unlocks after 3,
|
||||
// the join button keeps the sponsor, no page errors, no sideways scroll on a phone. Writes the 1200x630 share image too:
|
||||
// public/assets/chasing-unicorns-og.png (pass --og to refresh it). node qa/chasing-unicorns.mjs [--og]
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright/index.js';
|
||||
const { chromium } = (await import('file:///' + PW.replace(/^\/+/, ''))).default;
|
||||
const PORT = 8796, B = 'http://127.0.0.1:' + PORT;
|
||||
const DATA = path.join(os.tmpdir(), 'iap-unicorns-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
|
||||
const ok = [], bad = []; const t = (n, c, x) => (c ? ok : bad).push(n + (c || !x ? '' : ' -> ' + x));
|
||||
const srv = spawn(process.execPath, ['server.js'], { env: { ...process.env, PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'localtest', NODE_ENV: 'test', DATABASE_URL: '' }, stdio: 'ignore' });
|
||||
const bye = c => { try { srv.kill(); } catch (e) {} setTimeout(() => { try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} process.exit(c); }, 500); };
|
||||
for (let i = 0; i < 60; i++) { try { if ((await fetch(B + '/api/stats')).ok) break; } catch (e) {} await new Promise(r => setTimeout(r, 500)); }
|
||||
// a real member to share the page
|
||||
const DEV = 'c0ffee00c0ffee00c0ffee00c0ffee00';
|
||||
const jf = async (p, body, cookie) => { const r = await fetch(B + p, { method: body ? 'POST' : 'GET', redirect: 'manual', headers: { 'Content-Type': 'application/json', Cookie: cookie || '', 'X-Forwarded-For': '203.0.113.9' }, body: body ? JSON.stringify(body) : undefined }); let b = {}; try { b = await r.json(); } catch (e) {} return { r, b }; };
|
||||
const st = await jf('/api/auth/email/start', { email: 'sharer@example.com', fts: Date.now() - 20000 }, 'iap.dev=' + DEV);
|
||||
const vf = await jf('/api/auth/email/verify', { email: 'sharer@example.com', code: st.b.devCode || st.b.code }, 'iap.dev=' + DEV);
|
||||
const jar = ['iap.dev=' + DEV, ...(vf.r.headers.getSetCookie ? vf.r.headers.getSetCookie() : []).map(c => String(c).split(';')[0])].join('; ');
|
||||
await jf('/api/my/profile', { username: 'unisharer' }, jar);
|
||||
const pg = await fetch(B + '/chasing-unicorns?ref=unisharer', { redirect: 'manual' });
|
||||
const sc = (pg.headers.getSetCookie ? pg.headers.getSetCookie() : []).join(' | ');
|
||||
t('page serves 200', pg.status === 200, pg.status);
|
||||
t('?ref= sets the sponsor cookie', /iap\.sponsor=unisharer/.test(sc), sc.slice(0, 160));
|
||||
|
||||
const br = await chromium.launch(); const errs = [];
|
||||
const page = await br.newPage({ viewport: { width: 1280, height: 900 } }); page.on('pageerror', e => errs.push(e.message)); page.on('console', m => { if (m.type() === 'error') errs.push(m.text()); });
|
||||
await page.goto(B + '/chasing-unicorns?ref=unisharer', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(1500);
|
||||
if (process.argv.includes('--og')) {
|
||||
const og = await br.newPage({ viewport: { width: 1200, height: 630 }, deviceScaleFactor: 1 });
|
||||
await og.goto(B + '/chasing-unicorns', { waitUntil: 'domcontentloaded' }); await og.waitForTimeout(3500);
|
||||
await og.evaluate(() => { const i = document.querySelector('.intro p'); if (i) i.hidden = true; });
|
||||
await og.screenshot({ path: 'public/assets/chasing-unicorns-og.png' }); await og.close(); ok.push('share image written');
|
||||
}
|
||||
const join0 = await page.$eval('#joinBtn', a => a.getAttribute('href')); t('join button keeps the sponsor', join0 === '/join/unisharer?src=chasing-unicorns', join0);
|
||||
t('ending is locked at first', await page.$eval('#after', e => e.hidden));
|
||||
const flags = ['daily', 'withdraw', 'vip', 'team', 'clock', 'coin', 'keys'];
|
||||
for (const f of flags) {
|
||||
await page.click('.console [data-flag="' + f + '"] >> nth=0'); await page.waitForTimeout(150);
|
||||
const h = await page.$eval('#cardH', e => e.textContent); const open = await page.$eval('#veil', e => !e.hidden);
|
||||
t('flag ' + f + ' opens its card', open && h.length > 8, h);
|
||||
await page.click('#cardNext'); await page.waitForTimeout(100);
|
||||
}
|
||||
t('radar counts 7', (await page.$eval('#score', e => e.textContent)) === '7 of 8');
|
||||
t('ending unlocks after 3', !(await page.$eval('#after', e => e.hidden)));
|
||||
await page.waitForSelector('#proof.on', { timeout: 12000 }).catch(() => {});
|
||||
await page.click('#proof', { timeout: 5000 }).catch(() => {}); await page.waitForTimeout(150);
|
||||
const last = await page.$eval('#cardH', e => e.textContent).catch(() => ''); t('the popup is the 8th flag', /Dave from Denver|withdrew/.test(last), last);
|
||||
await page.click('#cardNext').catch(() => {}); await page.waitForTimeout(400);
|
||||
t('8 of 8 result', /8 of 8/.test(await page.$eval('#endH', e => e.textContent)));
|
||||
await page.screenshot({ path: 'qa/out/unicorns-end.png', fullPage: true });
|
||||
const ph = await br.newPage({ viewport: { width: 390, height: 844 } }); ph.on('pageerror', e => errs.push(e.message));
|
||||
await ph.goto(B + '/chasing-unicorns', { waitUntil: 'domcontentloaded' }); await ph.waitForTimeout(1200);
|
||||
const over = await ph.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); t('phone: no sideways scroll', over <= 1, over);
|
||||
await ph.screenshot({ path: 'qa/out/unicorns-phone.png' });
|
||||
t('no page errors', !errs.filter(e => !/favicon/.test(e)).length, errs.join(' | ').slice(0, 300));
|
||||
await br.close();
|
||||
console.log(ok.map(x => ' ok ' + x).join('\n')); if (bad.length) console.log(bad.map(x => ' FAIL ' + x).join('\n'));
|
||||
bye(bad.length ? 1 : 0);
|
||||
@@ -0,0 +1,287 @@
|
||||
// 5xYourTeam "The Draft" partner routes (draftpartner.js + the tank.adopt partner path, 2026-11-15).
|
||||
// node qa/draft-partner.test.mjs (also part of `bash qa/run.sh member`; `bash qa/run.sh draft` alone)
|
||||
// Part A, no server: the REAL tank.js + draftpartner.js with in-memory accounts, a fake chain, a fake hub and a MOCKED CLOCK.
|
||||
// signature, the pool rules (locked / sponsored / spam / throwaway / adopted twice / grace shown with opensAt / no contact data),
|
||||
// adopt (the 5x claim replaces the $20 rule only here, wallet + contract line, 10 open, fresh lock check, hub off, rid repeat,
|
||||
// the normal adoption email is the only mail), the auto-assign conflict rule (a drafted person is out of the tank; tank.sweep
|
||||
// leaves a pick's adoption alone), release (48 h hold, back with the original join time, two adoptions = kept, started = done,
|
||||
// locked = kept, hub silent = wait), the hourly sweep (wallet alone is not started), reconcile, status, the log.
|
||||
// Part B, LOCAL copy (throwaway DATA_DIR, JSON store, DRAFT_ALLOW_NO_HUB=1): the HTTP routes answer signed calls only.
|
||||
// Never production. Exit code 1 on any failure.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
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; // JSON stores only
|
||||
const SECRET = 'draft-test-secret-' + 'x'.repeat(40);
|
||||
let fails = 0, passes = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (cond || extra === undefined ? '' : ' ' + (typeof extra === 'string' ? extra : JSON.stringify(extra)))); if (!cond) fails++; else passes++; };
|
||||
const H = 3600000, D = 86400000;
|
||||
const addr = () => '0x' + crypto.randomBytes(20).toString('hex');
|
||||
|
||||
function fakeAccounts() {
|
||||
const by = new Map(); let nextId = 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; };
|
||||
return {
|
||||
_by: by,
|
||||
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * D, lastSeen: Date.now() - H, joinedVia: null }, o || {}); by.set(email, a); return pub(a); },
|
||||
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
|
||||
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
|
||||
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
|
||||
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
|
||||
async byAddress(w) { const x = String(w || '').toLowerCase(); return find(a => a.address && a.address.toLowerCase() === x); },
|
||||
async positionOwner() { return null; },
|
||||
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true }; },
|
||||
async listAll() { return [...by.values()].map(pub); },
|
||||
isUnclaimedShell: () => false,
|
||||
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); }
|
||||
};
|
||||
}
|
||||
|
||||
function bench(o) {
|
||||
o = o || {};
|
||||
for (const m of ['tank.js', 'draftpartner.js']) delete require.cache[require.resolve(path.join(SITE, m))];
|
||||
const tank = require(path.join(SITE, 'tank.js'));
|
||||
const dp = require(path.join(SITE, 'draftpartner.js'));
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-draft-'));
|
||||
const accounts = fakeAccounts(); const events = []; const chats = []; const mails = []; const notices = []; const assigned = []; const deliberate = [];
|
||||
const hub = { locked: new Set(), sponsored: new Set(), down: false, on: true, ids: new Map() };
|
||||
const flagged = new Set(); const spamList = [];
|
||||
const env = { now: Date.now() };
|
||||
const follow = { setDeliberate: async (email, token, by, note) => { deliberate.push({ email, token, by, note }); return accounts.setSponsorRef(email, token); } };
|
||||
const why = e => hub.down ? 'unknown' : hub.locked.has(e) ? 'locked' : hub.sponsored.has(e) ? 'sponsored' : null;
|
||||
tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) }, follow,
|
||||
messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 },
|
||||
mailer: { hasKey: () => true, send: async (to, subject, body) => { mails.push({ to, subject, body }); } }, site: 'https://iap.test',
|
||||
hooks: { network: () => null, isSuspended: () => false, excluded: e => flagged.has(e), payoutBlocked: async () => false, companyId: () => 1,
|
||||
networkHeld: async accts => new Map(accts.map(a => [a.email, why(a.email)]).filter(x => x[1])),
|
||||
networkLocked: async e => { const w = why(e); return w === 'locked' || w === 'unknown' ? w : null; },
|
||||
isDraftPick: id => dp.isDraftPick(id),
|
||||
assigned: r => { assigned.push(r); }, adminAlert: () => {}, claim: () => true, activated: () => false, notify: async (to, subject, text) => { notices.push({ to, subject, text }); } } });
|
||||
tank.setClock(() => env.now);
|
||||
process.env.DRAFT_PARTNER_SECRET = SECRET;
|
||||
const ready = dp.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse() }, tank, ads: { earnedTotals: async em => Object.fromEntries(em.map(e => [e, { earned: e.startsWith('surf') ? 420 : 0, balance: 0 }])) },
|
||||
requireHub: true, clock: () => env.now,
|
||||
hooks: { hubInfo: e => hub.ids.has(e) ? { id: hub.ids.get(e), door: 'linkspin' } : null, networkOn: () => hub.on, excluded: e => flagged.has(e), spamEmails: () => spamList,
|
||||
suggestDomain: d => require(path.join(SITE, 'emailcheck.js')).suggestDomain(d) } });
|
||||
let block = 1000;
|
||||
// a coach: a wallet linked here and payouts on (member id), but NO $20 purchase (their vesting is the 5x position)
|
||||
const coach = (email, memberId, extra) => accounts.add(email, Object.assign({ memberId, address: addr() }, extra || {}));
|
||||
const buy = (memberId, cents) => events.push({ type: 'Purchase', buyerId: memberId, priceCents: cents || 2000, block: block++ });
|
||||
return { tank, dp, ready, accounts, events, chats, mails, notices, assigned, deliberate, hub, flagged, spamList, env, coach, buy, dir };
|
||||
}
|
||||
const claimOf = (a, positions) => ({ wallet: a.address, username: a.username, positions: positions === undefined ? 1 : positions });
|
||||
let ridN = 0; const rid = () => 'rid-test-' + (++ridN) + '-' + crypto.randomBytes(3).toString('hex');
|
||||
|
||||
async function partA() {
|
||||
console.log('-- Part A: draftpartner.js + tank.js, mocked clock, fake hub');
|
||||
// ---- signature ----
|
||||
{
|
||||
const B = bench(); await B.ready;
|
||||
const raw = JSON.stringify({}); const ts = String(Date.now());
|
||||
const good = B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw) }, raw);
|
||||
ok(good.body && typeof good.body === 'object', 'signature: a good signature passes');
|
||||
ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw, 'other-secret-' + 'y'.repeat(30)) }, raw).status === 401, 'signature: another secret is refused');
|
||||
ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw) }, raw + ' ').status === 401, 'signature: a changed body is refused');
|
||||
const old = String(Date.now() - 6 * 60000);
|
||||
ok(B.dp.verify({ 'x-draft-ts': old, 'x-draft-sig': B.dp.sign(old, raw) }, raw).status === 401, 'signature: older than 5 minutes is refused');
|
||||
const keep = process.env.DRAFT_PARTNER_SECRET; process.env.DRAFT_PARTNER_SECRET = 'short';
|
||||
ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': 'x' }, raw).status === 503, 'signature: no (or a short) secret = 503, nothing answers');
|
||||
process.env.DRAFT_PARTNER_SECRET = keep;
|
||||
}
|
||||
// ---- the pool ----
|
||||
const B = bench(); await B.ready; const { tank, dp, accounts, env, hub } = B;
|
||||
accounts.add('live@x.co', { address: addr(), lastSeen: env.now - 2 * H });
|
||||
accounts.add('plain@x.co');
|
||||
accounts.add('surfer@x.co');
|
||||
accounts.add('locked@x.co'); hub.locked.add('locked@x.co');
|
||||
accounts.add('sponsoredhub@x.co'); hub.sponsored.add('sponsoredhub@x.co');
|
||||
accounts.add('flagged@x.co'); B.flagged.add('flagged@x.co');
|
||||
accounts.add('farm@x.co'); B.spamList.push('farm@x.co');
|
||||
accounts.add('temp@mailinator.com');
|
||||
accounts.add('typo@gmial.com');
|
||||
accounts.add('fresh@x.co', { created: env.now - 2 * H });
|
||||
accounts.add('kid@x.co', { sponsorRef: 'someone' });
|
||||
accounts.add('twice@x.co');
|
||||
hub.ids.set('live@x.co', 'h_0123456789abcdef');
|
||||
const C1 = B.coach('coach1@x.co', 41); const C2 = B.coach('coach2@x.co', 42);
|
||||
// twice@ has had two adoptions already (an old IAP one and a dropped one)
|
||||
B.buy(43); B.coach('iapadopter@x.co', 43);
|
||||
await tank.adopt('iapadopter@x.co', 'twice@x.co'); await accounts.setSponsorRef('twice@x.co', ''); // back in the tank by hand: 1 counted
|
||||
await tank.adopt('iapadopter@x.co', 'twice@x.co'); await accounts.setSponsorRef('twice@x.co', ''); // 2 counted
|
||||
for (const ad of await tank.openOf('twice@x.co')) await tank.closeAdoption(ad.id, 'dropped');
|
||||
B.mails.length = 0; B.chats.length = 0;
|
||||
const P = await dp.pool();
|
||||
const names = P.pool.map(c => c.username).sort();
|
||||
ok(P.ok && names.join(',') === ['fresh', 'live', 'plain', 'surfer'].join(','), 'pool: only people who pass every rule', names.join(','));
|
||||
ok(P.excluded.spam === 2 && P.excluded.throwaway === 2 && P.excluded.adoptedTwice === 1, 'pool: spam/flagged, throwaway + mistyped domains and adopted-twice counted out', P.excluded);
|
||||
ok(!names.includes('locked') && !names.includes('sponsoredhub') && !names.includes('kid'), 'pool: nobody locked on a contract, sponsored on the hub or sponsored here');
|
||||
const live = P.pool.find(c => c.username === 'live'); const fresh = P.pool.find(c => c.username === 'fresh'); const plain = P.pool.find(c => c.username === 'plain');
|
||||
ok(live.id === 'h_0123456789abcdef' && live.door === 'LinkSpin' && live.wallet === true && live.joinedAt > 0, 'card: hub id + door from the hub cache, wallet linked yes/no, joined', live);
|
||||
ok(/^i_[0-9a-f]{16}$/.test(plain.id) && plain.door === 'InstantAdPay', 'card: someone the hub does not know gets an opaque i_ id');
|
||||
ok(fresh.opensAt > env.now, 'card: a sign-up inside the 24-hour grace is shown with opensAt');
|
||||
ok(live.games === null && live.surfWei === null && typeof live.surfCredits === 'number', 'card: games null (not tracked here), surfing as credits, never invented');
|
||||
const keys = new Set(P.pool.flatMap(c => Object.keys(c)));
|
||||
ok(!JSON.stringify(P).includes('@') && !keys.has('email') && !keys.has('address'), 'pool: no contact data (no email, no wallet address) in the answer');
|
||||
ok(P.rules.returnHours === 72 && P.rules.holdHours === 48 && P.rules.maxOpen === 10 && P.rules.maxAdoptions === 2 && P.rules.graceHours === 24, 'pool: the rules travel with it', P.rules);
|
||||
|
||||
// ---- adopt ----
|
||||
const a0 = await dp.adopt({ rid: rid(), coach: claimOf(C1, 0), person: plain.id, kind: 'draft' });
|
||||
ok(a0.code === 'not_vested', 'adopt: no 5x position = refused (free members cannot adopt)', a0);
|
||||
const a1 = await dp.adopt({ rid: rid(), coach: { wallet: addr(), positions: 1 }, person: plain.id });
|
||||
ok(a1.code === 'coach_unknown', 'adopt: a wallet with no account here is refused', a1);
|
||||
const nw = accounts.add('nowallet@x.co', { memberId: 0 });
|
||||
accounts._by.get('nowallet@x.co').address = null;
|
||||
const nwc = B.coach('freecoach@x.co', 0);
|
||||
const a2 = await dp.adopt({ rid: rid(), coach: claimOf(nwc), person: plain.id });
|
||||
ok(a2.code === 'no_contract_line', 'adopt: a coach with nobody on this contract in their line is refused (a pick would land under the company)', a2);
|
||||
void nw;
|
||||
hub.on = false;
|
||||
const a3 = await dp.adopt({ rid: rid(), coach: claimOf(C1), person: plain.id });
|
||||
ok(a3.code === 'hub_off', 'adopt: hub off = nobody can be drafted', a3);
|
||||
ok((await dp.pool()).pool.length === 0, 'pool: hub off = empty pool');
|
||||
hub.on = true;
|
||||
ok(!(await tank.eligibility('coach1@x.co')).ok, "the coach is NOT eligible for InstantAdPay's own tank button (keeps its $20 rule)");
|
||||
const r1 = rid();
|
||||
const g = await dp.adopt({ rid: rid(), coach: claimOf(C1), person: fresh.id });
|
||||
ok(g.code === 'grace', 'adopt: a sign-up inside the 24-hour grace is refused', g);
|
||||
const ok1 = await dp.adopt({ rid: r1, coach: claimOf(C1), person: live.id, kind: 'draft', week: '2026-11-16', slot: '1.1' });
|
||||
ok(ok1.ok && /^iap:\d+$/.test(ok1.ref) && ok1.person === live.id && ok1.expires === env.now + 3 * D && ok1.holdUntil === env.now + 48 * H, 'adopt: a 5x coach with payouts on and no $20 buy adopts; 3-day window, 48 h hold', ok1);
|
||||
const la = await accounts.byEmail('live@x.co');
|
||||
ok(la.sponsorRef === 'coach1', 'adopt: the sponsor is now the coach (InstantAdPay record)', la.sponsorRef);
|
||||
ok(B.deliberate.some(d => d.email === 'live@x.co' && d.by === 'adopt'), "adopt: the move went through the deliberate path (sponsorfollow + the hub's sponsor-change, by 'adopt')");
|
||||
const open = await tank.openOf('live@x.co');
|
||||
ok(open.length === 1 && open[0].expires - open[0].ts === 3 * D && /5xYourTeam draft pick/.test(open[0].note), "adopt: the tank adoption's own window is 3 days, noted as a draft pick", open[0]);
|
||||
ok(B.mails.length === 1 && B.mails[0].to === 'live@x.co' && /is now your sponsor on InstantAdPay/.test(B.mails[0].subject), 'mail: exactly one, the normal "X is now your sponsor" adoption email', B.mails.map(m => m.subject));
|
||||
ok(B.chats.some(c => c.to === 'live@x.co' && /your coach from 5xYourTeam/.test(c.text)), 'adopt: a site chat from the coach (site messages only)');
|
||||
ok(!tank.payView().some(x => x.email === 'live@x.co'), 'adopt: no switch-on-payouts reminder mails are queued for a pick');
|
||||
ok(B.assigned.length === 0, 'adopt: no payments-topic pickup post');
|
||||
const rep = await dp.adopt({ rid: r1, coach: claimOf(C1), person: live.id });
|
||||
ok(rep.ok && rep.repeat && rep.ref === ok1.ref && B.mails.length === 1, 'adopt: the same rid again answers the first result and sends nothing');
|
||||
const tw = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: live.id });
|
||||
ok(tw.code === 'gone', 'adopt: someone already picked is no longer in the pool', tw);
|
||||
// fresh lock check at adopt (the pool cache is 30 s old at most; the adopt asks the hub again)
|
||||
accounts.add('late@x.co'); const lp = (await dp.pool()).pool; dp._poolReset();
|
||||
const late = (await dp.pool()).pool.find(c => c.username === 'late');
|
||||
hub.locked.add('late@x.co'); const al = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: late.id });
|
||||
ok(al.code === 'gone' || al.code === 'locked', 'adopt: locked a moment ago = refused', al); hub.locked.delete('late@x.co'); void lp;
|
||||
hub.down = true; dp._poolReset();
|
||||
const ad = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: late.id });
|
||||
ok(ad.error && (ad.code === 'gone' || ad.code === 'hub_unknown'), 'adopt: a hub that does not answer refuses (the conservative side)', ad);
|
||||
hub.down = false; dp._poolReset();
|
||||
// 10 open picks at most
|
||||
for (let i = 0; i < 10; i++) accounts.add('fill' + i + '@x.co');
|
||||
const pl = (await dp.pool()).pool; let made = 0;
|
||||
for (const c of pl.filter(c => /^fill/.test(c.username))) { const r = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: c.id }); if (r.ok) made++; }
|
||||
const over = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: plain.id });
|
||||
ok(made === 10 && over.code === 'full', 'adopt: 10 open picks a coach, the 11th is refused', { made, over });
|
||||
|
||||
// ---- auto-assign vs the pick window ----
|
||||
env.now += 30 * H; // past any 24-hour activation hold
|
||||
const tick = await tank.readyTick();
|
||||
ok(!tick.assigned.some(x => x.adoptee === 'live@x.co') && (await accounts.byEmail('live@x.co')).sponsorRef === 'coach1', 'conflict rule: a drafted person (wallet linked) is out of the tank, never auto-assigned while the pick runs');
|
||||
ok(!(await tank.waiting()).some(w => w.email === 'live@x.co'), 'conflict rule: not on the waiting list while picked');
|
||||
|
||||
// ---- release ----
|
||||
const early = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' });
|
||||
ok(early.code === 'hold', 'release: not inside the 48-hour hold', early);
|
||||
const notMine = await dp.release({ rid: rid(), coach: claimOf(C2), ref: ok1.ref, why: 'coach' });
|
||||
ok(notMine.code === 'not_yours', 'release: another coach cannot release it', notMine);
|
||||
const tooEarly = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'return' });
|
||||
ok(tooEarly.code === 'too_early', 'return: not before the 3 days', tooEarly);
|
||||
env.now += 20 * H; // 50 h after the pick
|
||||
const rel = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' });
|
||||
const back = await accounts.byEmail('live@x.co');
|
||||
ok(rel.ok && rel.outcome === 'returned' && back.sponsorRef === '', 'release: after 48 h the pick goes back to the tank', rel);
|
||||
ok(B.deliberate.some(d => d.email === 'live@x.co' && d.by === 'release' && /released by the coach/.test(d.note)), "release: the move went through the deliberate path (by 'release')");
|
||||
dp._poolReset();
|
||||
const again = (await dp.pool()).pool.find(c => c.id === live.id);
|
||||
ok(again && again.joinedAt === live.joinedAt && !again.opensAt, 'release: back in the pool with the ORIGINAL join time, no new sign-up grace', again);
|
||||
ok(again.adoptionsTotal === 1 && again.adoptions === 0, 'release: the dropped pick still counts toward their two (total 1; 0 outside 5xYourTeam, which counts its own picks)', again);
|
||||
const relAgain = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' });
|
||||
ok(relAgain.ok && relAgain.already && relAgain.outcome === 'returned', 'release: a repeat answers "already" and changes nothing');
|
||||
ok(B.mails.length === 11, 'mail: still only the adoption emails (1 + 10), nothing on release', B.mails.length);
|
||||
// second adoption: C3 picks them again; at 3 days unstarted they stay with C3 (adopted twice)
|
||||
const C3 = B.coach('coach3@x.co', 44);
|
||||
const p2 = await dp.adopt({ rid: rid(), coach: claimOf(C3), person: live.id, kind: 'instant' });
|
||||
ok(p2.ok, 'second pick of the same person (their 2nd adoption)', p2);
|
||||
env.now += 3 * D + H;
|
||||
const sw = await dp.sweep();
|
||||
ok(sw.kept === 1 && (await accounts.byEmail('live@x.co')).sponsorRef === 'coach3', 'sweep: at 3 days, a person on their 2nd adoption stays with the coach (kept)', sw);
|
||||
dp._poolReset();
|
||||
ok(!(await dp.pool()).pool.some(c => c.id === live.id), 'pool: someone adopted twice is never offered again');
|
||||
|
||||
// ---- the hourly sweep: wallet alone is not started; started = done; locked = kept; hub silent = wait ----
|
||||
const C4 = B.coach('coach4@x.co', 45);
|
||||
accounts.add('w1@x.co'); accounts.add('s1@x.co'); accounts.add('k1@x.co'); accounts.add('u1@x.co'); dp._poolReset();
|
||||
const pool4 = (await dp.pool()).pool; const idOf = u => pool4.find(c => c.username === u).id;
|
||||
const pw = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('w1') }); const ps = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('s1') });
|
||||
const pk = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('k1') }); const pu = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('u1') });
|
||||
ok(pw.ok && ps.ok && pk.ok && pu.ok, 'four more picks for the sweep checks');
|
||||
accounts._by.get('w1@x.co').address = addr(); // linked a wallet only
|
||||
accounts._by.get('s1@x.co').address = addr(); accounts._by.get('s1@x.co').memberId = 77; B.buy(77, 1000); // switched on payouts + bought
|
||||
// tank.sweep (the IAP 7-day sweep) leaves a pick's expired adoption alone
|
||||
env.now += 3 * D + H;
|
||||
hub.locked.add('k1@x.co');
|
||||
const st0 = await dp.status({ ids: [idOf('s1'), idOf('w1'), 'h_ffffffffffffffff'] });
|
||||
ok(st0.people['h_ffffffffffffffff'] === null, 'status: someone 5xYourTeam holds no pick for answers null');
|
||||
ok(st0.people[idOf('s1')].payouts > 0 && st0.people[idOf('s1')].purchase > 0 && st0.people[idOf('w1')].wallet > 0 && !st0.people[idOf('w1')].payouts, 'status: milestones (wallet / payouts / purchase as first-seen times)', st0.people[idOf('w1')]);
|
||||
ok(!JSON.stringify(st0).includes('@'), 'status: no contact data');
|
||||
hub.down = true;
|
||||
const swU = await dp.sweep();
|
||||
ok(swU.waiting >= 1 && swU.done === 1 && (await accounts.byEmail('u1@x.co')).sponsorRef === 'coach4', 'sweep: hub not answering = the return waits, nobody moved', swU);
|
||||
hub.down = false;
|
||||
const sw2 = await dp.sweep();
|
||||
ok(sw2.returned === 2 && sw2.kept === 1, 'sweep: started = done (even with the hub silent), wallet-only + plain = returned, locked = kept', sw2);
|
||||
ok((await accounts.byEmail('w1@x.co')).sponsorRef === '' && (await accounts.byEmail('s1@x.co')).sponsorRef === 'coach4' && (await accounts.byEmail('k1@x.co')).sponsorRef === 'coach4', 'sweep: sponsors after the 3 days (wallet-only back to the tank; started and locked stay)');
|
||||
const tsw = await tank.sweep();
|
||||
ok(tsw.back === 0, 'tank.sweep: never touches a pick (the pick rule decides, not the 7-day wallet rule)', tsw);
|
||||
// a pick whose tank adoption was closed some other way (released on InstantAdPay itself, a LinkSpin follow) reconciles
|
||||
accounts.add('m1@x.co'); dp._poolReset(); const pm = (await dp.pool()).pool.find(c => c.username === 'm1');
|
||||
const pmk = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: pm.id });
|
||||
for (const a of await tank.openOf('m1@x.co')) await tank.closeAdoption(a.id, 'moved');
|
||||
const stm = await dp.status({ ids: [pm.id] });
|
||||
ok(pmk.ok && stm.people[pm.id].pick.status === 'moved', 'reconcile: a pick closed on InstantAdPay shows as moved', stm.people[pm.id].pick);
|
||||
// the log: every call with a reason
|
||||
const av = await dp.adminView();
|
||||
ok(av.log.length > 20 && av.log.every(l => l.op && l.ts && (l.ok || l.code)) && av.log.some(l => l.op === 'adopt' && !l.ok && l.code === 'not_vested') && av.log.some(l => l.op === 'sweep' && l.code === 'kept'), 'log: every call is logged with an outcome code / reason', av.log.slice(0, 3));
|
||||
ok(!JSON.stringify(av.picks).includes('@'), 'admin view: picks carry no emails');
|
||||
}
|
||||
|
||||
// ---------------- Part B: the routes on a local copy ----------------
|
||||
async function partB() {
|
||||
console.log('-- Part B: HTTP routes on a local copy');
|
||||
const port = Number(process.env.DRAFT_E2E_PORT || 8825);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-draft-b-'));
|
||||
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_EMAIL: 'admin@iap.test', ADMIN_PASSWORD: 'localtest', DRAFT_PARTNER_SECRET: SECRET, DRAFT_ALLOW_NO_HUB: '1', LS_URL: 'http://127.0.0.1:9', HUB_ENABLED: '' });
|
||||
delete env.DATABASE_URL; delete env.NODE_ENV;
|
||||
const child = spawn(process.execPath, ['server.js'], { cwd: SITE, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let log = ''; child.stdout.on('data', d => { log += d; }); child.stderr.on('data', d => { log += d; });
|
||||
const base = 'http://127.0.0.1:' + port;
|
||||
try {
|
||||
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(base + '/api/config')).ok; } catch (e) {} if (!up) await new Promise(r => setTimeout(r, 500)); }
|
||||
ok(up, 'local copy up on :' + port, up ? undefined : log.slice(-600));
|
||||
if (!up) return;
|
||||
const call = async (op, body, opts) => { const raw = JSON.stringify(body || {}); const ts = String(Date.now()); const sig = (opts && opts.sig) || crypto.createHmac('sha256', SECRET).update('draft.v1.' + ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(base + '/api/partner/draft/' + op, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Draft-Ts': ts, 'X-Draft-Sig': sig }, body: raw }); return { status: r.status, body: await r.json().catch(() => null) }; };
|
||||
const p = await call('pool', {});
|
||||
ok(p.status === 200 && p.body.ok && Array.isArray(p.body.pool) && p.body.rules.maxOpen === 10, 'POST /api/partner/draft/pool signed: 200 with rules + pool', p);
|
||||
ok((await call('pool', {}, { sig: 'f'.repeat(64) })).status === 401, 'unsigned / wrong signature: 401');
|
||||
ok((await call('nope', {})).status === 404, 'unknown op: 404');
|
||||
const a = await call('adopt', { rid: 'rid-route-0001', coach: { wallet: addr(), positions: 1 }, person: 'h_0000000000000000' });
|
||||
ok(a.status === 400 && a.body.code === 'coach_unknown', 'adopt for an unknown coach: 400 with a code', a.body);
|
||||
const s = await call('status', { ids: ['h_0000000000000000'] });
|
||||
ok(s.status === 200 && s.body.people['h_0000000000000000'] === null, 'status: 200, unknown person null');
|
||||
ok((await fetch(base + '/api/admin/draft')).status === 401, 'GET /api/admin/draft needs the admin');
|
||||
} finally { child.kill(); }
|
||||
}
|
||||
|
||||
await partA();
|
||||
if (!process.env.DRAFT_SKIP_B) await partB();
|
||||
console.log(fails ? 'FAILED ' + fails + ' (passed ' + passes + ')' : 'ALL PASSED (' + passes + ')');
|
||||
process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,351 @@
|
||||
// Network hub sync (hubsync.js) against a REAL network-hub started in this process (JSON mode, throwaway DATA_DIR), with
|
||||
// InstantAdPay's own accounts / lssync / lsinbound in JSON mode on another throwaway dir. Synthetic members only.
|
||||
// Then the flag-off check: server.js started with and without HUB_ENABLED.
|
||||
// node qa/hubsync.test.cjs (HUB_DIR = the network-hub checkout; needs /v1/resolve by {id})
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const http = require('http');
|
||||
const crypto = require('crypto');
|
||||
const assert = require('assert');
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const HUB_DIR = process.env.HUB_DIR || ['..', path.join('..', '..')].flatMap(up => ['network-hub', 'network-hub-resolve-id'].map(d => path.join(ROOT, up, d))).find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||
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); } }
|
||||
const IAP_SECRET = 'i'.repeat(40), CTB_SECRET = 'c'.repeat(40);
|
||||
const W = k => '0x' + String(k).repeat(40).slice(0, 40);
|
||||
const sig = (secret, ts, raw) => crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
||||
const listen = srv => new Promise(ok => srv.listen(0, '127.0.0.1', () => ok(srv.address().port)));
|
||||
// mail audit (2026-11-14): every outbound request this process makes is recorded; only the local hub and site may be called.
|
||||
// mailer.js sends with https.request (SendGrid), Telegram and Sendy go out over https too, so both doors are watched.
|
||||
const outside = [];
|
||||
{ const realFetch = global.fetch; global.fetch = (u, o) => { const s = String(u && u.url ? u.url : u); if (!/^http:[/][/]127[.]0[.]0[.]1:/.test(s)) outside.push(s); return realFetch(u, o); };
|
||||
const https = require('https'); const realReq = https.request; https.request = function (...a) { outside.push('https ' + JSON.stringify((a[0] && a[0].hostname) || a[0])); return realReq.apply(this, a); }; }
|
||||
|
||||
delete process.env.DATABASE_URL; delete process.env.LS_SYNC_SECRET; // JSON stores, LinkSpin push off
|
||||
const HUB_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-hub-'));
|
||||
const IAP_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-iap-'));
|
||||
|
||||
(async () => {
|
||||
// InstantAdPay's hook receiver: the same call server.js makes for POST /api/hub/events
|
||||
let hubsync = null;
|
||||
const iapSrv = http.createServer((req, res) => {
|
||||
const chunks = []; req.on('data', c => chunks.push(c)); req.on('end', async () => {
|
||||
const r = await hubsync.receive(req.headers, Buffer.concat(chunks).toString('utf8'));
|
||||
res.writeHead(r.status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(r.body));
|
||||
});
|
||||
});
|
||||
const iapPort = await listen(iapSrv);
|
||||
|
||||
// the hub: iap gets hooks and sees emails (it needs them to make accounts); ctb is the other door
|
||||
process.env.DATA_DIR = HUB_DATA;
|
||||
process.env.HUB_SITES = JSON.stringify({ iap: { secret: IAP_SECRET, hook: 'http://127.0.0.1:' + iapPort + '/api/hub/events', seeEmails: true }, ctb: { secret: CTB_SECRET, seeEmails: true } });
|
||||
const hubReq = m => require(path.join(HUB_DIR, m));
|
||||
const hubConfig = hubReq('lib/config'); const hubStore = hubReq('lib/store'); const hooks = hubReq('lib/hooks');
|
||||
const hubSrv = await hubReq('server').start(0); const hubPort = hubSrv.address().port;
|
||||
const HUB = 'http://127.0.0.1:' + hubPort;
|
||||
const deliver = () => hooks.deliver('iap', hubConfig.SITES.iap);
|
||||
async function ctb(p, body) { // a call from another door
|
||||
const raw = JSON.stringify(body), ts = String(Date.now());
|
||||
const r = await fetch(HUB + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': 'ctb', 'X-Hub-Ts': ts, 'X-Hub-Sig': sig(CTB_SECRET, ts, raw) }, body: raw });
|
||||
return r.json();
|
||||
}
|
||||
const hubPerson = email => hubReq('lib/people').byEmail(email);
|
||||
|
||||
// InstantAdPay's side, JSON mode
|
||||
const accounts = require(path.join(ROOT, 'accounts.js')); accounts.init({ dataDir: IAP_DATA });
|
||||
const lssync = require(path.join(ROOT, 'lssync.js')); const lsinbound = require(path.join(ROOT, 'lsinbound.js'));
|
||||
lssync.init({ dataDir: IAP_DATA, accounts }); lsinbound.init({ dataDir: IAP_DATA, accounts, lssync });
|
||||
const old = (await accounts.ensure('old.member@example.test', '', null, null)).account; // made before the flag went on
|
||||
await accounts.setUsername(old.email, 'oldie');
|
||||
await new Promise(r => setTimeout(r, 5));
|
||||
process.env.HUB_ENABLED = '1'; process.env.HUB_URL = HUB; process.env.HUB_SECRET = IAP_SECRET; process.env.HUB_SITE = 'iap';
|
||||
hubsync = require(path.join(ROOT, 'hubsync.js'));
|
||||
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound });
|
||||
accounts.onChange(e => { lssync.touch(e); hubsync.touch(e); }); accounts.onWalletLinked(e => hubsync.wallet(e)); // as server.js wires it
|
||||
const settle = () => new Promise(r => setTimeout(r, 50));
|
||||
const signed = (events, secret, ts) => { const raw = JSON.stringify({ events }); ts = ts || String(Date.now()); return { headers: { 'x-hub-ts': ts, 'x-hub-sig': sig(secret || IAP_SECRET, ts, raw) }, raw }; };
|
||||
|
||||
await t('hook signature: wrong secret and a stale timestamp are refused, a good one is accepted', async () => {
|
||||
let s = signed([], 'z'.repeat(40)); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 401);
|
||||
s = signed([], IAP_SECRET, String(Date.now() - 6 * 60000)); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 401);
|
||||
s = signed([]); s.headers['x-hub-sig'] = s.headers['x-hub-sig'].replace(/^./, c => c === 'a' ? 'b' : 'a'); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 401);
|
||||
s = signed([]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200);
|
||||
});
|
||||
|
||||
let ann, bob;
|
||||
await t('round trip: two CTB joins reach InstantAdPay as waiting accounts, sponsor line kept', async () => {
|
||||
await ctb('/v1/join', { email: 'ann@example.test', username: 'annctb' });
|
||||
await ctb('/v1/join', { email: 'bob@example.test', username: 'bobctb', ref: 'annctb' });
|
||||
assert.strictEqual(await deliver(), 2);
|
||||
ann = await accounts.byEmail('ann@example.test'); bob = await accounts.byEmail('bob@example.test');
|
||||
assert.ok(ann && bob, 'both accounts exist');
|
||||
assert.strictEqual(bob.joinedVia, 'hub'); assert.strictEqual(bob.joinedRef, 'hub:ctb');
|
||||
assert.ok(accounts.isUnclaimedShell(bob), 'a waiting account, left out of the sweeps');
|
||||
assert.strictEqual(bob.sponsorRef, ann.username || ann.code); assert.strictEqual(bob.username, 'bobctb');
|
||||
assert.strictEqual((await accounts.listAll(100)).filter(a => a.joinedVia === 'hub').length, 0, 'listAll leaves the waiting accounts out');
|
||||
assert.strictEqual(hubStore.cursor('iap'), hubStore.eventsAfter(0, 100).length, 'hub cursor moved after the 2xx');
|
||||
});
|
||||
|
||||
await t('the same events delivered again change nothing', async () => {
|
||||
const before = JSON.stringify(await accounts.listAll(100, { shells: true }));
|
||||
const skipped = hubsync.adminView().skipped;
|
||||
hubStore.setCursor('iap', 0); await hubStore.flush();
|
||||
assert.strictEqual(await deliver(), 2);
|
||||
assert.strictEqual(JSON.stringify(await accounts.listAll(100, { shells: true })), before);
|
||||
assert.strictEqual(hubsync.adminView().skipped, skipped + 2);
|
||||
});
|
||||
|
||||
await t('a sponsor not on InstantAdPay yet comes along (climbs the hub line)', async () => {
|
||||
await ctb('/v1/join', { email: 'dee@example.test', username: 'deectb' });
|
||||
await ctb('/v1/join', { email: 'carl@example.test', username: 'carlctb', ref: 'deectb' });
|
||||
const evs = hubStore.eventsAfter(hubStore.cursor('iap'), 10); const carlEv = evs.find(e => e.personId === hubPerson('carl@example.test').id);
|
||||
const s = signed([carlEv]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200); // carl's event alone, before dee's
|
||||
const dee = await accounts.byEmail('dee@example.test'); const carl = await accounts.byEmail('carl@example.test');
|
||||
assert.ok(dee && dee.joinedVia === 'hub', 'sponsor shell built'); assert.strictEqual(carl.sponsorRef, dee.username || dee.code);
|
||||
await deliver(); // dee's own event later: already there, nothing new
|
||||
assert.strictEqual((await accounts.listAll(100, { shells: true })).filter(a => a.email === 'dee@example.test').length, 1);
|
||||
});
|
||||
|
||||
await t('an InstantAdPay sign-up is reported to the hub under its InstantAdPay sponsor; its own event is skipped', async () => {
|
||||
await accounts.touchSeen(ann.email); // ann claimed her waiting account by signing in
|
||||
const r = await accounts.ensure('erin@example.test', ann.username || ann.code, null, null); assert.ok(r.created);
|
||||
await settle(); await hubsync.flush(true);
|
||||
const p = hubPerson('erin@example.test'); assert.ok(p, 'hub has erin');
|
||||
assert.strictEqual(p.door.site, 'iap'); assert.strictEqual(p.sponsorId, hubPerson('ann@example.test').id);
|
||||
const applied = hubsync.adminView().applied; await deliver();
|
||||
assert.strictEqual(hubsync.adminView().applied, applied, 'own join not applied back');
|
||||
await accounts.setUsername('erin@example.test', 'erin_iap'); await settle(); await hubsync.flush(true);
|
||||
assert.strictEqual(hubPerson('erin@example.test').aliases.iap, 'erin_iap', 'username follows');
|
||||
});
|
||||
|
||||
await t('a wallet linked on InstantAdPay reaches the hub', async () => {
|
||||
const x = await accounts.linkWallet('erin@example.test', W('e')); assert.ok(!x.error, x.error);
|
||||
await settle(); await hubsync.flush(true);
|
||||
assert.strictEqual(hubPerson('erin@example.test').wallet, W('e'));
|
||||
});
|
||||
|
||||
await t('wallet.connected fills a waiting account, never a claimed one', async () => {
|
||||
await ctb('/v1/wallet', { email: 'bob@example.test', wallet: W('b') });
|
||||
await ctb('/v1/wallet', { email: 'ann@example.test', wallet: W('a') });
|
||||
await deliver();
|
||||
assert.strictEqual((await accounts.byEmail('bob@example.test')).address, W('b'));
|
||||
assert.strictEqual((await accounts.byEmail('ann@example.test')).address, null, 'ann signed in: she links her own wallet here');
|
||||
});
|
||||
|
||||
await t('an existing InstantAdPay account keeps its sponsor; the difference is recorded', async () => {
|
||||
await accounts.setSponsorRef(old.email, ann.username || ann.code);
|
||||
await ctb('/v1/join', { email: old.email, ref: 'bobctb' }); await deliver();
|
||||
const a = await accounts.byEmail(old.email);
|
||||
assert.strictEqual(a.sponsorRef, ann.username || ann.code, 'InstantAdPay sponsor stands');
|
||||
assert.strictEqual(a.joinedVia, null, 'not turned into a waiting account');
|
||||
const d = hubsync.adminView().disagreements.find(x => x.email === old.email);
|
||||
assert.ok(d && d.iap === 'ann@example.test' && d.hub === 'bob@example.test', JSON.stringify(d));
|
||||
assert.ok(!hubsync.adminView().disagreements.find(x => x.email === 'erin@example.test'), 'agreeing members are not listed');
|
||||
});
|
||||
|
||||
await t('a hub that is down: the hook answers 503 (hub retries), the outbox keeps the join, sign-up is not blocked', async () => {
|
||||
await ctb('/v1/join', { email: 'fay@example.test' });
|
||||
process.env.HUB_URL = 'http://127.0.0.1:1';
|
||||
await assert.rejects(deliver(), /503/);
|
||||
assert.strictEqual(await accounts.byEmail('fay@example.test'), null);
|
||||
const r = await accounts.ensure('gus@example.test', '', null, null); assert.ok(r.created, 'sign-up went through');
|
||||
await settle(); await hubsync.flush(true);
|
||||
const saved = JSON.parse(fs.readFileSync(path.join(IAP_DATA, 'hubsync.json'), 'utf8'));
|
||||
assert.ok(saved.outbox.find(i => i.email === 'gus@example.test' && i.tries === 1), 'persisted with a retry count');
|
||||
process.env.HUB_URL = HUB;
|
||||
await deliver(); assert.ok(await accounts.byEmail('fay@example.test'), 'retried event applied');
|
||||
await hubsync.flush(true); assert.ok(hubPerson('gus@example.test'), 'join sent once the hub is back');
|
||||
assert.strictEqual(hubsync.adminView().outbox, 0);
|
||||
});
|
||||
|
||||
await t('a refused call is final (409 wallet taken), not retried forever', async () => {
|
||||
await accounts.ensure('hal@example.test', '', null, null); await settle(); await hubsync.flush(true);
|
||||
await ctb('/v1/join', { email: 'ivy@example.test' }); await ctb('/v1/wallet', { email: 'ivy@example.test', wallet: W('9') });
|
||||
await accounts.linkWallet('hal@example.test', W('9')); await settle(); await hubsync.flush(true);
|
||||
const v = hubsync.adminView(); assert.strictEqual(v.outbox, 0); assert.ok(v.recent.find(l => l.type === 'out-refused' && l.code === 'wallet_taken'));
|
||||
});
|
||||
|
||||
await t('rule 2: a paid Purchase on the InstantAdPay contract reaches the hub and moves the network sponsor to this contract (2026-11-14)', async () => {
|
||||
// tureia2003's shape: locked on LinkSpin under silverstussy (activated only), then bound AND paid here under paidtowatch
|
||||
await ctb('/v1/join', { email: 'ptw@example.test', username: 'ptw' }); await ctb('/v1/wallet', { email: 'ptw@example.test', wallet: W('d') });
|
||||
await ctb('/v1/join', { email: 'sil@example.test', username: 'sil' }); await ctb('/v1/wallet', { email: 'sil@example.test', wallet: W('f') });
|
||||
await ctb('/v1/join', { email: 'tur@example.test', ref: 'sil', username: 'tur' });
|
||||
await ctb('/v1/contract-bind', { contract: 'linkspin', email: 'tur@example.test', wallet: W('7'), sponsorRef: W('f') });
|
||||
assert.strictEqual(hubPerson('tur@example.test').sponsorId, hubPerson('sil@example.test').id);
|
||||
const members = { 5: { account: W('d') }, 12: { account: W('7') } };
|
||||
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound, chain: { member: async id => members[id] || null } });
|
||||
hubsync.onChain({ type: 'MemberActivated', id: 12, account: W('7'), sponsorId: 5 });
|
||||
hubsync.onChain({ type: 'Purchase', buyerId: 12, priceCents: 0, paidWei: '0', tx: '0xfree' }); // nothing paid in: not a spend
|
||||
hubsync.onChain({ type: 'Purchase', buyerId: 12, priceCents: 3500, paidWei: '1000', tx: '0xpaid', ts: 1700000000000 });
|
||||
hubsync.onChain({ type: 'Purchase', buyerId: 12, priceCents: 3500, paidWei: '1000', tx: '0xpaid', ts: 1700000000000 }); // seen twice
|
||||
await settle(); await hubsync.flush(true);
|
||||
const p = hubPerson('tur@example.test');
|
||||
assert.strictEqual(p.bindings.iap.sponsorId, hubPerson('ptw@example.test').id);
|
||||
assert.strictEqual(p.bindings.iap.spentCents, 3500, 'one purchase counted once');
|
||||
assert.strictEqual(p.bindings.linkspin.sponsorId, hubPerson('sil@example.test').id, 'the LinkSpin lock keeps its sponsor');
|
||||
assert.strictEqual(p.sponsorId, hubPerson('ptw@example.test').id, 'network sponsor = the contract with money spent');
|
||||
assert.strictEqual(hubsync.adminView().outbox, 0);
|
||||
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound });
|
||||
});
|
||||
|
||||
await t('sponsor.changed and unknown event types are acknowledged and ignored', async () => {
|
||||
const s = signed([{ seq: 99001, type: 'sponsor.changed', personId: hubPerson('bob@example.test').id, data: { by: 'admin' } }, { seq: 99002, type: 'member.blocked', personId: 'h_0000000000000000', data: {} }]);
|
||||
assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200);
|
||||
});
|
||||
|
||||
const HP = hubReq('lib/people');
|
||||
await t('rule 2 on arrival: someone the InstantAdPay contract holds arrives under that lock sponsor, not the network sponsor; sponsor.changed never moves them', async () => {
|
||||
await ctb('/v1/join', { email: 'lx@example.test', username: 'lockx' }); // their sponsor on the InstantAdPay contract
|
||||
await ctb('/v1/join', { email: 'ly@example.test', username: 'locky' }); // their sponsor on LinkSpin, where the money was spent
|
||||
await ctb('/v1/join', { email: 'lk@example.test', username: 'lockkid', ref: 'locky' });
|
||||
HP.bindContract({ site: 'iap', contract: 'iap', email: 'lk@example.test', wallet: W('3'), sponsorRef: 'lockx', at: 1000 });
|
||||
HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'lk@example.test', wallet: W('3'), sponsorRef: 'locky', at: 2000, spentCents: 2500 });
|
||||
await hubStore.flush();
|
||||
const hp = hubPerson('lk@example.test');
|
||||
assert.strictEqual(hp.sponsorId, hubPerson('ly@example.test').id, 'network sponsor = LinkSpin (money spent there)');
|
||||
assert.strictEqual(hp.bindings.iap.sponsorId, hubPerson('lx@example.test').id);
|
||||
await deliver();
|
||||
const kid = await accounts.byEmail('lk@example.test'); const lx = await accounts.byEmail('lx@example.test');
|
||||
assert.ok(kid && lx, 'both arrived');
|
||||
assert.strictEqual(kid.sponsorRef, lx.username || lx.code, 'the InstantAdPay lock sponsor is written here');
|
||||
const s = signed([{ seq: 99101, type: 'sponsor.changed', personId: hp.id, data: { by: 'contract', contract: 'linkspin' } }]);
|
||||
assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200);
|
||||
assert.strictEqual((await accounts.byEmail('lk@example.test')).sponsorRef, lx.username || lx.code, 'sponsor.changed is ignored');
|
||||
// climbing: a lock sponsor not on InstantAdPay yet comes along before the member (their event alone)
|
||||
await ctb('/v1/join', { email: 'lz@example.test', username: 'lockz' });
|
||||
await ctb('/v1/join', { email: 'lk2@example.test', username: 'lockkid2', ref: 'locky' });
|
||||
HP.bindContract({ site: 'iap', contract: 'iap', email: 'lk2@example.test', wallet: W('4'), sponsorRef: 'lockz', at: 3000, spentCents: 2000 });
|
||||
HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'lk2@example.test', wallet: W('4'), sponsorRef: 'locky', at: 1500, spentCents: 2000 }); // earlier spend: network = locky
|
||||
await hubStore.flush();
|
||||
assert.strictEqual(hubPerson('lk2@example.test').sponsorId, hubPerson('ly@example.test').id);
|
||||
const ev = hubStore.eventsAfter(0, 1e6).find(e => e.type === 'member.joined' && e.personId === hubPerson('lk2@example.test').id);
|
||||
const s2 = signed([ev]); assert.strictEqual((await hubsync.receive(s2.headers, s2.raw)).status, 200);
|
||||
const lz = await accounts.byEmail('lz@example.test');
|
||||
assert.ok(lz, 'the lock sponsor came along'); assert.strictEqual((await accounts.byEmail('lk2@example.test')).sponsorRef, lz.username || lz.code);
|
||||
await deliver();
|
||||
});
|
||||
|
||||
// the holding tank, as server.js wires it with HUB_ENABLED, with a mailer and messages that only record
|
||||
const tank = require(path.join(ROOT, 'tank.js'));
|
||||
const sent = [];
|
||||
const mailer = { hasKey: () => true, send: async (...a) => { sent.push(['mail', a[0], a[1]]); } };
|
||||
const messages = { sendChat: async (...a) => { sent.push(['chat', a[2]]); }, deliver: async (...a) => { sent.push(['notice', a[2]]); }, lastFrom: async () => Date.now() }; // every sponsor 'just wrote': rescue warnings are not what this checks
|
||||
tank.init({ dataDir: IAP_DATA, accounts, chain: { recentEvents: () => [], member: async () => null }, messages, mailer,
|
||||
hooks: { network: async (email, address) => (await hubsync.hubSponsor(email)) || lsinbound.networkSponsor(email, address), networkHeld: a => hubsync.heldAmong(a), networkLocked: e => hubsync.lockedAnywhere(e) } });
|
||||
|
||||
await t('rule 3: the tank never offers anyone locked on any network contract or sponsored in the hub; release refuses a locked member', async () => {
|
||||
await ctb('/v1/join', { email: 'tk1@example.test', username: 'tk1ctb', ref: 'annctb' }); // the hub knows a sponsor
|
||||
for (const e of ['tk1', 'tk2', 'tk3']) assert.ok((await accounts.ensure(e + '@example.test', '', null, null)).created); // signed up here, no sponsor
|
||||
await settle(); await hubsync.flush(true);
|
||||
HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'tk2@example.test', wallet: W('5'), sponsorRef: '' }); await hubStore.flush(); // locked, top of that tree
|
||||
hubsync._heldReset();
|
||||
const held = await hubsync.heldAmong([await accounts.byEmail('tk1@example.test'), await accounts.byEmail('tk2@example.test'), await accounts.byEmail('tk3@example.test')]);
|
||||
assert.deepStrictEqual([...held.entries()].sort(), [['tk1@example.test', 'sponsored'], ['tk2@example.test', 'locked']]);
|
||||
const w = (await tank.waiting()).map(x => x.email);
|
||||
assert.ok(w.includes('tk3@example.test'), 'a free member is offered');
|
||||
assert.ok(!w.includes('tk1@example.test') && !w.includes('tk2@example.test'), 'sponsored and locked are not: ' + w.join(','));
|
||||
// tk2 under erin here, not activated here: releasing them to the tank is refused, the hub's lock elsewhere stands
|
||||
const erin = await accounts.byEmail('erin@example.test'); await accounts.setSponsorRef('tk2@example.test', erin.username || erin.code);
|
||||
const r = await tank.release('erin@example.test', 'tk2@example.test');
|
||||
assert.ok(r.error && /locked/.test(r.error), JSON.stringify(r));
|
||||
assert.strictEqual((await accounts.byEmail('tk2@example.test')).sponsorRef, erin.username || erin.code);
|
||||
// the 15-minute tick: with HUB_TANK_ALIGN off tk1 is only held; with it on, aligned to the sponsor the hub knows (ann has a real account here), quietly
|
||||
await tank.readyTick(); assert.strictEqual((await accounts.byEmail('tk1@example.test')).sponsorRef || '', '', 'alignment from the hub is off by default');
|
||||
process.env.HUB_TANK_ALIGN = 'on'; await tank.readyTick(); delete process.env.HUB_TANK_ALIGN;
|
||||
assert.strictEqual((await accounts.byEmail('tk1@example.test')).sponsorRef, ann.username || ann.code, 'aligned to the hub sponsor');
|
||||
});
|
||||
|
||||
await t('rule 3 fail-safe: hub unreachable past the 1-hour cache = nobody it was asked about is offered; back = offered again', async () => {
|
||||
process.env.HUB_URL = 'http://127.0.0.1:1'; hubsync._heldAge(30 * 60000);
|
||||
assert.ok((await tank.waiting()).map(x => x.email).includes('tk3@example.test'), 'within the hour the last answer stands');
|
||||
hubsync._heldReset(); // nothing cached, hub down
|
||||
assert.ok(!(await tank.waiting()).map(x => x.email).includes('tk3@example.test'), 'unknown = held');
|
||||
assert.strictEqual(await hubsync.lockedAnywhere('tk3@example.test'), 'unknown');
|
||||
process.env.HUB_URL = HUB; hubsync._heldReset();
|
||||
assert.ok((await tank.waiting()).map(x => x.email).includes('tk3@example.test'));
|
||||
});
|
||||
|
||||
await t('an adoption-window expiry (tank label expire) reaches the hub as a sponsor change by expiry (fix 2026-11-15)', async () => {
|
||||
assert.strictEqual(hubsync._hubBy('expire'), 'expiry'); assert.strictEqual(hubsync._hubBy('adopt'), 'adopt');
|
||||
const recs = new Map(); const follow = { get: e => recs.get(String(e).toLowerCase()) || null };
|
||||
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound, follow }); // as server.js passes followStore
|
||||
const erin = await accounts.byEmail('erin@example.test');
|
||||
recs.set('tk3@example.test', { by: 'adopt', sponsorEmail: 'erin@example.test', at: Date.now() });
|
||||
await accounts.setSponsorRef('tk3@example.test', erin.username || erin.code); await settle(); await hubsync.flush(true);
|
||||
let hp = hubPerson('tk3@example.test'); assert.strictEqual(hp.sponsorId, hubPerson('erin@example.test').id, 'adopt reached the hub');
|
||||
recs.set('tk3@example.test', { by: 'expire', sponsorEmail: '', at: Date.now() + 1 });
|
||||
await accounts.setSponsorRef('tk3@example.test', ''); await settle(); await hubsync.flush(true);
|
||||
hp = hubPerson('tk3@example.test'); const last = hp.sponsorHistory[hp.sponsorHistory.length - 1];
|
||||
assert.strictEqual(hp.sponsorId, null, 'expiry cleared the hub sponsor'); assert.strictEqual(last.by, 'expiry', JSON.stringify(last));
|
||||
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound }); // back as the other tests had it
|
||||
});
|
||||
|
||||
await t('mail audit: hub arrivals (new, sponsor climbed, existing filled, wallet) and the tank ticks send no mail, chat, notice or outside call', async () => {
|
||||
sent.length = 0; outside.length = 0;
|
||||
await ctb('/v1/join', { email: 'ma@example.test', username: 'mailtop' }); await ctb('/v1/wallet', { email: 'ma@example.test', wallet: W('6') });
|
||||
await ctb('/v1/join', { email: 'mb@example.test', username: 'mailkid', ref: 'mailtop' }); await ctb('/v1/wallet', { email: 'mb@example.test', wallet: W('8') });
|
||||
process.env.HUB_ENABLED = ''; await accounts.ensure('mc@example.test', '', null, null); process.env.HUB_ENABLED = '1'; // here before the hub knew them
|
||||
await ctb('/v1/join', { email: 'mc@example.test', username: 'mailfill' }); // an existing InstantAdPay account: empty fields filled
|
||||
const evs = hubStore.eventsAfter(hubStore.cursor('iap'), 100);
|
||||
const kid = evs.find(e => e.personId === hubPerson('mb@example.test').id && e.type === 'member.joined');
|
||||
const s = signed([kid]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200); // the kid first: the sponsor climbs
|
||||
await deliver();
|
||||
assert.ok(await accounts.byEmail('ma@example.test') && await accounts.byEmail('mb@example.test'));
|
||||
assert.strictEqual((await accounts.byEmail('mb@example.test')).address, W('8'));
|
||||
assert.strictEqual((await accounts.byEmail('mc@example.test')).username, 'mailfill', 'filled');
|
||||
await settle(); await hubsync.flush(true); await tank.readyTick(); await tank.sweep(); await settle(); await hubsync.flush(true);
|
||||
assert.deepStrictEqual(JSON.parse(fs.readFileSync(path.join(IAP_DATA, 'hubsync.json'), 'utf8')).outbox, []);
|
||||
assert.deepStrictEqual(sent, [], 'nothing sent');
|
||||
assert.deepStrictEqual(outside, [], 'no outside call');
|
||||
// the old direct LinkSpin sync never pushes a waiting account the hub made (LinkSpin's registry route would switch payouts
|
||||
// on and email them); a member who signs up here still goes
|
||||
const pushed = []; const lsStub = http.createServer((req, res) => { let d = ''; req.on('data', c => { d += c; }); req.on('end', () => { try { for (const r of JSON.parse(d).rows || []) pushed.push(r.email); } catch (e) {} res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"ok":true,"proto":2}'); }); });
|
||||
process.env.LS_URL = 'http://127.0.0.1:' + await listen(lsStub); process.env.LS_SYNC_SECRET = 's'.repeat(40);
|
||||
try {
|
||||
await lssync.tick(true);
|
||||
assert.ok(pushed.length > 0, 'the sync ran');
|
||||
for (const e of ['ma@example.test', 'mb@example.test', 'lk@example.test', 'bob@example.test']) assert.ok(!pushed.includes(e), e + ' (a hub waiting account) was pushed');
|
||||
assert.ok(pushed.includes('erin@example.test'), 'an InstantAdPay sign-up still syncs');
|
||||
} finally { delete process.env.LS_SYNC_SECRET; lsStub.close(); }
|
||||
// and the hub path itself never loads a mail module
|
||||
const loaded = Object.keys(require.cache).map(f => path.basename(f));
|
||||
for (const m of ['mailer.js', 'sendy.js', 'messages.js', 'drip.js']) assert.ok(!loaded.includes(m), m + ' is loaded');
|
||||
});
|
||||
|
||||
await t('flag off: the module answers 404 and reports nothing', async () => {
|
||||
process.env.HUB_ENABLED = '';
|
||||
const s = signed([]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 404);
|
||||
await accounts.ensure('jon@example.test', '', null, null); await settle();
|
||||
assert.ok(!JSON.parse(fs.readFileSync(path.join(IAP_DATA, 'hubsync.json'), 'utf8')).outbox.length);
|
||||
process.env.HUB_ENABLED = '1';
|
||||
});
|
||||
|
||||
hubSrv.close(); iapSrv.close();
|
||||
|
||||
// server.js itself: without HUB_ENABLED the route does not exist and no hubsync file is written; with it, unsigned = 401
|
||||
async function boot(env) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-site-')); const port = 18000 + Math.floor(Math.random() * 2000);
|
||||
const ch = spawn(process.execPath, ['server.js'], { cwd: ROOT, env: Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_PASSWORD: 'localtest', HUB_ENABLED: '', HUB_URL: '', HUB_SECRET: '' }, env), stdio: 'ignore' });
|
||||
for (let i = 0; i < 120; i++) { try { await fetch('http://127.0.0.1:' + port + '/'); break; } catch (e) { await new Promise(r => setTimeout(r, 250)); } }
|
||||
return { ch, dir, url: 'http://127.0.0.1:' + port };
|
||||
}
|
||||
for (const [label, env, want] of [['off', {}, 'off'], ['on', { HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:1', HUB_SECRET: IAP_SECRET }, 401]]) {
|
||||
await t('server.js with the flag ' + label, async () => {
|
||||
const b = await boot(env);
|
||||
try {
|
||||
const r = await fetch(b.url + '/api/hub/events', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"events":[]}' });
|
||||
const reg = await fetch(b.url + '/api/partner/registry', { method: 'POST', body: '{}' });
|
||||
assert.strictEqual(reg.status, 503, 'LinkSpin route unchanged (no LS secret here)');
|
||||
if (want === 'off') { assert.notStrictEqual(r.status, 401); assert.notStrictEqual(r.status, 200); assert.ok(!fs.existsSync(path.join(b.dir, 'hubsync.json')), 'no hubsync file'); }
|
||||
else { assert.strictEqual(r.status, want); assert.ok(fs.existsSync(path.join(b.dir, 'hubsync.json'))); }
|
||||
} finally { b.ch.kill(); }
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`\n${n - fails}/${n} passed`);
|
||||
process.exit(fails ? 1 : 0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,68 @@
|
||||
// My line: directs' email + origin + search (Marty, 2026-11-12). Boots a throwaway server, makes a sponsor and three directs who
|
||||
// join through tagged links (?src=), then checks in a real browser that "Your line" shows each direct's email, where they came
|
||||
// from and how they joined, that the Activity drop-down shows the same for a direct, and that the search box narrows the list.
|
||||
// Screenshot in qa/out/line-origin.png. node qa/line-origin.mjs
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright/index.js';
|
||||
const { chromium } = (await import('file:///' + PW.replace(/^\/+/, ''))).default;
|
||||
const PORT = 8797, B = 'http://127.0.0.1:' + PORT;
|
||||
const DATA = path.join(os.tmpdir(), 'iap-line-origin-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
|
||||
const ok = [], bad = []; const t = (n, c, x) => (c ? ok : bad).push(n + (c || !x ? '' : ' -> ' + x));
|
||||
const srv = spawn(process.execPath, ['server.js'], { env: { ...process.env, PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'localtest', ADMIN_EMAIL: 'admin@example.com', NODE_ENV: 'test', DATABASE_URL: '' }, stdio: 'ignore' });
|
||||
const bye = c => { try { srv.kill(); } catch (e) {} setTimeout(() => { try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} process.exit(c); }, 500); };
|
||||
for (let i = 0; i < 60; i++) { try { if ((await fetch(B + '/api/stats')).ok) break; } catch (e) {} await new Promise(r => setTimeout(r, 500)); }
|
||||
const DEV = 'c0ffee00c0ffee00c0ffee00c0ffee00';
|
||||
const cookiesOf = r => (r.headers.getSetCookie ? r.headers.getSetCookie() : [r.headers.get('set-cookie')]).filter(Boolean).map(c => String(c).split(';')[0]);
|
||||
const jf = async (p, body, cookie, extra) => { const r = await fetch(B + p, { method: body ? 'POST' : 'GET', redirect: 'manual', headers: Object.assign({ 'Content-Type': 'application/json', Cookie: cookie }, extra || {}), body: body ? JSON.stringify(body) : undefined }); let b = {}; try { b = await r.json(); } catch (e) {} return { r, b }; };
|
||||
async function signIn(email, jarIn, dev, ip) { // each test person gets their own device id, or the one-account-per-person guard blocks them
|
||||
const jar0 = ['iap.dev=' + (dev || DEV), ...(jarIn || [])].join('; ');
|
||||
const xf = { 'X-Forwarded-For': ip || '203.0.113.1' }; // a different test address per person (the per-connection sign-up guard)
|
||||
const st = await jf('/api/auth/email/start', { email, fts: Date.now() - 20000 }, jar0, xf);
|
||||
const code = st.b.devCode || st.b.code; if (!code) { console.log('no dev code for', email, JSON.stringify(st.b)); bye(2); }
|
||||
const vf = await jf('/api/auth/email/verify', { email, code }, jar0, xf);
|
||||
if (vf.b && vf.b.error) console.log('verify', email, vf.b.error);
|
||||
return [jar0, ...cookiesOf(vf.r)].join('; ');
|
||||
}
|
||||
const jar = await signIn('sponsor@example.com');
|
||||
await jf('/api/my/profile', { username: 'sponsorone' }, jar);
|
||||
const me = (await jf('/api/me', null, jar)).b; const tok = me.username || me.refCode; t('sponsor has a link token', !!tok, JSON.stringify(me).slice(0, 120));
|
||||
const directs = [['ann@example.com', '?src=mailergold', 'https://mailer.gold/x'], ['bob@example.com', '?src=pam-mail', ''], ['cat@example.com', '', 'https://massifly.com/feed']];
|
||||
for (const [email, q, ref] of directs) {
|
||||
const j = await jf('/join/' + tok + q, null, '', Object.assign({ 'X-Forwarded-For': '198.51.100.' + (10 + directs.findIndex(d => d[0] === email)) }, ref ? { Referer: ref } : {}));
|
||||
await signIn(email, cookiesOf(j.r), DEV.slice(0, 26) + String(directs.findIndex(d => d[0] === email)).padStart(6, '0'), '198.51.100.' + (10 + directs.findIndex(d => d[0] === email)));
|
||||
}
|
||||
const me2 = (await jf('/api/my/dashboard', null, jar)).b; t('the 3 directs are under the sponsor', (me2.referrals || []).length === 3, 'tok=' + tok + ' referrals=' + JSON.stringify(me2.referrals || []).slice(0, 300));
|
||||
if ((me2.referrals || []).length !== 3) {
|
||||
try { const d = JSON.parse(fs.readFileSync(path.join(DATA, 'accounts.json'), 'utf8')); console.log(JSON.stringify(Object.values(d.byEmail || {}).map(x => [x.email, x.username, x.sponsorRef, x.joinedRef, x.joinedVia]))); } catch (e) { console.log('no accounts.json', fs.readdirSync(DATA).join(',')); }
|
||||
console.log(bad.join('\n')); bye(1);
|
||||
}
|
||||
const br = await chromium.launch(); const ctx = await br.newContext({ viewport: { width: 1280, height: 900 } });
|
||||
await ctx.addCookies(jar.split('; ').map(kv => { const [name, ...v] = kv.split('='); return { name, value: v.join('='), url: B }; }));
|
||||
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
|
||||
const page = await ctx.newPage();
|
||||
await page.goto(B + '/my#line', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(4000);
|
||||
for (const sel of ['#unameSkip', '[data-close]', '.modal .x']) { try { await page.click(sel, { timeout: 800 }); } catch (e) {} }
|
||||
await page.evaluate(() => { document.querySelectorAll('.modal-back,.lgate,.iap-welcome').forEach(m => m.hidden = true); const b = document.querySelector('[data-pane="line"]'); if (b) b.click(); }); await page.waitForTimeout(1500);
|
||||
const rows = await page.$$eval('#rosterWrap table.roster tr', xs => xs.map(x => x.innerText.replace(/\s+/g, ' ')));
|
||||
t('Your line lists the 3 directs', rows.length === 3, rows.length);
|
||||
t('each row shows the email', ['ann@', 'bob@', 'cat@'].every(e => rows.some(r => r.includes(e))), JSON.stringify(rows));
|
||||
t('tagged link with referrer: from mailer.gold/mailergold', rows.some(r => r.includes('ann@') && r.includes('from mailer.gold/mailergold')), JSON.stringify(rows));
|
||||
t('tagged link, no referrer: from pam-mail', rows.some(r => r.includes('bob@') && r.includes('from pam-mail')), JSON.stringify(rows));
|
||||
t('untagged: from massifly.com', rows.some(r => r.includes('cat@') && r.includes('from massifly.com')), JSON.stringify(rows));
|
||||
await (await page.$('#lineRosterCard')).screenshot({ path: 'qa/out/line-origin.png' });
|
||||
await page.fill('#rosterWrap .lst-q', 'mailergold'); await page.waitForTimeout(600);
|
||||
const after = await page.$$eval('#rosterWrap table.roster tr', xs => xs.filter(x => !x.hidden).map(x => x.innerText));
|
||||
t('search by source narrows to 1', after.length === 1 && after[0].includes('ann@'), after.length);
|
||||
const focused = await page.evaluate(() => document.activeElement && document.activeElement.classList.contains('lst-q'));
|
||||
t('the search box keeps focus while typing', focused);
|
||||
// Activity drop-down on a direct in the three-level card
|
||||
const act = await page.$('#lineageWrap [data-act]');
|
||||
if (act) { await act.click(); await page.waitForTimeout(1200); const box = await page.$eval('#lineageWrap .lin-act:not([hidden])', e => e.innerText).catch(() => ''); t('Activity shows Email + Came for a direct', /Email/.test(box) && /Came/.test(box) && /@example\.com/.test(box), box.slice(0, 200)); }
|
||||
else t('three-level card has an Activity button', false, 'none');
|
||||
const lv = await page.$eval('#lineageWrap', e => e.innerText).catch(() => ''); t('three-level card shows the origin line', /from (mailer\.gold\/mailergold|pam-mail|massifly\.com)/.test(lv), lv.slice(0, 200));
|
||||
await br.close();
|
||||
console.log(ok.map(x => ' ok ' + x).join('\n')); if (bad.length) console.log(bad.map(x => ' FAIL ' + x).join('\n'));
|
||||
bye(bad.length ? 1 : 0);
|
||||
@@ -0,0 +1,23 @@
|
||||
// GET /api/admin/member-extra (2026-11-14): the network hub's member lookup reads opt-out, tank and hold state here. Read-only.
|
||||
// Runs against LOCAL (bash qa/run.sh member starts it). Admin = Bearer localtest.
|
||||
const B = process.env.LOCAL || 'http://127.0.0.1:8796';
|
||||
let pass = 0, fail = 0; const ok = (c, m, x) => { if (c) pass++; else { fail++; console.log('[bug] member-extra ' + m + (x ? ' :: ' + x : '')); } };
|
||||
const email = 'mx' + Date.now() + '@example.com'; const ip = '198.51.100.' + (20 + Math.floor(Math.random() * 200));
|
||||
const H = { 'Content-Type': 'application/json', 'X-Forwarded-For': ip, 'User-Agent': 'Mozilla/5.0 MemberExtraQA' };
|
||||
const post = (p, b) => fetch(B + p, { method: 'POST', headers: H, body: JSON.stringify(b) }).then(r => r.json().catch(() => ({})));
|
||||
const get = (q, auth) => fetch(B + '/api/admin/member-extra?email=' + encodeURIComponent(q), { headers: auth ? { Authorization: 'Bearer ' + auth } : {} });
|
||||
try {
|
||||
ok((await get(email)).status === 401, 'no admin header is refused');
|
||||
ok((await get(email, 'wrong')).status === 401, 'a wrong admin password is refused');
|
||||
ok((await get(email, 'localtest')).status === 404, 'an unknown email is 404');
|
||||
const st = await post('/api/auth/email/start', { email, fts: Date.now() - 8000, fage: 8000 });
|
||||
if (st.devCode) await post('/api/auth/email/verify', { email, code: st.devCode });
|
||||
const r = await get(email, 'localtest'); const j = await r.json().catch(() => null);
|
||||
ok(r.status === 200 && j, 'a known account answers', r.status);
|
||||
ok(j && j.tank && typeof j.tank.inTank === 'boolean', 'tank.inTank is a boolean', JSON.stringify(j));
|
||||
ok(j && 'optedOut' in j, 'optedOut is present');
|
||||
const w = await fetch(B + '/api/admin/member-extra?email=' + encodeURIComponent(email), { method: 'POST', headers: { Authorization: 'Bearer localtest' } });
|
||||
ok(w.status !== 200 || !(await w.text()).includes('optedOut'), 'POST is not a route (read-only)');
|
||||
} catch (e) { fail++; console.log('[bug] member-extra crashed :: ' + e.message); }
|
||||
console.log('member-extra: ' + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,219 @@
|
||||
// Network sign-in (InstantAdPay <-> LinkSpin, 2026-11-12) end to end: boots BOTH servers locally on throwaway DATA_DIRs and drives
|
||||
// a real browser across them. Same file in both repos. node qa/networksso.e2e.mjs
|
||||
// The other repo is found at NSSO_PEER_DIR, else ../../linkspin/site or ../../onchain-ad-membership/site from this site dir.
|
||||
// InstantAdPay runs on http://127.0.0.1:<port> and LinkSpin on http://localhost:<port>: two hosts, so the two sites' cookies
|
||||
// stay apart like instantadpay.com and linkspin.app do. No mail key on either copy (no email can leave), JSON stores, devCode.
|
||||
// Proves: IAP -> LinkSpin and LinkSpin -> IAP arrive signed in without a code; the silent check on a sign-in page (signed in on
|
||||
// the other site -> in; not -> the normal sign-in, one bounce only); signed out on the other site -> normal sign-in; a replayed or
|
||||
// expired token is refused; an email not on the receiving site yet gets the email-code form prefilled, nothing created; sign-out
|
||||
// stays per site; bots never bounce; no email-code request is made by any network sign-in.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
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 || !fs.existsSync(path.join(IAP_DIR, 'networksso.js')) || !fs.existsSync(path.join(LS_DIR, 'networksso.js'))) {
|
||||
console.log('SKIP network sign-in e2e: the other repo (with networksso.js) was not found. Set NSSO_PEER_DIR.'); process.exit(0);
|
||||
}
|
||||
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||
const SECRET = crypto.randomBytes(24).toString('hex');
|
||||
const IP = Number(process.env.NSSO_IAP_PORT || 8821), LP = Number(process.env.NSSO_LS_PORT || 8822);
|
||||
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP;
|
||||
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));
|
||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-e2e-'));
|
||||
// a request log on each server (method + path only), so "no email-code request was made" is checked on the server side
|
||||
const SPY = path.join(TMP, 'reqlog.cjs');
|
||||
fs.writeFileSync(SPY, "const http=require('http');const e=http.Server.prototype.emit;http.Server.prototype.emit=function(ev,req){if(ev==='request'&&req&&req.url)process.stdout.write('REQ '+req.method+' '+String(req.url).split('?')[0]+'\\n');return e.apply(this,arguments);};\n");
|
||||
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: '', LS_SYNC_SECRET: '', NODE_OPTIONS: '--require ' + JSON.stringify(SPY).slice(1, -1) }, 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 });
|
||||
const reqs = name => logs[name].split('\n').filter(l => l.startsWith('REQ '));
|
||||
const codeReqs = () => reqs('iap').concat(reqs('ls')).filter(l => /\/api\/auth\/email\/(start|verify)$/.test(l)).length;
|
||||
|
||||
// sign in through the email code over plain HTTP (a separate client: its own IP via x-forwarded-for, its own device)
|
||||
let ipN = 10;
|
||||
async function codeSignIn(base, email) {
|
||||
const h = { 'Content-Type': 'application/json', 'x-forwarded-for': '10.9.0.' + (ipN++), 'User-Agent': UA };
|
||||
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 = (v.headers.getSetCookie ? v.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid='));
|
||||
if (!sid) throw new Error('code sign-in failed on ' + base + ' for ' + email + ': ' + JSON.stringify(sj) + ' / ' + v.status + ' ' + (await v.text()).slice(0, 200));
|
||||
return sid.slice('iap.sid='.length);
|
||||
}
|
||||
const meOf = async (ctx, base) => { const r = await ctx.request.get(base + '/api/me', { headers: { Accept: 'application/json' } }); try { return await r.json(); } catch (e) { return {}; } };
|
||||
async function newCtx(sessions) {
|
||||
const ctx = await browser.newContext({ userAgent: UA });
|
||||
const add = [];
|
||||
if (sessions && sessions.iap) add.push({ name: 'iap.sid', value: sessions.iap, domain: '127.0.0.1', path: '/' });
|
||||
if (sessions && sessions.ls) add.push({ name: 'iap.sid', value: sessions.ls, domain: 'localhost', path: '/' });
|
||||
if (add.length) await ctx.addCookies(add);
|
||||
return ctx;
|
||||
}
|
||||
let browser = null;
|
||||
try {
|
||||
for (let i = 0; i < 60; 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; await sleep(500); }
|
||||
browser = await chromium.launch();
|
||||
// members: A and B have accounts on both sites, C only on InstantAdPay, D only on LinkSpin
|
||||
const A = 'nsso-a@example.com', B = 'nsso-b@example.com', C = 'nsso-c@example.com', D = 'nsso-d@example.com';
|
||||
const aI = await codeSignIn(IAP, A); await codeSignIn(LS, A);
|
||||
const bL = await codeSignIn(LS, B); await codeSignIn(IAP, B);
|
||||
const cI = await codeSignIn(IAP, C);
|
||||
const dL = await codeSignIn(LS, D);
|
||||
const codes0 = codeReqs();
|
||||
|
||||
// 1. IAP -> LinkSpin through the /go hop
|
||||
let ctx = await newCtx({ iap: aI }); let page = await ctx.newPage();
|
||||
await page.goto(IAP + '/go/linkspin?to=' + encodeURIComponent('/ads'));
|
||||
await page.waitForLoadState('domcontentloaded');
|
||||
let me = await meOf(ctx, LS);
|
||||
ok(page.url() === LS + '/ads' && me.signedIn && me.email === A, 'IAP -> LinkSpin: lands on /ads signed in as the same member, no code', page.url() + ' ' + JSON.stringify({ s: me.signedIn, e: me.email }));
|
||||
ok((await meOf(ctx, IAP)).email === A, 'IAP session untouched');
|
||||
// sign-out on LinkSpin stays on LinkSpin, and the silent check does not sign them straight back in
|
||||
await ctx.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||
await page.goto(LS + '/ads'); await page.waitForTimeout(2500);
|
||||
me = await meOf(ctx, LS);
|
||||
ok(!me.signedIn && page.url() === LS + '/ads', 'signed out on LinkSpin: stays signed out there (no automatic sign-in back)', page.url());
|
||||
ok((await meOf(ctx, IAP)).email === A, 'signing out of LinkSpin leaves InstantAdPay signed in');
|
||||
// a deliberate link from IAP still signs them in after the sign-out
|
||||
await page.goto(IAP + '/go/linkspin?to=' + encodeURIComponent('/credits?from=iap&task=refuel#refuel')); await page.waitForLoadState('domcontentloaded');
|
||||
me = await meOf(ctx, LS);
|
||||
ok(me.email === A && page.url() === LS + '/credits?from=iap&task=refuel#refuel', 'after a sign-out, a link from InstantAdPay signs in again and keeps the query and hash', page.url());
|
||||
await ctx.close();
|
||||
|
||||
// 2. LinkSpin -> IAP through the /go hop (dashboard gets ?welcome=1, the step a code sign-in takes for the login ad)
|
||||
ctx = await newCtx({ ls: bL }); page = await ctx.newPage();
|
||||
const navs = []; page.on('framenavigated', f => { if (f === page.mainFrame()) navs.push(f.url()); });
|
||||
await page.goto(LS + '/go/iap?to=' + encodeURIComponent('/my#engine')); await page.waitForLoadState('domcontentloaded');
|
||||
me = await meOf(ctx, IAP);
|
||||
ok(me.signedIn && me.email === B && navs.some(u => u.startsWith(IAP + '/my?welcome=1#engine')), 'LinkSpin -> IAP: lands on /my#engine signed in as the same member, no code', navs.slice(-2).join(' , '));
|
||||
await ctx.close();
|
||||
|
||||
// 3. silent check: signed in on IAP, open a LinkSpin screen directly
|
||||
ctx = await newCtx({ iap: aI }); page = await ctx.newPage();
|
||||
await page.goto(LS + '/links'); await page.waitForURL(u => String(u).startsWith(LS + '/links'), { timeout: 15000 }); await page.waitForTimeout(2500);
|
||||
me = await meOf(ctx, LS);
|
||||
ok(me.email === A && page.url() === LS + '/links', 'silent check: a LinkSpin screen opened directly signs in through IAP', page.url());
|
||||
await ctx.close();
|
||||
// and the other way: signed in on LinkSpin, open the IAP dashboard
|
||||
ctx = await newCtx({ ls: bL }); page = await ctx.newPage();
|
||||
await page.goto(IAP + '/my'); await page.waitForTimeout(4000);
|
||||
me = await meOf(ctx, IAP);
|
||||
ok(me.email === B && page.url().startsWith(IAP + '/my'), 'silent check: the IAP sign-in page signs in through LinkSpin', page.url());
|
||||
await ctx.close();
|
||||
|
||||
// 4. silent check, signed in nowhere: one bounce, then the normal sign-in; no second bounce on reload
|
||||
ctx = await newCtx(); page = await ctx.newPage();
|
||||
const starts = []; page.on('request', r => { if (r.url().includes('/sso/start')) starts.push(r.url()); });
|
||||
await page.goto(LS + '/ads'); await page.waitForTimeout(3000);
|
||||
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)');
|
||||
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();
|
||||
|
||||
// 5. expired / absent session on the provider: signed out on IAP, the /go link is a plain link and LinkSpin asks for the code
|
||||
const aI2 = await codeSignIn(IAP, A);
|
||||
ctx = await newCtx({ iap: aI2 }); page = await ctx.newPage();
|
||||
await ctx.request.post(IAP + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||
await page.goto(IAP + '/go/linkspin?to=%2Fads'); await page.waitForTimeout(2500);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads', 'signed out on IAP: /go/linkspin is a plain link, LinkSpin shows its sign-in', page.url());
|
||||
await ctx.close();
|
||||
// a session that expired on the provider: the check answers none
|
||||
ctx = await newCtx({ iap: 'f'.repeat(64) }); page = await ctx.newPage();
|
||||
await page.goto(LS + '/sso/start?mode=go&to=%2Fads'); await page.waitForTimeout(1500);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && page.url().startsWith(IAP + '/my'), 'an expired IAP session on a deliberate tap: IAP asks for its own sign-in first (2026-11-14)', page.url());
|
||||
ok((await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), 'IAP remembers the unfinished trip while the member signs in');
|
||||
await ctx.close();
|
||||
|
||||
// 6. not on the receiving site yet: C (IAP only) going to LinkSpin, D (LinkSpin only) going to IAP
|
||||
ctx = await newCtx({ iap: cI }); page = await ctx.newPage();
|
||||
await page.goto(IAP + '/go/linkspin?to=%2Fads'); await page.waitForSelector('#siEmail', { timeout: 10000 }); await page.waitForTimeout(1500);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && (await page.inputValue('#siEmail')) === C && (await page.locator('#nssoNote').count()) === 1, 'IAP member not on LinkSpin yet: LinkSpin sign-in with the email filled in, nothing signed', await page.inputValue('#siEmail'));
|
||||
ok(!fs.readFileSync(path.join(TMP, 'ls', 'accounts.json'), 'utf8').includes(C), 'no LinkSpin account was created by the network sign-in');
|
||||
await ctx.close();
|
||||
ctx = await newCtx({ ls: dL }); page = await ctx.newPage();
|
||||
await page.goto(LS + '/go/iap?to=%2Fmy'); await page.waitForTimeout(4000);
|
||||
ok(!(await meOf(ctx, IAP)).signedIn && page.url().startsWith(IAP + '/my') && (await page.inputValue('#mcEmail').catch(() => '')) === D, 'LinkSpin member not on IAP yet: IAP sign-in with the email filled in, nothing signed', page.url() + ' ' + (await page.inputValue('#mcEmail').catch(() => '?')));
|
||||
await ctx.close();
|
||||
|
||||
// 7. replay: walk the hops by hand, spend the token once, then try it again with the state cookie put back
|
||||
const aI3 = await codeSignIn(IAP, A);
|
||||
ctx = await newCtx({ iap: aI3 });
|
||||
const hop = async url => { const r = await ctx.request.get(url, { maxRedirects: 0, headers: { 'User-Agent': UA, 'sec-fetch-dest': 'document' } }); return r.headers()['location'] || ''; };
|
||||
let loc = await hop(LS + '/sso/start?mode=go&to=%2Fads');
|
||||
const st = (await ctx.cookies(LS)).find(c => c.name === 'nsso.st');
|
||||
loc = await hop(loc.startsWith('http') ? loc : LS + loc);
|
||||
ok(/^http:\/\/localhost:\d+\/sso\/in\?t=v1\./.test(loc), 'provider minted a token for LinkSpin', loc.slice(0, 60));
|
||||
const tokUrl = loc;
|
||||
let land = await hop(tokUrl);
|
||||
ok(land === '/ads' && (await meOf(ctx, LS)).email === A, 'first use signs in');
|
||||
await ctx.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||
await ctx.addCookies([{ name: 'nsso.st', value: st.value, domain: 'localhost', path: '/' }]);
|
||||
land = await hop(tokUrl);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && /token already used/.test(logs.ls), 'the same token again is refused (replay), even with the state cookie put back', land);
|
||||
// a token from a different browser (state cookie missing) is refused: login CSRF
|
||||
const ctx2 = await newCtx({ iap: aI3 });
|
||||
const r2 = await ctx2.request.get(LS + '/sso/start?mode=go&to=%2Fads', { maxRedirects: 0, headers: { 'sec-fetch-dest': 'document' } });
|
||||
const l2 = await ctx2.request.get(r2.headers()['location'], { maxRedirects: 0 });
|
||||
const other = await newCtx(); const r3 = await other.request.get(l2.headers()['location'], { maxRedirects: 0 });
|
||||
ok(!(await meOf(other, LS)).signedIn && /refused: state/.test(logs.ls), 'a token opened in another browser (no matching state) is refused', r3.headers()['location']);
|
||||
await ctx2.close(); await other.close();
|
||||
// an expired token (minted by hand with a past clock) is refused
|
||||
const require = createRequire(import.meta.url); process.env.NETWORK_SSO_SECRET = SECRET;
|
||||
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||
const st2 = crypto.randomBytes(16).toString('hex');
|
||||
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]);
|
||||
const old = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads', now: Date.now() - 120000 });
|
||||
await hop(LS + '/sso/in?t=' + old);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && /refused: expired/.test(logs.ls), 'an expired token is refused');
|
||||
const forged = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads' }).replace(/.$/, c => c === 'A' ? 'B' : 'A');
|
||||
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]); await hop(LS + '/sso/in?t=' + forged);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && /refused: signature/.test(logs.ls), 'a tampered token is refused');
|
||||
// open redirect: an off-site path never leaves the site
|
||||
const ev = await hop(IAP + '/go/linkspin?to=' + encodeURIComponent('https://evil.example/x'));
|
||||
ok(ev === LS + '/sso/start?mode=go&to=%2F', '/go with an off-site path stays on the network', ev);
|
||||
const ev2 = await ctx.request.get(LS + '/sso/in?none=1&to=' + encodeURIComponent('//evil.example'), { maxRedirects: 0 });
|
||||
ok(ev2.headers()['location'] === '/ads', '/sso/in never redirects off the site', ev2.headers()['location']);
|
||||
await ctx.close();
|
||||
|
||||
// 8. bots and API calls never bounce
|
||||
const bot = await fetch(LS + '/sso/start?to=%2Fads', { redirect: 'manual', headers: { 'User-Agent': 'Googlebot/2.1 (+http://www.google.com/bot.html)' } });
|
||||
ok(bot.headers.get('location') === '/ads' && !(bot.headers.getSetCookie ? bot.headers.getSetCookie() : []).length, 'a crawler on /sso/start goes straight to the page');
|
||||
const bs = await (await fetch(IAP + '/api/sso/status', { headers: { 'User-Agent': 'Googlebot/2.1' } })).json();
|
||||
ok(bs.check === false, 'a crawler is never told to check');
|
||||
|
||||
// 9. no email-code request was made by any network sign-in (only the setup code sign-ins above)
|
||||
const total = codeReqs();
|
||||
ok(total === codes0 + 4, 'no email-code request made by any network sign-in (server request log: only the 2 later setup sign-ins, start + verify each)', 'before ' + codes0 + ', after ' + total);
|
||||
ok(!/sendCode|sendgrid/i.test(logs.iap + logs.ls), 'no mail send attempted on either server');
|
||||
ok(/network-sso signed in from InstantAdPay n\*\*\*@example\.com/.test(logs.ls) && /network-sso signed in from LinkSpin n\*\*\*@example\.com/.test(logs.iap), 'successes logged with the email masked');
|
||||
ok(!logs.iap.includes(SECRET) && !logs.ls.includes(SECRET) && !/nsso-a@example\.com/.test((logs.iap + logs.ls).split('\n').filter(l => l.includes('network-sso')).join('\n')), 'no secret and no full email in the network sign-in log lines');
|
||||
} catch (e) { console.log('FAIL exception', e && e.stack || e); fails++; }
|
||||
finally {
|
||||
try { if (browser) await browser.close(); } catch (e) {}
|
||||
try { srvI.kill(); } catch (e) {} try { srvL.kill(); } 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 (network-sso / errors)\n' + logs[k].split('\n').filter(l => /network-sso|error|Error/.test(l)).slice(-25).join('\n')); }
|
||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,126 @@
|
||||
// Network sign-in (InstantAdPay <-> LinkSpin, 2026-11-12): unit test of networksso.js. Same file in both repos. node qa/networksso.test.cjs
|
||||
// Token sign/verify, expiry, clock skew, tamper, wrong audience, state binding, replay, the secret switch, open redirects,
|
||||
// bots, and the route handler with fake requests (no server, no network, throwaway DATA_DIR).
|
||||
'use strict';
|
||||
const fs = require('fs'), os = require('os'), path = require('path'), crypto = require('crypto');
|
||||
process.env.NETWORK_SSO_SECRET = 'u'.repeat(48);
|
||||
const N = require('../networksso.js');
|
||||
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-unit-'));
|
||||
const st = crypto.randomBytes(16).toString('hex');
|
||||
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
|
||||
(async () => {
|
||||
const sessions = { 'tok-a': { email: 'a@example.com' } };
|
||||
const accounts = new Set(['a@example.com']);
|
||||
const signedIn = [];
|
||||
N.init({ self: 'iap', peer: 'linkspin', peerBase: () => 'https://ls.example', isProd: true, dataDir: DATA, db: null, defaultPath: '/my',
|
||||
member: async req => sessions[(/sid=([^;]+)/.exec(req.headers.cookie || '') || [])[1]] || null,
|
||||
accept: async e => accounts.has(e) ? { ok: true } : { fallback: 'no account here yet' },
|
||||
signIn: async e => { signedIn.push(e); return 'iap.sid=new; Path=/; HttpOnly'; },
|
||||
landing: to => to, signinPath: to => '/my' });
|
||||
|
||||
// ---- tokens ----
|
||||
const t = N.mint({ iss: 'linkspin', aud: 'iap', email: 'A@Example.com', st, to: '/my#buy' });
|
||||
let v = N.verify(t, { iss: 'linkspin', aud: 'iap', st });
|
||||
ok(v.ok && v.email === 'a@example.com' && v.to === '/my#buy', 'round trip: email (lower-cased) and path come back', JSON.stringify(v));
|
||||
ok(/^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(t), 'token format v1.<payload>.<hmac>');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'linkspin', st }).error === 'audience', 'wrong audience refused');
|
||||
ok(N.verify(t, { iss: 'iap', aud: 'iap', st }).error === 'audience', 'wrong issuer refused');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st, now: Date.now() + 61000 }).error === 'expired', 'expired after 60 s');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st, now: Date.now() + 55000 }).ok, 'still good at 55 s');
|
||||
const fut = N.mint({ iss: 'linkspin', aud: 'iap', email: 'a@example.com', st, to: '/', now: Date.now() + 120000 });
|
||||
ok(N.verify(fut, { iss: 'linkspin', aud: 'iap', st }).error === 'expired', 'issued too far in the future refused');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st: crypto.randomBytes(16).toString('hex') }).error === 'state', 'state from another browser refused');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st: '' }).error === 'state', 'missing state cookie refused');
|
||||
const [, body, mac] = t.split('.');
|
||||
const pl = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString()); pl.email = 'evil@example.com';
|
||||
ok(N.verify('v1.' + b64u(JSON.stringify(pl)) + '.' + mac, { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'payload tampered (email swapped) refused');
|
||||
ok(N.verify('v1.' + body + '.' + (mac[0] === 'A' ? 'B' : 'A') + mac.slice(1), { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'signature tampered refused');
|
||||
const longer = JSON.parse(JSON.stringify(pl)); longer.email = 'a@example.com'; longer.exp = longer.iat + 3600000;
|
||||
const forged = 'v1.' + b64u(JSON.stringify(longer)) + '.' + b64u(crypto.createHmac('sha256', process.env.NETWORK_SSO_SECRET).update('nsso.v1.' + b64u(JSON.stringify(longer))).digest());
|
||||
ok(N.verify(forged, { iss: 'linkspin', aud: 'iap', st }).error === 'expired', 'a validly signed token with a life over 60 s is refused');
|
||||
ok(N.verify('garbage', { iss: 'linkspin', aud: 'iap', st }).error === 'malformed' && N.verify('', { iss: 'linkspin', aud: 'iap', st }).error === 'malformed', 'garbage refused');
|
||||
process.env.NETWORK_SSO_SECRET = 'w'.repeat(48);
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'another secret refused');
|
||||
process.env.NETWORK_SSO_SECRET = 'short';
|
||||
ok(!N.enabled() && N.verify(t, { iss: 'linkspin', aud: 'iap', st }).error === 'off', 'secret under 32 characters = switched off');
|
||||
process.env.NETWORK_SSO_SECRET = 'u'.repeat(48);
|
||||
|
||||
// ---- replay ----
|
||||
ok(await N.spend(v.n, v.exp) === true, 'first use of a nonce is spent');
|
||||
ok(await N.spend(v.n, v.exp) === false, 'second use of the same nonce refused (replay)');
|
||||
ok(JSON.parse(fs.readFileSync(path.join(DATA, 'network-sso-nonces.json'), 'utf8'))[v.n] > 0, 'spent nonce kept on disk (survives a restart inside the window)');
|
||||
|
||||
// ---- open redirects ----
|
||||
const bad = ['https://evil.example/x', '//evil.example/x', '/\\evil.example', '\\\\evil.example', 'javascript:alert(1)', '/x\r\nSet-Cookie: a=b', ' /my', '/my\t', 'http:/evil.example', '/' + 'a'.repeat(700), '', null];
|
||||
ok(bad.every(b => N.safePath(b, '/my') === '/my'), 'off-site, protocol-relative, backslash, script, header-injection and over-long paths fall back to the default', bad.map(b => N.safePath(b, '/my')).filter(x => x !== '/my').join(' | '));
|
||||
ok(N.safePath('/credits?from=iap&task=refuel#refuel') === '/credits?from=iap&task=refuel#refuel' && N.safePath('/my#buy') === '/my#buy', 'same-site paths with query and hash pass');
|
||||
ok(N.safePath('/%2F%2Fevil.example') === '/%2F%2Fevil.example', 'an encoded // stays a path on this site');
|
||||
const t2 = N.mint({ iss: 'linkspin', aud: 'iap', email: 'a@example.com', st, to: 'https://evil.example/' });
|
||||
ok(N.verify(t2, { iss: 'linkspin', aud: 'iap', st }).to === '/', 'a token carrying an off-site path lands on /');
|
||||
|
||||
// ---- bots ----
|
||||
const R = (url, cookie, ua, extra) => ({ method: 'GET', url, headers: Object.assign({ cookie: cookie || '', 'user-agent': ua === undefined ? 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130 Safari/537.36' : ua }, extra || {}) });
|
||||
ok(N.isBot(R('/', '', 'Googlebot/2.1')) && N.isBot(R('/', '', 'facebookexternalhit/1.1')) && N.isBot(R('/', '', '')) && N.isBot(R('/', '', 'Mozilla/5.0 HeadlessChrome/120')) && !N.isBot(R('/')), 'bots, previews, headless and empty agents are bots; a browser is not');
|
||||
|
||||
// ---- the handler ----
|
||||
const call = async req => { let code = 0, h = {}, body = ''; const res = { writeHead: (c, hh) => { code = c; h = hh || {}; }, end: b => { body = b || ''; } };
|
||||
const handled = await N.handle(req, res, new URL(req.url, 'http://x')); const set = [].concat(h['Set-Cookie'] || []); return { handled, code, loc: h.Location, set, body }; };
|
||||
let r = await call(R('/go/linkspin?to=/ads'));
|
||||
ok(r.code === 302 && r.loc === 'https://ls.example/ads', '/go signed out: a plain link to the other site');
|
||||
r = await call(R('/go/linkspin?to=//evil.example', 'sid=tok-a'));
|
||||
ok(r.loc === 'https://ls.example/sso/start?mode=go&to=%2F', '/go never forwards an off-site path', r.loc);
|
||||
r = await call(R('/go/linkspin?to=/ads%3Fx%3D1', 'sid=tok-a'));
|
||||
ok(r.loc === 'https://ls.example/sso/start?mode=go&to=%2Fads%3Fx%3D1', '/go signed in: through the other site\'s /sso/start', r.loc);
|
||||
r = await call(R('/sso/start?to=/my', '', 'Googlebot/2.1'));
|
||||
ok(r.loc === '/my' && !r.set.length, 'bot on /sso/start: no bounce, no cookies');
|
||||
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');
|
||||
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);
|
||||
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'));
|
||||
ok(r.loc === 'https://ls.example/sso/in?none=1&to=%2Fads', 'provider, signed out: none');
|
||||
r = await call(R('/sso/check?st=nothex&to=/ads', 'sid=tok-a'));
|
||||
ok(r.loc.includes('none=1'), 'provider: a malformed state gets none, never a token');
|
||||
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');
|
||||
// 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));
|
||||
ok(r.loc === '/my#buy' && r.set.includes('iap.sid=new; Path=/; HttpOnly') && signedIn.length === 1, 'receiver: valid token -> session cookie, redirect to the path');
|
||||
const once = mk('a@example.com', '/my');
|
||||
r = await call(R('/sso/in?t=' + once, 'nsso.st=' + st)); r = await call(R('/sso/in?t=' + once, 'nsso.st=' + st));
|
||||
ok(signedIn.length === 2 && !r.set.some(c => c.startsWith('iap.sid=')), 'receiver: the same token twice signs in once (replay refused)');
|
||||
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my'), 'nsso.st=' + crypto.randomBytes(16).toString('hex')));
|
||||
ok(signedIn.length === 2 && r.loc === '/my', 'receiver: a token pushed into another browser (login CSRF) is refused');
|
||||
r = await call(R('/sso/in?t=' + issued, 'nsso.st=' + st));
|
||||
ok(signedIn.length === 2, 'receiver: a token minted FOR the other site is refused here');
|
||||
r = await call(R('/sso/in?t=' + mk('new@example.com', '/my'), 'nsso.st=' + st));
|
||||
ok(signedIn.length === 2 && r.loc === '/my' && r.set.some(c => /^nsso\.hint=new%40example\.com;.*HttpOnly/.test(c)), 'receiver: not a member here yet -> normal sign-in with the email kept for the form, nothing created');
|
||||
r = await call(R('/sso/in?none=1&to=https://evil.example', 'nsso.st=' + st));
|
||||
ok(r.loc === '/my' && r.set.some(c => /^nsso\.st=;/.test(c)), 'receiver: none -> the sign-in page, never an off-site path');
|
||||
r = await call(R('/api/sso/status', 'nsso.hint=new%40example.com; nsso.tried=1'));
|
||||
let j = JSON.parse(r.body); ok(j.hint === 'new@example.com' && j.check === false && r.set.some(c => /^nsso\.hint=;/.test(c)), '/api/sso/status hands the hint over once and clears it');
|
||||
j = JSON.parse((await call(R('/api/sso/status'))).body); ok(j.check === true && j.peer === 'LinkSpin', '/api/sso/status: signed out, fresh browser -> check');
|
||||
j = JSON.parse((await call(R('/api/sso/status', 'sid=tok-a'))).body); ok(j.check === false, '/api/sso/status: signed in -> no check');
|
||||
j = JSON.parse((await call(R('/api/sso/status', '', 'Googlebot/2.1'))).body); ok(j.check === false, '/api/sso/status: bot -> no check');
|
||||
process.env.NETWORK_SSO_SECRET = '';
|
||||
r = await call(R('/go/linkspin?to=/ads', 'sid=tok-a')); ok(r.loc === 'https://ls.example/ads', 'secret not set: /go is a plain link');
|
||||
j = JSON.parse((await call(R('/api/sso/status'))).body); ok(j.check === false, 'secret not set: no silent check');
|
||||
ok(N.offCookie().startsWith('nsso.off=1;') && /Max-Age=43200/.test(N.offCookie()), 'sign-out cookie pauses the silent check 12 hours');
|
||||
ok(!(await call({ method: 'POST', url: '/sso/in', headers: {} })).handled, 'non-GET requests are not handled');
|
||||
})().catch(e => { console.log('FAIL exception', e && e.stack || e); fails++; }).finally(() => {
|
||||
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exitCode = fails ? 1 : 0;
|
||||
});
|
||||
@@ -2,10 +2,12 @@
|
||||
# InstantAdPay QA harness runner. From the site dir:
|
||||
# bash qa/run.sh public # live public pages only (no local server)
|
||||
# bash qa/run.sh member # local copy: member + admin walk
|
||||
# bash qa/run.sh sso # network sign-in InstantAdPay <-> LinkSpin: unit + both servers end to end (NSSO_PEER_DIR = the other repo's site dir if not side by side; also runs in member)
|
||||
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
||||
# bash qa/run.sh all # public + member + earn
|
||||
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
|
||||
# bash qa/run.sh walletnudge # game wallet push (any linked wallet, activated or not) + no-wallet nudge copy against a mock game (also runs in member)
|
||||
# bash qa/run.sh draft # 5xYourTeam The Draft partner routes: pool / adopt / release / status rules on the real tank.js (mocked clock, fake hub) + the signed HTTP routes on a local copy (also runs in member)
|
||||
# bash qa/run.sh tankhold # holding-tank activation hold, 24-hour safety net (mocked clock) and LinkSpin alignment: unit + local copy (also runs in member)
|
||||
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests and the two-server e2e (local IAP + local LinkSpin, throwaway data)
|
||||
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
|
||||
@@ -61,19 +63,29 @@ syntax_gate
|
||||
if [ "$MODE" = "public" ]; then
|
||||
node qa/walk.mjs public || status=1
|
||||
node qa/chatbot-sync.mjs || status=1
|
||||
elif [ "$MODE" = "sso" ]; then
|
||||
node qa/networksso.test.cjs || status=1
|
||||
node qa/networksso.e2e.mjs || status=1
|
||||
elif [ "$MODE" = "member" ]; then
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||
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/tank-hold.mjs || status=1
|
||||
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
|
||||
elif [ "$MODE" = "draft" ]; then
|
||||
node qa/draft-partner.test.mjs || status=1
|
||||
elif [ "$MODE" = "theme" ]; then
|
||||
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/theme-contrast.mjs || status=1; }; stop_local 8797
|
||||
elif [ "$MODE" = "policy" ]; then
|
||||
node qa/profile-policy.test.cjs || status=1
|
||||
elif [ "$MODE" = "bixpay" ]; then
|
||||
node qa/bixpay.test.cjs || status=1
|
||||
elif [ "$MODE" = "hub" ]; then
|
||||
node qa/hubsync.test.cjs || status=1 # needs the network-hub checkout beside this repo (HUB_DIR to override)
|
||||
elif [ "$MODE" = "walletnudge" ]; then
|
||||
node qa/walletnudge.test.cjs || status=1
|
||||
elif [ "$MODE" = "tankhold" ]; then
|
||||
|
||||
+40
-26
@@ -5,7 +5,9 @@
|
||||
// Roland by default), order -> fulfil -> ownership (permanent, no expiry), the bundle grants all three, no double charge (owned hero
|
||||
// refused, a waiting order for an owned hero cancelled, each tx once, one package one order), packages bought before the order or too
|
||||
// small, a pass order and a hero order side by side, settings (price 0 = free for everyone, bundle list), the hand-off claim (heroes,
|
||||
// heroBundle, heroSale, heroBundleCap only when set), comp / revoke, stats, and that hero sales never touch the pass records. Exit 1 on failure.
|
||||
// heroBundle, heroSale, heroBundleCap only when set), comp / revoke, stats, and that hero sales never touch the pass records.
|
||||
// 2026-11-14 (Marty approved): Kestrel is free in the game at level 20, so she is never sold here (no buy, never in a bundle, a waiting
|
||||
// Kestrel order is cancelled unpaid); a member who bought her before keeps her. Exit 1 on failure.
|
||||
'use strict';
|
||||
const fs = require('fs'); const os = require('os'); const path = require('path');
|
||||
const gp = require('../gamepass');
|
||||
@@ -27,33 +29,43 @@ const pkg = (email, cents, at, tx) => gp.onEvent({ type: 'Purchase', priceCents:
|
||||
let r = gp.buyHero('m@x.com', T0, 'kestrel'); ok(r.error === 'Bonus heroes are not on sale yet.', 'heroSales off: a member is refused', JSON.stringify(r));
|
||||
ok(![...orders.values()].length, 'a refused buy opens no order');
|
||||
let v = gp.view('m@x.com', T0).heroes; ok(v.show === false && v.items.every(i => !i.open), 'heroSales off: the member card hides the heroes', JSON.stringify(v.items.map(i => i.open)));
|
||||
v = gp.view('admin@x.com', T0, { preview: true }).heroes; ok(v.show && v.preview && v.items.every(i => i.open) && v.bundle.open && v.items.map(i => i.package).join() === '20,20,20,20' && v.bundle.package === 50, 'the admin preview: every hero open, $20 packages, the bundle on the $50 package', JSON.stringify(v));
|
||||
v = gp.view('admin@x.com', T0, { preview: true }).heroes; ok(v.show && v.preview && v.items.filter(i => !i.freeAt).every(i => i.open) && v.items.find(i => i.key === 'kestrel').freeAt === 20 && !v.items.find(i => i.key === 'kestrel').open && v.bundle.open && v.items.map(i => i.package).join() === '20,20,20,20' && v.bundle.package === 50, 'the admin preview: every sold hero open (Kestrel shown free at 20, not open), $20 packages, the bundle on the $50 package', JSON.stringify(v));
|
||||
r = gp.buyHero('admin@x.com', T0, 'roland', { preview: true }); ok(r.needPay && r.price === 2000 && r.package === 20 && /Roland the Paladin joins you in Shards of Valor/.test(r.message) && !/—/.test(r.message), 'the admin test opens a $20 order', JSON.stringify(r));
|
||||
r = gp.cancelHeroOrder('admin@x.com', 'roland'); ok(r.ok && r.order, 'the admin cancels the test order');
|
||||
ok(!(await pkg('admin@x.com', 2000, T0 + 1000)), 'a cancelled order is never fulfilled later');
|
||||
|
||||
// 2. on sale: one hero, order then a fresh package
|
||||
// 2. on sale: Kestrel is never sold (free at 20 in the game); a past Kestrel buyer keeps her; a waiting Kestrel order is cancelled unpaid
|
||||
SC.heroSales = '1';
|
||||
r = gp.buyHero('m@x.com', T0, 'kestrel'); ok(r.needPay && r.payUrl.includes('#buy') && r.usd === 20, 'on sale: buy opens a waiting order, no charge', JSON.stringify(r));
|
||||
const r2 = gp.buyHero('m@x.com', T0 + 10, 'kestrel'); ok(r2.reused && r2.order === r.order, 'a second click reuses the same order');
|
||||
r = gp.buyHero('m@x.com', T0, 'kestrel'); ok(/Kestrel the Archer is free for every player at level 20 in Shards of Valor, so she is not for sale\./.test(r.error || '') && !/\u2014/.test(r.error), 'Kestrel is refused: free at level 20', JSON.stringify(r));
|
||||
ok(![...orders.values()].some(o => o.hero === 'kestrel' && o.status === 'waiting'), 'no Kestrel order opened');
|
||||
passes.set('k@x.com', { until: 0, bought: [], heroes: { kestrel: { ts: T0 - 86400000, via: 'package', tx: '0xoldkes', cents: 2000, usd: 20 } } });
|
||||
ok(gp.heroesOwned('k@x.com').owned.join() === 'kestrel' && gp.heroClaim('k@x.com').heroes.join() === 'kestrel', 'a member who bought Kestrel before keeps her (the hand-off still says so)');
|
||||
v = gp.view('k@x.com', T0).heroes; ok(v.items.find(i => i.key === 'kestrel').owned && v.show, 'her card says Yours for good');
|
||||
orders.set('hero-oldkes', { status: 'waiting', kind: 'hero', hero: 'kestrel', email: 'w@x.com', ts: T0 });
|
||||
ok(!(await pkg('w@x.com', 2000, T0 + 1000)), 'a Kestrel order from before the change is never fulfilled');
|
||||
ok(orders.get('hero-oldkes').status === 'cancelled' && /free at level 20/.test(orders.get('hero-oldkes').why || ''), 'and it is cancelled unpaid', JSON.stringify(orders.get('hero-oldkes')));
|
||||
ok(gp.heroesOwned('w@x.com').owned.length === 0, 'nothing granted for it');
|
||||
// one sold hero: order then a fresh package
|
||||
r = gp.buyHero('m@x.com', T0, 'roland'); ok(r.needPay && r.payUrl.includes('#buy') && r.usd === 20, 'on sale: buy opens a waiting order, no charge', JSON.stringify(r));
|
||||
const r2 = gp.buyHero('m@x.com', T0 + 10, 'roland'); ok(r2.reused && r2.order === r.order, 'a second click reuses the same order');
|
||||
ok(!(await pkg('m@x.com', 2000, T0 - 60000)), 'a package bought before the order does not fulfil it');
|
||||
ok(!(await pkg('m@x.com', 1000, T0 + 1000)), 'a $10 package is too small');
|
||||
let ev = await pkg('m@x.com', 2000, T0 + 2000, '0xkes1');
|
||||
ok(ev && ev.hero === 'kestrel' && ev.heroes.join() === 'kestrel', 'a fresh $20 package fulfils it', JSON.stringify(ev));
|
||||
ok(gp.heroesOwned('m@x.com').owned.join() === 'kestrel', 'Kestrel is owned');
|
||||
ok(!(await pkg('m@x.com', 2000, T0 + 3000, '0xkes1')), 'the same tx never counts twice');
|
||||
r = gp.buyHero('m@x.com', T0 + 4000, 'kestrel'); ok(/already have Kestrel/.test(r.error || ''), 'no double charge: an owned hero is refused', JSON.stringify(r));
|
||||
const rec = passes.get('m@x.com'); ok(rec.heroes.kestrel.tx === '0xkes1' && rec.heroes.kestrel.via === 'package' && rec.heroes.kestrel.usd === 20 && !rec.heroes.kestrel.until && !(rec.bought || []).length && !rec.tiers, 'stored for good (no expiry), never as a pass sale', JSON.stringify(rec));
|
||||
let ev = await pkg('m@x.com', 2000, T0 + 2000, '0xrol1');
|
||||
ok(ev && ev.hero === 'roland' && ev.heroes.join() === 'roland', 'a fresh $20 package fulfils it', JSON.stringify(ev));
|
||||
ok(gp.heroesOwned('m@x.com').owned.join() === 'roland', 'Roland is owned');
|
||||
ok(!(await pkg('m@x.com', 2000, T0 + 3000, '0xrol1')), 'the same tx never counts twice');
|
||||
r = gp.buyHero('m@x.com', T0 + 4000, 'roland'); ok(/already have Roland/.test(r.error || ''), 'no double charge: an owned hero is refused', JSON.stringify(r));
|
||||
const rec = passes.get('m@x.com'); ok(rec.heroes.roland.tx === '0xrol1' && rec.heroes.roland.via === 'package' && rec.heroes.roland.usd === 20 && !rec.heroes.roland.until && !(rec.bought || []).length && !rec.tiers, 'stored for good (no expiry), never as a pass sale', JSON.stringify(rec));
|
||||
ok(gp.flag('m@x.com', T0).active === false, 'a hero is not a Game Pass');
|
||||
ok(gp.heroesOwned('m@x.com').owned.includes('kestrel') && gp.heroesOwned('m@x.com', T0 + 3650 * 86400000).owned.includes('kestrel'), 'owned years later too');
|
||||
ok(gp.heroesOwned('m@x.com').owned.includes('roland') && gp.heroesOwned('m@x.com', T0 + 3650 * 86400000).owned.includes('roland'), 'owned years later too');
|
||||
|
||||
// 3. the bundle: all three, and its refusals
|
||||
r = gp.buyHero('m@x.com', T0, 'bundle'); ok(r.needPay && r.price === 5000 && r.package === 50 && /Valda the Barbarian, Morag the Druid, Roland the Paladin/.test(r.message), 'Kestrel owner may buy the bundle (Kestrel is not in it)', JSON.stringify(r));
|
||||
ok(!(await pkg('m@x.com', 2000, T0 + 5000)), 'a $20 package does not pay the $50 bundle');
|
||||
ev = await pkg('m@x.com', 5000, T0 + 6000);
|
||||
r = gp.buyHero('k@x.com', T0, 'bundle'); ok(r.needPay && r.price === 5000 && r.package === 50 && /Valda the Barbarian, Morag the Druid, Roland the Paladin/.test(r.message), 'a Kestrel owner may buy the bundle (Kestrel is not in it)', JSON.stringify(r));
|
||||
ok(!(await pkg('k@x.com', 2000, T0 + 5000)), 'a $20 package does not pay the $50 bundle');
|
||||
ev = await pkg('k@x.com', 5000, T0 + 6000);
|
||||
ok(ev && ev.hero === 'bundle' && ev.heroes.join() === 'valda,morag,roland', 'a $50 package fulfils the bundle: all three', JSON.stringify(ev));
|
||||
ok(gp.heroesOwned('m@x.com').owned.join() === 'kestrel,valda,morag,roland' && gp.heroesOwned('m@x.com').bundle, 'four owned, bundle flag set');
|
||||
r = gp.buyHero('m@x.com', T0, 'bundle'); ok(/already have/.test(r.error || ''), 'the bundle twice: refused');
|
||||
ok(gp.heroesOwned('k@x.com').owned.join() === 'kestrel,valda,morag,roland' && gp.heroesOwned('k@x.com').bundle, 'four owned, bundle flag set');
|
||||
r = gp.buyHero('k@x.com', T0, 'bundle'); ok(/already have/.test(r.error || ''), 'the bundle twice: refused');
|
||||
r = gp.buyHero('n@x.com', T0, 'morag'); await pkg('n@x.com', 2000, T0 + 100); r = gp.buyHero('n@x.com', T0 + 200, 'bundle');
|
||||
ok(/already have Morag the Druid, so the bundle is not for you/.test(r.error || ''), 'a member who owns one bundle hero is sent to buy the rest one at a time', JSON.stringify(r));
|
||||
|
||||
@@ -68,22 +80,24 @@ const pkg = (email, cents, at, tx) => gp.onEvent({ type: 'Purchase', priceCents:
|
||||
ok(e1 && e1.hero === 'roland' && e2 && e2.tier === 'weekly' && gp.flag('p@x.com', T0 + 3000).active, 'a $20 package pays the hero, a $5 package the weekly pass', JSON.stringify({ e1, e2 }));
|
||||
|
||||
// 5. settings: price 0 = free for every account; bundle list
|
||||
SC.heroPriceKestrelCents = '0';
|
||||
ok(gp.heroesOwned('nobody@x.com').owned.join() === 'kestrel', 'Kestrel priced 0: owned by every account');
|
||||
r = gp.buyHero('q@x.com', T0, 'kestrel'); ok(/free for everyone/.test(r.error || ''), 'a free hero is never sold');
|
||||
let claim = gp.heroClaim('nobody@x.com'); ok(claim.heroes.join() === 'kestrel' && claim.heroSale.free.join() === 'kestrel' && claim.heroBundle === false && !('heroBundleCap' in claim), 'the hand-off says Kestrel is free (the game opens her for guests too)', JSON.stringify(claim));
|
||||
delete SC.heroPriceKestrelCents; SC.heroBundleHeroes = 'kestrel,valda,morag';
|
||||
ok(gp.cfg().heroes.bundle.heroes.join() === 'kestrel,valda,morag', 'the bundle list is a setting');
|
||||
SC.heroPriceRolandCents = '0';
|
||||
ok(gp.heroesOwned('nobody@x.com').owned.join() === 'roland', 'Roland priced 0: owned by every account');
|
||||
r = gp.buyHero('q@x.com', T0, 'roland'); ok(/free for everyone/.test(r.error || ''), 'a free hero is never sold');
|
||||
let claim = gp.heroClaim('nobody@x.com'); ok(claim.heroes.join() === 'roland' && claim.heroSale.free.join() === 'roland' && claim.heroBundle === false && !('heroBundleCap' in claim), 'the hand-off says Roland is free (the game opens him for guests too)', JSON.stringify(claim));
|
||||
delete SC.heroPriceRolandCents; SC.heroBundleHeroes = 'valda,morag';
|
||||
ok(gp.cfg().heroes.bundle.heroes.join() === 'valda,morag', 'the bundle list is a setting');
|
||||
SC.heroBundleHeroes = 'kestrel,valda,morag';
|
||||
ok(gp.cfg().heroes.bundle.heroes.join() === 'valda,morag', 'a bundle setting naming Kestrel drops her (free at 20, never sold)');
|
||||
delete SC.heroBundleHeroes;
|
||||
|
||||
// 6. the hand-off claim and the bundle cap (unset by default; only for bundle owners once set)
|
||||
claim = gp.heroClaim('m@x.com'); ok(claim.heroes.join() === 'kestrel,valda,morag,roland' && claim.heroBundle === true && !('heroBundleCap' in claim) && claim.heroSale.bundle.join() === 'valda,morag,roland' && claim.heroSale.each === 20 && claim.heroSale.bundlePrice === 50, 'claim: owned heroes, bundle, sale; no cap', JSON.stringify(claim));
|
||||
SC.heroBundleCap = '40'; ok(gp.heroClaim('m@x.com').heroBundleCap === 40 && !('heroBundleCap' in gp.heroClaim('n@x.com')), 'heroBundleCap set: only bundle owners carry it'); delete SC.heroBundleCap;
|
||||
claim = gp.heroClaim('k@x.com'); ok(claim.heroes.join() === 'kestrel,valda,morag,roland' && claim.heroBundle === true && !('heroBundleCap' in claim) && claim.heroSale.bundle.join() === 'valda,morag,roland' && claim.heroSale.each === 20 && claim.heroSale.bundlePrice === 50, 'claim: owned heroes, bundle, sale; no cap', JSON.stringify(claim));
|
||||
SC.heroBundleCap = '40'; ok(gp.heroClaim('k@x.com').heroBundleCap === 40 && !('heroBundleCap' in gp.heroClaim('n@x.com')), 'heroBundleCap set: only bundle owners carry it'); delete SC.heroBundleCap;
|
||||
|
||||
// 7. comp, revoke, stats
|
||||
r = gp.compHero('z@x.com', 'valda', 'admin hero test'); ok(r.ok && gp.heroesOwned('z@x.com').owned.join() === 'valda', 'comp grants a hero');
|
||||
r = gp.revokeHero('z@x.com', 'valda', 'admin hero test'); ok(r.ok && !gp.heroesOwned('z@x.com').owned.length, 'revoke takes it back (support only)');
|
||||
const st = gp.heroStats(); ok(st.sold.kestrel === 1 && st.sold.valda === 2 && st.sold.morag === 3 && st.sold.roland === 3 && st.bundles === 2 && st.usd === 160 && st.comped === 0, 'stats: per hero, bundles, dollars (3 x $20 + 2 x $50 = $160)', JSON.stringify(st));
|
||||
const st = gp.heroStats(); ok(st.sold.kestrel === 1 && st.sold.valda === 2 && st.sold.morag === 3 && st.sold.roland === 4 && st.bundles === 2 && st.usd === 180 && st.comped === 0 && st.waiting === 0, 'stats: per hero, bundles, dollars (4 x $20 incl. the old Kestrel sale + 2 x $50 = $180), no waiting order', JSON.stringify(st));
|
||||
const ps = gp.adminStats(T0 + 3000).passes; ok(ps.soldTotal === 1 && ps.usdTotal === 5, 'pass stats count only the weekly pass (no hero in the pass pool)', JSON.stringify(ps));
|
||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// InstantAdPay holding-tank adoption cap + BTC4Hits wording (2026-11-11). No server: the real tank.js with in-memory
|
||||
// accounts, a fake chain and a capturing mailer/messages, on a throwaway dir. node qa/tank-cap.test.mjs
|
||||
// Marty: an adopter may hold up to 10 people from the tank at one time (not yet switched on payouts), as a setting;
|
||||
// a BTC4Hits import is told the truth (their BTC4Hits account came over), never "You joined InstantAdPay without a sponsor".
|
||||
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 && !c ? ' ' + String(x).slice(0, 300) : '')); if (c) passes++; else fails++; };
|
||||
const DAY = 86400000;
|
||||
function bench(cap) {
|
||||
delete require.cache[require.resolve(path.join(SITE, 'tank.js'))];
|
||||
const tank = require(path.join(SITE, 'tank.js'));
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankcap-'));
|
||||
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: null, code: 'c' + (n++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 3 * DAY, lastSeen: Date.now() - 3600000, 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 sponsorOf() { return null; }, _by: by };
|
||||
const events = []; const mails = []; const chats = [];
|
||||
tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice(), getConfig: () => ({ explorer: 'https://polygonscan.com' }) },
|
||||
messages: { sendChat: async (id, from, to, text) => { chats.push({ to, text }); }, lastFrom: async () => 0 },
|
||||
mailer: { hasKey: () => true, send: async (to, subject, text) => { mails.push({ to, subject, text }); } }, site: 'https://instantadpay.test',
|
||||
capOpen: cap === undefined ? undefined : () => cap, hooks: {} });
|
||||
accounts.add('adopter@x.co', { username: 'helper', memberId: 77, address: '0x' + '1'.repeat(40), joinedVia: null });
|
||||
events.push({ type: 'Purchase', buyerId: 77, priceCents: 2000, block: 1 });
|
||||
return { tank, accounts, mails, chats };
|
||||
}
|
||||
{
|
||||
const { tank, accounts, mails, chats } = bench();
|
||||
for (let i = 0; i < 12; i++) accounts.add('m' + i + '@b4h.test', i < 6 ? { joinedVia: 'btc4hits', joinedRef: 'btc4hits' } : {});
|
||||
ok(tank.capOpen() === 10, 'default cap is 10');
|
||||
let n = 0; for (let i = 0; i < 10; i++) { const r = await tank.adopt('adopter@x.co', 'm' + i + '@b4h.test'); if (r.ok) n++; else console.log(' adopt ' + i + ': ' + r.error); }
|
||||
ok(n === 10, 'adopts 10 in a row');
|
||||
const r11 = await tank.adopt('adopter@x.co', 'm10@b4h.test');
|
||||
ok(r11.error && /helping 10 people/.test(r11.error) && /10 at one time is the most/.test(r11.error) && !/—/.test(r11.error), 'the 11th is refused with a clear message', JSON.stringify(r11));
|
||||
const v = await tank.view('adopter@x.co'); ok(v.cap === 10 && v.eligible === false, 'tank view shows cap 10, not eligible');
|
||||
accounts._by.get('m3@b4h.test').memberId = 901;
|
||||
ok((await tank.adopt('adopter@x.co', 'm10@b4h.test')).ok, 'a held member switching on payouts frees a slot right away');
|
||||
ok((await tank.adopt('adopter@x.co', 'm11@b4h.test')).error, 'and the cap holds again');
|
||||
const imp = mails.filter(m => m.to === 'm0@b4h.test'); const reg = mails.filter(m => m.to === 'm7@b4h.test');
|
||||
ok(imp.length === 1 && reg.length === 1, 'exactly one email to each adoptee');
|
||||
ok(/BTC4Hits has closed, and your BTC4Hits account came over to InstantAdPay/.test(imp[0].text) && !/You joined InstantAdPay/.test(imp[0].text), 'BTC4Hits import: email says the account came over', imp[0].text);
|
||||
ok(/Your BTC4Hits account moved to InstantAdPay without a sponsor/.test((chats.find(c => c.to === 'm0@b4h.test') || {}).text || ''), 'BTC4Hits import: default first chat reads right');
|
||||
ok(/^You joined InstantAdPay without a sponsor/.test(reg[0].text), 'ordinary tank member keeps the old wording');
|
||||
ok(!mails.some(m => /—/.test(m.text + m.subject)), 'no em dash in any adoption email');
|
||||
}
|
||||
{
|
||||
const { tank, accounts } = bench(3);
|
||||
for (let i = 0; i < 4; i++) accounts.add('s' + i + '@b4h.test');
|
||||
for (let i = 0; i < 3; i++) await tank.adopt('adopter@x.co', 's' + i + '@b4h.test');
|
||||
const r = await tank.adopt('adopter@x.co', 's3@b4h.test'); ok(r.error && /3 at one time/.test(r.error), 'tankAdoptCap setting is respected (3)', JSON.stringify(r));
|
||||
ok(bench('junk').tank.capOpen() === 10, 'a bad setting falls back to 10');
|
||||
}
|
||||
console.log('\n' + passes + ' passed, ' + fails + ' failed'); process.exit(fails ? 1 : 0);
|
||||
@@ -119,6 +119,8 @@ async function partA() {
|
||||
for (const em of ['a@x.co', 'b@x.co', 'c@x.co']) accounts._by.get(em).lastSeen = env.now - H;
|
||||
const r4 = await tank.readyTick();
|
||||
ok(r4.assigned.length === 1 && r4.assigned[0].adopter === 'a@x.co', 'rotation wraps to the least recently assigned (A)', JSON.stringify(r4.assigned));
|
||||
// since 2026-11-11 the cap is people held at one time who have not switched on payouts (default 10): fill A up by hand
|
||||
for (let i = 0; i < tank.capOpen(); i++) { accounts.add('fill' + i + '@x.co'); await tank.adopt('a@x.co', 'fill' + i + '@x.co'); }
|
||||
// A now has 2 open adoptions (free + free4): full. Make B and C stale: nobody eligible
|
||||
accounts._by.get('b@x.co').lastSeen = env.now - 8 * 86400000; accounts._by.get('c@x.co').lastSeen = env.now - 8 * 86400000;
|
||||
accounts.add('free5@x.co', { address: '0x' + 'f'.repeat(40) });
|
||||
|
||||
@@ -229,6 +229,10 @@ async function record(p) {
|
||||
if (!out.repeat && out.kind === 'refuel' && X.feed && (!X.marks || await X.marks.claim('rffeed:' + tx))) {
|
||||
try { await X.feed(await feedLine(email, out)); } catch (e) { console.error('refuel feed', e.message); }
|
||||
}
|
||||
// a counted refuel of $50+ (either site) earns a Downline Banners spot, paid by the company (Marty 2026-11-13), once per tx
|
||||
if (!out.repeat && out.kind === 'refuel' && cents >= 5000 && X.refuelSpot && (!X.marks || await X.marks.claim('rfspot:' + tx))) {
|
||||
X.refuelSpot({ email, site, tx, cents }).catch(e => console.error('refuel spot', e.message));
|
||||
}
|
||||
await drainLocal().catch(e => console.error('refuel drain', e.message));
|
||||
if (out.kind && out.kind !== 'none') console.log('refuel:', site, out.kind, 'month', out.month, email.replace(/^(.).*(@.*)$/, '$1***$2'), String(tx).slice(0, 12));
|
||||
return Object.assign({ on: true }, out);
|
||||
|
||||
+2
-2
@@ -57,7 +57,7 @@ function renderPage() {
|
||||
const desc = 'What changed on InstantAdPay and what is coming next: release notes and the roadmap, updated as things ship.';
|
||||
let h = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>What\'s new | InstantAdPay</title>'
|
||||
+ '<meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="' + SITE + '/whats-new"><meta property="og:title" content="What\'s new on InstantAdPay"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:image" content="' + SITE + '/banners/iap-hero-1200x630.png"><meta name="twitter:card" content="summary_large_image">'
|
||||
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261101th">'
|
||||
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln">'
|
||||
+ '<style>.wn{max-width:820px}.wn h1{margin:10px 0 6px}.wn .lead{margin:0 0 26px}.note{border-left:3px solid var(--mint);padding:4px 0 4px 18px;margin:0 0 26px}.note h2{font-size:21px;margin:0 0 4px}.note .when{color:var(--muted);font-size:13px;margin:0 0 8px}.note p,.note li{max-width:68ch}.note ul{margin:6px 0 0 20px}.tagc{display:inline-block;font-size:11px;letter-spacing:.08em;text-transform:uppercase;border-radius:999px;padding:2px 9px;margin-left:8px;vertical-align:middle;border:1px solid var(--line);color:var(--muted)}.tag-new{color:var(--mint);border-color:var(--mint-line-2)}.tag-improved{color:var(--cyan);border-color:var(--cyan-line)}.tag-fixed{color:var(--gold);border-color:var(--gold-line)}.rm{display:grid;gap:10px;margin:0 0 30px}.rmi{display:flex;gap:14px;align-items:flex-start;background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px}.rmi b{display:block}.rmi span{color:var(--muted);font-size:14px}.st{flex:0 0 auto;font-size:11px;letter-spacing:.08em;text-transform:uppercase;border-radius:999px;padding:3px 10px;border:1px solid var(--line);color:var(--muted);margin-top:3px}.st-building{color:var(--mint);border-color:var(--mint-line-2)}.st-planned{color:var(--cyan);border-color:var(--cyan-line)}</style></head><body><div class="wrap wn">'
|
||||
+ '<section class="hero" style="padding:56px 0 8px"><p class="eyebrow">Release notes and roadmap</p><h1>What\'s new, <em>and what\'s next</em>.</h1><p class="lead">' + esc(desc) + '</p></section>';
|
||||
h += '<h2 style="font-size:24px;margin:0 0 12px">On the roadmap</h2>';
|
||||
@@ -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=20261023ov"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
h += '</div><script src="/assets/common.js?v=20261114ns"></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 };
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// Atomic JSON data files (2026-11-13 incident). Every store here saves with fs.writeFileSync(file.json, ...), which truncates
|
||||
// the file and then writes it. During a deploy the old and new app copies share the volume for a few seconds; the new copy read
|
||||
// rotator.json while the old one was half way through writing it, JSON.parse failed, the store fell back to EMPTY and its next
|
||||
// save wrote that empty list over 294 spin links. This makes every .json write inside DATA_DIR atomic (write a temp file in the
|
||||
// same folder, then rename it over the real one), so a reader only ever sees the old file or the new one, never half of one.
|
||||
// The SAME file ships in InstantAdPay and LinkSpin; server.js installs it right after DATA_DIR is known.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let installed = false;
|
||||
function install(dataDir) {
|
||||
if (installed) return; installed = true;
|
||||
const root = path.resolve(dataDir) + path.sep;
|
||||
const orig = fs.writeFileSync;
|
||||
fs.writeFileSync = function (file, data, opts) {
|
||||
const flag = opts && typeof opts === 'object' ? opts.flag : null;
|
||||
if (typeof file === 'string' && /\.json$/i.test(file) && (!flag || flag === 'w') && path.resolve(file).startsWith(root)) {
|
||||
const tmp = file + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8);
|
||||
try { orig.call(fs, tmp, data, opts); fs.renameSync(tmp, file); }
|
||||
catch (e) { try { fs.unlinkSync(tmp); } catch (x) {} throw e; }
|
||||
return;
|
||||
}
|
||||
return orig.apply(fs, arguments);
|
||||
};
|
||||
}
|
||||
module.exports = { install };
|
||||
@@ -17,6 +17,7 @@ const chain = require('./chain');
|
||||
const auth = require('./auth');
|
||||
const accounts = require('./accounts');
|
||||
const forumsso = require('./forumsso'); // Earners Corner forum sign-in (DiscourseConnect, 2026-11-10)
|
||||
const networksso = require('./networksso'); // network sign-in with LinkSpin (2026-11-12, Marty approved): see networksso.js
|
||||
const themehead = require('./themehead'); // 2026-11-01 light/dark theme head script for server-rendered pages + its CSP hash
|
||||
const ads = require('./ads');
|
||||
const mailer = require('./mailer');
|
||||
@@ -54,10 +55,43 @@ 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 draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET)
|
||||
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)
|
||||
let follow = null, followStore = null;
|
||||
const LS_BASE = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
|
||||
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 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
|
||||
// their network sponsor's wallet as sponsor. Signed with NETWORK_SSO_SECRET ('net.v1.' + ts + newline + raw body).
|
||||
async function refuelSpotToBL({ email, site, tx, cents }) {
|
||||
const a = await accounts.byEmail(email).catch(() => null);
|
||||
const mask = String(email).replace(/^(.).*(@.*)$/, '$1***$2');
|
||||
if (!a || !a.address) { console.log('refuel spot: no wallet linked, not sent', mask); return; }
|
||||
const sp = await accounts.sponsorOf(email).catch(() => null);
|
||||
const raw = JSON.stringify({ tx, site, cents, wallet: a.address, sponsorWallet: sp && sp.address ? sp.address : null });
|
||||
const sec = String(process.env.NETWORK_SSO_SECRET || '').trim(); if (sec.length < 32) return;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex');
|
||||
try {
|
||||
const r = await fetch(BL_BASE() + '/api/partner/refuel-spot', { method: 'POST', body: raw, signal: AbortSignal.timeout(10000), headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } });
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (r.ok) {
|
||||
console.log('refuel spot queued on Downline Banners', mask, String(tx).slice(0, 12), j.repeat ? '(repeat)' : '');
|
||||
if (!j.repeat) await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], 'Your refuel earned a Downline Banners spot',
|
||||
'<p>Your $' + (cents / 100).toFixed(0) + ' refuel earned you a free spot on <a href="https://downlinebanners.com/my">Downline Banners</a>, the network banner board. It is being placed in the line for your wallet now.</p><p>Open <a href="https://downlinebanners.com/my">My Spots</a> to add your banner and link (or use one of your LinkSpin Banner Spins). Your InstantAdPay sign-in carries you in.</p>', 'notice').catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (r.status === 400 || r.status === 401) { console.error('refuel spot refused', r.status, j.error || '', mask); return; }
|
||||
} catch (e) {}
|
||||
await new Promise(ok => setTimeout(ok, 30000 * (i + 1)));
|
||||
}
|
||||
console.error('refuel spot: Downline Banners did not answer', mask, String(tx).slice(0, 12));
|
||||
}
|
||||
let activationCache = { at: 0, map: null };
|
||||
function activationByAddress() { // MemberActivated events by wallet, for the Sponsor check (when the contract bound the sponsor)
|
||||
if (activationCache.map && Date.now() - activationCache.at < 60000) return activationCache.map;
|
||||
@@ -92,15 +126,18 @@ const supportbot = require('./supportbot'); // @CTBTickets_bot: ticket pings wit
|
||||
const tickets = require('./tickets'); // help desk: member Help pane, public /support, chatbot hand-off, admin Support pane (Marty, 2026-10-16)
|
||||
const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15)
|
||||
const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12)
|
||||
const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/refuel', '/conversion-tracking', '/presentation', '/support', '/bixpay']);
|
||||
const TRAFFIC_PAGES = new Set(['/chasing-unicorns', '/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/refuel', '/conversion-tracking', '/presentation', '/support', '/bixpay']);
|
||||
let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute)
|
||||
const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting
|
||||
const netsites = require('./netsites'); // footer network list from the hub (2026-11-14 trust pack)
|
||||
const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY)
|
||||
|
||||
const PORT = Number(process.env.PORT || 3000);
|
||||
const ROOT = __dirname;
|
||||
const PUBLIC_DIR = path.join(ROOT, 'public');
|
||||
const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, 'data');
|
||||
require('./safefs').install(DATA_DIR); // every .json data file is written atomically (2026-11-13 rotator.json loss)
|
||||
const docstore = require('./docstore'); docstore.install(DATA_DIR); // data documents live in MySQL when DOCSTORE_URL is set (2026-11-13, database is the standard)
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme';
|
||||
const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase();
|
||||
// Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept
|
||||
@@ -109,7 +146,7 @@ const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase();
|
||||
const ADMIN_SESS_FILE = path.join(DATA_DIR, 'admin-sessions.json');
|
||||
const ADMIN_TTL = 12 * 60 * 60 * 1000;
|
||||
let adminSessions = {};
|
||||
try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; }
|
||||
if (!process.env.DOCSTORE_URL) { try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } } // with MySQL: loaded right after docstore.init
|
||||
function saveAdminSessions() {
|
||||
const now = Date.now();
|
||||
for (const k of Object.keys(adminSessions)) if (!adminSessions[k] || adminSessions[k].expires < now) delete adminSessions[k];
|
||||
@@ -534,11 +571,16 @@ async function frameCheck(url, inGame) {
|
||||
}
|
||||
async function boot() {
|
||||
await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode)
|
||||
await docstore.init({}); // before any module reads its data
|
||||
process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); });
|
||||
if (process.env.DOCSTORE_URL) { try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } }
|
||||
marks.init({ db });
|
||||
marks.ensureTable().catch(e => console.error('marks table', e.message));
|
||||
lsconv.init({ db, dataDir: DATA_DIR });
|
||||
lsreport.init({ db, dataDir: DATA_DIR });
|
||||
accounts.onWalletLinked(e => { lsreport.wallet(e).catch(err => console.error('lsreport wallet', err.message)); });
|
||||
accounts.onWalletLinked(hubsync.enabled()
|
||||
? e => { lsreport.wallet(e).catch(err => console.error('lsreport wallet', err.message)); hubsync.wallet(e); }
|
||||
: e => { lsreport.wallet(e).catch(err => console.error('lsreport wallet', err.message)); });
|
||||
auth.onSeen((email, req) => lsconv.noteSession(email, clientIp(req), req.headers['user-agent'])); // own-click tests on LinkSpin (2026-10-26)
|
||||
setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref();
|
||||
chain.init({ onEvent: ev => {
|
||||
@@ -559,10 +601,37 @@ async function boot() {
|
||||
wednesday.onEvent(ev).catch(e => console.error('wednesday bonus', e.message));
|
||||
refuel.onIapPurchase(ev).catch(e => console.error('refuel streak', e.message)); // its own bonus, stacked on Friday/Wednesday; no-op while refuelStreak is off
|
||||
sponsorSyncOnEvent(ev).catch(e => console.error('sponsor sync', e.message));
|
||||
hubsync.onChain(ev); // network hub: payout switch-on -> contract bind (no-op unless HUB_ENABLED)
|
||||
lsReportPurchase(ev).catch(e => console.error('lsreport purchase', e.message)); // reporting only: one local row, delivered in the background
|
||||
}).catch(e => console.error('marks claim', e.message));
|
||||
} });
|
||||
auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: 'instantadpay.com' });
|
||||
// network sign-in (2026-11-12): a member signed in on LinkSpin arrives here signed in, and the other way round. Member sessions
|
||||
// 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
|
||||
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;
|
||||
let email = s.email || null; if (!email && s.address) { try { const a = await accounts.byAddress(s.address); if (a && a.email) email = a.email; } catch (e) {} }
|
||||
return email && !fraud.isSuspended(email) ? Object.assign({}, s, { email }) : null; },
|
||||
accept: async email => {
|
||||
const a = await accounts.byEmail(email);
|
||||
if (!a) return { fallback: 'no account here yet' };
|
||||
if (accounts.isUnclaimedShell(a)) return { fallback: 'waiting account, first sign-in needs the code' };
|
||||
if (fraud.isSuspended(email) || fraud.isBlocked(email)) return { fallback: 'suspended or blocked' };
|
||||
return { ok: true };
|
||||
},
|
||||
signIn: async (email, req) => { // the same session the email code makes (4 hours, same rights)
|
||||
const a = await accounts.byEmail(email); let memberId = 0;
|
||||
if (a && a.address) { try { memberId = await chain.memberIdByAccount(a.address); } catch (e) {} }
|
||||
fraud.recordSeen(email, req).catch(() => {});
|
||||
return auth.sessionCookie(await auth.mintSession({ email: a.email, address: a.address, memberId }));
|
||||
},
|
||||
// the dashboard runs the welcome tour / login ad after a sign-in (?welcome=1, the same step a code sign-in takes)
|
||||
landing: to => { const x = new URL(to, 'http://x'); if (x.pathname === '/my') x.searchParams.set('welcome', '1'); return x.pathname + x.search + x.hash; },
|
||||
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()) });
|
||||
mailer.init({ dataDir: DATA_DIR });
|
||||
@@ -570,7 +639,7 @@ async function boot() {
|
||||
reports.init({ dataDir: DATA_DIR });
|
||||
drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: 'https://instantadpay.com' });
|
||||
chatbot.init({ dataDir: DATA_DIR, chain, bixLive: () => bixpay.live(), gameLive: slug => String(siteConfig().gamesLive == null ? 'polhunter' : siteConfig().gamesLive).split(',').map(x => x.trim().toLowerCase()).includes(slug), refuelOn: () => refuel.cfg().on, passTiers: () => { const c = gamepass.cfg(); return { on: c.enabled && c.tierSales, rows: gamepass.TIER_DEFS.filter(d => d.key !== 'weekly').map(d => ({ name: d.name, perks: d.perks, price: c.tiers[d.key].price, usd: c.tiers[d.key].price / 100, days: c.tiers[d.key].days, sale: c.tiers[d.key].sale })) }; },
|
||||
heroSale: () => { const h = gamepass.cfg().heroes, N = Object.fromEntries(gamepass.HERO_DEFS.map(d => [d.key, d.name])); return { sale: h.sale, rows: gamepass.HERO_DEFS.map(d => ({ name: d.name, usd: h.price[d.key] / 100, free: h.price[d.key] === 0 })), bundle: { names: h.bundle.heroes.map(k => N[k]), usd: h.bundle.price / 100 } }; } }); // pass tiers fact follows sovTiers (2026-10-22); bonus heroes follow heroSales (2026-11-05)
|
||||
heroSale: () => { const h = gamepass.cfg().heroes, N = Object.fromEntries(gamepass.HERO_DEFS.map(d => [d.key, d.name])); return { sale: h.sale, rows: gamepass.HERO_DEFS.map(d => ({ name: d.name, usd: h.price[d.key] / 100, free: h.price[d.key] === 0, freeAt: d.freeAt || null })), bundle: { names: h.bundle.heroes.map(k => N[k]), usd: h.bundle.price / 100 } }; } }); // pass tiers fact follows sovTiers (2026-10-22); bonus heroes follow heroSales (2026-11-05)
|
||||
setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000);
|
||||
setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000);
|
||||
setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends
|
||||
@@ -623,6 +692,7 @@ async function boot() {
|
||||
featuredPerDay: () => ads.rates().featuredPerDay || 40,
|
||||
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); },
|
||||
badge: (email, key) => postBadgeOnce(email, key, 'Monthly Refuel'),
|
||||
refuelSpot: refuelSpotToBL, // $50+ counted refuel -> one Downline Banners spot (2026-11-13)
|
||||
feed: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> \u00b7 ' + text, sc.telegramEchoTopicId); } });
|
||||
kit.init({ dataDir: DATA_DIR, program: 'iap', publicDir: PUBLIC_DIR, siteUrl: 'https://instantadpay.com',
|
||||
entitled: async email => { const v = await refuel.view(email); return v && v.on ? { on: true, months: v.kits || {}, nextRefuel: v.refuelDayLabel || null, today: v.today || null } : { on: false }; },
|
||||
@@ -660,9 +730,14 @@ async function boot() {
|
||||
sponsorAccount: em => accounts.byEmail(em),
|
||||
wouldCycle: async (email, sp) => { let cur = sp; const seen = new Set(); for (let i = 0; cur && i < 60; i++) { if (cur.email === email || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); } return false; },
|
||||
activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null });
|
||||
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore,
|
||||
tank.init({ capOpen: () => siteConfig().tankAdoptCap, dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore,
|
||||
// activation hold + 24-hour safety net (2026-10-27): a tank member is never bound under the fallback position
|
||||
hooks: { network: (email, address) => lsinbound.networkSponsor(email, address), isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em),
|
||||
// network hub rule 3 (2026-11-14, only with HUB_ENABLED): the hub's sponsor comes first for alignment, and nobody it reports
|
||||
// locked on a network contract or sponsored is offered, moved to the tank or auto-assigned (hubsync.js: cache + fail-safe)
|
||||
hooks: { network: async (email, address) => (hubsync.enabled() ? await hubsync.hubSponsor(email).catch(() => null) : null) || lsinbound.networkSponsor(email, address),
|
||||
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
|
||||
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),
|
||||
@@ -672,6 +747,13 @@ async function boot() {
|
||||
// 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 });
|
||||
// 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(); }
|
||||
// 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'),
|
||||
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);
|
||||
setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
|
||||
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account
|
||||
@@ -753,6 +835,7 @@ 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
|
||||
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);
|
||||
setInterval(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 60 * 60 * 1000);
|
||||
@@ -824,6 +907,7 @@ 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)
|
||||
tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11
|
||||
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
|
||||
@@ -863,7 +947,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; 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; 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 || {});
|
||||
@@ -1537,12 +1621,13 @@ async function tankNotifyTick() {
|
||||
// the first run of this rule: anyone who joined before it was already announced at sign-up.
|
||||
const graceFrom = st.graceFrom || (st.graceFrom = st.last || Date.now());
|
||||
const fresh = [];
|
||||
for (const w of tank.openedSince(await tank.waiting(), since)) if ((w.joined || 0) > graceFrom && await marks.claim('tankopen:' + w.email + ':' + (w.joined || 0))) fresh.push(w);
|
||||
const all = await tank.waiting(); // the running total goes in the post too (Marty 2026-11-14: "post those totals")
|
||||
for (const w of tank.openedSince(all, since)) if ((w.joined || 0) > graceFrom && await marks.claim('tankopen:' + w.email + ':' + (w.joined || 0))) fresh.push(w);
|
||||
st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st));
|
||||
if (!fresh.length) return;
|
||||
const named = fresh.filter(w => w.username).map(w => '@' + w.username);
|
||||
const who = named.length ? ': ' + named.slice(0, 8).join(', ') + (named.length > 8 ? ' and ' + (named.length - 8) + ' more' : '') : '';
|
||||
const text = '\u{1FAA3} <b>InstantAdPay</b> \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who
|
||||
const text = '\u{1FAA3} <b>InstantAdPay</b> \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who + ' (' + tank.adoptableOf(all).length + ' waiting in total)'
|
||||
+ '\nAdopt from My line \u203a Holding tank: <a href="https://instantadpay.com/my#line">instantadpay.com/my</a>';
|
||||
await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId);
|
||||
}
|
||||
@@ -2284,6 +2369,16 @@ const server = http.createServer(async (req, res) => {
|
||||
const to = 'https://instantadpay.com' + (p === '/' ? '/' : ref ? '/join/' + ref[1] : p) + (u.search || '');
|
||||
res.writeHead(302, { Location: to, 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }); return res.end();
|
||||
} }
|
||||
// network sign-in with LinkSpin (2026-11-12): /go/linkspin, /sso/start, /sso/check, /sso/in, /api/sso/status
|
||||
if (req.method === 'GET' && (p === '/go/linkspin' || p === '/go/bannerline' || p === '/go/vbb' || p === '/go/viraladblitz' || p === '/go/downlinehydra' || p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
|
||||
// network member lookup for Downline Banners (2026-11-13, Marty: share links use the InstantAdPay username): ?u=<username> -> the
|
||||
// account's linked wallet, ?a=<wallet> -> the username. Public data only (usernames are public join links, wallets are on-chain).
|
||||
if (req.method === 'GET' && p === '/api/network/member') {
|
||||
let a = null; const un = String(u.searchParams.get('u') || '').trim().toLowerCase(), ad = String(u.searchParams.get('a') || '').trim().toLowerCase();
|
||||
try { if (/^[a-z0-9_]{1,20}$/.test(un)) a = await accounts.byUsername(un); else if (/^0x[0-9a-f]{40}$/.test(ad)) a = await accounts.byAddress(ad); } catch (e) {}
|
||||
const ok = a && a.address && a.username && !fraud.isSuspended(a.email);
|
||||
return json(res, 200, ok ? { username: a.username, address: String(a.address).toLowerCase() } : { username: null, address: null }, { 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' });
|
||||
}
|
||||
|
||||
// a LinkSpin click arriving on any page (?lsclk= or ?lsid=): the first-party cookie, 30 days, last click wins (reporting only, lsreport.js).
|
||||
// Added to whatever the page sends, like the viral-link cookies below.
|
||||
@@ -2377,9 +2472,15 @@ const server = http.createServer(async (req, res) => {
|
||||
// pays a referral bounty only for people it actually sent, so that proof has to be reliable
|
||||
// rather than dependent on a header (Marty, 2026-09-24: "not just members that come on board
|
||||
// IAP and work their way over to POL Hunter").
|
||||
if (!cookies['iap.ref']) {
|
||||
// A ?src= tag on the link (every mailer / traffic-source spin link carries one) is recorded with the host, so a sign-up
|
||||
// says "mailer.gold/mailergold" or just "mailergold" when the referrer was stripped, and a tagged visit replaces an
|
||||
// untagged "direct" first touch (Marty, 2026-11-12: "we need the source tag so we can know where these things come from").
|
||||
const srcTag = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30);
|
||||
const prevRef = decodeURIComponent(cookies['iap.ref'] || '');
|
||||
if (!prevRef || (srcTag && prevRef === 'direct')) {
|
||||
const host = u.searchParams.get('from') === 'polhunter' ? 'polhunter.com' : u.searchParams.get('from') === 'driprunner' ? 'driprunner.saasy.top' : coach.refHost(req.headers.referer);
|
||||
set.push('iap.ref=' + encodeURIComponent(host) + cookieTail);
|
||||
const fromGame = /^(polhunter|driprunner)$/.test(String(u.searchParams.get('from') || '')); // PolHunter's bounty proof reads the bare host: never tag it
|
||||
set.push('iap.ref=' + encodeURIComponent(srcTag && !fromGame ? (host && host !== 'direct' ? host + '/' : '') + srcTag : host) + cookieTail);
|
||||
}
|
||||
return serveJoinPage(res, tok, ang ? angle : '', ang, set);
|
||||
}
|
||||
@@ -2404,7 +2505,7 @@ const server = http.createServer(async (req, res) => {
|
||||
const r = await drip.unsubscribe(u.searchParams.get('e'), u.searchParams.get('t'));
|
||||
const msg = r.error ? r.error : 'Done. You will not get any more emails from InstantAdPay, apart from sign-in codes you ask for and receipts for payments to or from your account. Your account is unchanged.';
|
||||
res.writeHead(r.error ? 400 : 200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }));
|
||||
return res.end('<!doctype html><html' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><title>InstantAdPay</title>' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261101th"></head><body><div class="wrap" style="max-width:560px;padding:80px 22px"><a href="/"><img src="/logo.png" alt="InstantAdPay" style="height:34px"></a><h1 style="font-size:30px;margin:26px 0 12px">' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '</h1><p>' + msg + '</p><p><a class="btn small sec" href="/my">Member area</a></p></div></body></html>');
|
||||
return res.end('<!doctype html><html' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><title>InstantAdPay</title>' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln"></head><body><div class="wrap" style="max-width:560px;padding:80px 22px"><a href="/"><img src="/logo.png" alt="InstantAdPay" style="height:34px"></a><h1 style="font-size:30px;margin:26px 0 12px">' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '</h1><p>' + msg + '</p><p><a class="btn small sec" href="/my">Member area</a></p></div></body></html>');
|
||||
}
|
||||
|
||||
// -- public API
|
||||
@@ -2429,6 +2530,7 @@ const server = http.createServer(async (req, res) => {
|
||||
try { for (const b of (await blog.listPublished()).slice(0, 40)) pages.push({ path: '/blog/' + b.slug, title: 'Article: ' + b.title, cover: b.cover || null }); } catch (e) {}
|
||||
return json(res, 200, { pages });
|
||||
}
|
||||
if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res);
|
||||
if (p === '/api/config' && req.method === 'GET') {
|
||||
const c = chain.getConfig();
|
||||
// public copy of the site settings: never anything that looks like a credential
|
||||
@@ -2767,7 +2869,7 @@ const server = http.createServer(async (req, res) => {
|
||||
let memberId = 0;
|
||||
if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} }
|
||||
const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId });
|
||||
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ clutterhunt: '/api/my/clutterhunt', spellwheel: '/api/my/spellwheel', polybreak: '/api/my/polybreak', polminer: '/api/my/polminer', turkeydrop: '/api/my/turkeydrop', warpwares: '/api/my/warpwares', polywarriors: '/api/my/polywarriors', driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
|
||||
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ clutterhunt: '/api/my/clutterhunt', spellwheel: '/api/my/spellwheel', polybreak: '/api/my/polybreak', polminer: '/api/my/polminer', turkeydrop: '/api/my/turkeydrop', warpwares: '/api/my/warpwares', polywarriors: '/api/my/polywarriors', driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || (networksso.pendingBack(req) ? '/sso/resume' : null) }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
|
||||
}
|
||||
|
||||
// -- in-game sign-in (2026-10-03): see GAME_AUTH. Mirrors /api/auth/email/start + verify, minus cookies.
|
||||
@@ -2938,7 +3040,7 @@ const server = http.createServer(async (req, res) => {
|
||||
}
|
||||
if (p === '/api/auth/logout' && req.method === 'POST') {
|
||||
await auth.logout(req);
|
||||
return json(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie() });
|
||||
return json(res, 200, { ok: true }, { 'Set-Cookie': [auth.clearCookie(), networksso.offCookie()] }); // signed out stays signed out: no silent network sign-in here for 12 hours
|
||||
}
|
||||
if (p === '/api/gas' && req.method === 'GET') {
|
||||
try { return json(res, 200, await chain.suggestedFees()); }
|
||||
@@ -2970,7 +3072,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'] : null, sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
|
||||
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,
|
||||
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)
|
||||
@@ -3090,6 +3192,9 @@ const server = http.createServer(async (req, res) => {
|
||||
const rTot = await ads.earnedTotals(joined.map(r => r.email)); // surf earnings per referral (Marty, 2026-09-29)
|
||||
out.referrals = joined.map(r => ({
|
||||
name: r.username || r.email.replace(/^(.).*(@.*)$/, '$1***$2'), // username, else privacy mask
|
||||
// directs only (this list IS the member's directs): email, where they came from and how they joined, up front in
|
||||
// "Your line" instead of buried in the three-level card (Marty, 2026-11-12)
|
||||
email: r.email, src: r.joinedRef || null, via: r.joinedVia || null, ref: r.code || null,
|
||||
joined: r.created,
|
||||
lastSeen: r.lastSeen || 0,
|
||||
wallet: !!r.address, activated: !!r.memberId,
|
||||
@@ -3164,6 +3269,19 @@ const server = http.createServer(async (req, res) => {
|
||||
if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' });
|
||||
return json(res, 200, Object.assign(await adminMember.view(a.email), { pwPasses: pwPasses.get(String(a.email).toLowerCase()) || null })); // mint passes on the card (2026-10-10)
|
||||
}
|
||||
// -- admin: the network hub's member lookup (Marty 2026-11-14, read-only): what the member card leaves out. GET ?email=
|
||||
if (p === '/api/admin/member-extra' && req.method === 'GET') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const e = String(u.searchParams.get('email') || '').trim().toLowerCase();
|
||||
const a = e ? await accounts.byEmail(e) : null;
|
||||
if (!a) return json(res, 404, { error: 'no such account' });
|
||||
const r = tank.readyRec(e);
|
||||
return json(res, 200, {
|
||||
optedOut: await drip.isUnsubscribed(e).catch(() => null), updatesOptIn: await updates.optedIn(e).catch(() => null),
|
||||
tank: { inTank: !a.sponsorRef && !a.memberId, ready: r ? { readyAt: r.readyAt || null, holdUntil: r.readyAt ? r.readyAt + tank.READY_MS : null } : null, adoptions: await tank.summaryFor(e).catch(() => null) },
|
||||
fraud: await fraud.get(e).then(f => f && { flags: f.flags || [], suspended: !!f.suspended, suspendedReason: f.suspendedReason || null }).catch(() => null)
|
||||
});
|
||||
}
|
||||
if (p === '/api/admin/member' && req.method === 'PATCH') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req);
|
||||
@@ -3203,6 +3321,27 @@ const server = http.createServer(async (req, res) => {
|
||||
// -- link-farm scan (2026-10-30): last result + allowlist, run now (no Telegram), allow / unallow an email
|
||||
if (p === '/api/admin/spamscan' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, spamscan.view()); }
|
||||
if (p === '/api/admin/spamscan/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); await spamscan.run({ manual: true, quiet: true }); return json(res, 200, spamscan.view()); }
|
||||
// admin -> one member: inbox message + email (Marty 2026-11-12: "no way to send them an inbox message that would email them as well")
|
||||
if (p === '/api/admin/member/message' && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e);
|
||||
if (!acct) return json(res, 404, { error: 'No such member.' });
|
||||
const subject = String(b.subject || '').trim().slice(0, 150), text = String(b.text || '').trim().slice(0, 8000);
|
||||
if (!subject || !text) return json(res, 400, { error: 'Subject and message are both needed.' });
|
||||
const escH = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const html = text.split(/\n{2,}/).map(par => '<p>' + escH(par).replace(/\n/g, '<br>') + '</p>').join('');
|
||||
await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [e], subject, html, 'broadcast');
|
||||
let emailed = false, emailSkipped = '';
|
||||
if (!mailer.hasKey()) emailSkipped = 'mail is not set up on this server';
|
||||
else {
|
||||
const hello = acct.username ? 'Hi @' + acct.username + ',\n\n' : 'Hi,\n\n';
|
||||
const tail = '\n\nYou can reply from your member inbox: https://instantadpay.com/my\n\nMarty Bostick, InstantAdPay';
|
||||
try { emailed = (await mailer.send(e, subject, hello + text + tail, '<div style="font-family:Arial,sans-serif;font-size:15px;line-height:1.5">' + '<p>' + escH(hello.trim()) + '</p>' + html + '<p>You can reply from your member inbox: <a href="https://instantadpay.com/my">instantadpay.com/my</a></p><p>Marty Bostick, InstantAdPay</p></div>')) !== false; if (!emailed) emailSkipped = 'they unsubscribed from email'; }
|
||||
catch (err) { emailSkipped = 'the mail service failed (' + String(err.message || err).slice(0, 80) + ')'; }
|
||||
}
|
||||
console.log('admin message', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'inbox ok', emailed ? 'emailed' : 'email skipped: ' + emailSkipped);
|
||||
return json(res, 200, { ok: true, inbox: true, emailed, emailSkipped });
|
||||
}
|
||||
if (p === '/api/admin/spamscan/allow' && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'Which email?' });
|
||||
@@ -3579,6 +3718,52 @@ const server = http.createServer(async (req, res) => {
|
||||
const rv = await refuel.view(email);
|
||||
return json(res, 200, { ok: true, refuel: rv, facts: rv.on ? await engine.facts({ site: 'iap', adminMember, ads, coach }, email) : null });
|
||||
}
|
||||
// -- network hub hooks (hubsync.js, 2026-11-12): signed with HUB_SECRET (X-Hub-Ts + X-Hub-Sig), 5-minute window. Only with HUB_ENABLED.
|
||||
// -- personal notices (2026-11-13, first use: Marty's go on the Downline Banners wallet nudge to sponsors). Admin only. One
|
||||
// message per member, each with its own text: InstantAdPay inbox (messages.deliver, kind notice) + email through the site
|
||||
// mailer, which skips anyone who unsubscribed and adds the unsubscribe link. Once per member per batch (marks.claim
|
||||
// 'nb:<batch>:<email>'), so a repeated call never mails anyone twice. Runs in the background, 400 ms apart;
|
||||
// GET ?batch= reads the result (notice-batches.json).
|
||||
if (p === '/api/admin/notice-batch' && (req.method === 'POST' || req.method === 'GET')) {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
||||
const NB = path.join(DATA_DIR, 'notice-batches.json');
|
||||
const readNB = () => { try { return JSON.parse(fs.readFileSync(NB, 'utf8')); } catch (e) { return {}; } };
|
||||
if (req.method === 'GET') return json(res, 200, readNB()[String(u.searchParams.get('batch') || '')] || { error: 'No such batch.' });
|
||||
const b = await readBody(req); // { batch, subject, html, text, items: [{ email, vars: { key: value } }] }, {{key}} filled per member
|
||||
const batch = String(b.batch || '').replace(/[^a-z0-9-]/gi, '').slice(0, 60); const subjectT = String(b.subject || '').slice(0, 160);
|
||||
const items = Array.isArray(b.items) ? b.items.slice(0, 5000) : [];
|
||||
const fill = (t, v, html) => String(t || '').replace(/\{\{(\w+)\}\}/g, (m, k) => { const x = v && v[k] != null ? String(v[k]) : ''; return html ? x.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])) : x; });
|
||||
const subject = subjectT;
|
||||
if (!batch || !subject || !items.length) return json(res, 400, { error: 'batch, subject and items required' });
|
||||
const all = readNB(); if (all[batch] && all[batch].running) return json(res, 409, { error: 'That batch is already running.' });
|
||||
all[batch] = { subject, total: items.length, sent: 0, inbox: 0, optedOut: 0, noAccount: 0, repeat: 0, failed: 0, running: true, started: Date.now() };
|
||||
fs.writeFileSync(NB, JSON.stringify(all));
|
||||
json(res, 200, { ok: true, batch, total: items.length });
|
||||
(async () => {
|
||||
const st = all[batch];
|
||||
for (const it of items) {
|
||||
const e = String(it.email || '').trim().toLowerCase();
|
||||
try {
|
||||
const acct = await accounts.byEmail(e); if (!acct) { st.noAccount++; continue; }
|
||||
if (!(await marks.claim('nb:' + batch + ':' + e))) { st.repeat++; continue; }
|
||||
const subj = fill(subjectT, it.vars, false), html = fill(b.html, it.vars, true), text = fill(b.text, it.vars, false);
|
||||
await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [e], subj, html, 'notice'); st.inbox++;
|
||||
const ok = await mailer.send(e, subj, text, html);
|
||||
if (ok === false) st.optedOut++; else st.sent++;
|
||||
} catch (err) { st.failed++; console.error('notice-batch', batch, err.message); }
|
||||
const cur = readNB(); cur[batch] = st; fs.writeFileSync(NB, JSON.stringify(cur));
|
||||
await new Promise(r => setTimeout(r, 400));
|
||||
}
|
||||
st.running = false; st.finished = Date.now(); const cur = readNB(); cur[batch] = st; fs.writeFileSync(NB, JSON.stringify(cur));
|
||||
console.log('notice-batch', batch, JSON.stringify(st));
|
||||
})().catch(err => console.error('notice-batch', err.message));
|
||||
return;
|
||||
}
|
||||
if (p === '/api/hub/events' && req.method === 'POST' && hubsync.enabled()) {
|
||||
let raw; try { raw = (await readRaw(req, 2e6)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
|
||||
const r = await hubsync.receive(req.headers, raw); return json(res, r.status, r.body);
|
||||
}
|
||||
if (p === '/api/admin/hub' && req.method === 'GET' && hubsync.enabled()) { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, hubsync.adminView()); }
|
||||
if (p === '/api/partner/registry' && req.method === 'POST') {
|
||||
const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
||||
const b = sg.body;
|
||||
@@ -3649,10 +3834,34 @@ const server = http.createServer(async (req, res) => {
|
||||
}
|
||||
if (p === '/api/admin/lssync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await lssync.tick(!!(b && b.force))); }
|
||||
if (p === '/api/admin/walletnudge/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await walletnudge.tick()); }
|
||||
// -- 5xYourTeam The Draft (draftpartner.js, 2026-11-15): signed partner calls, DRAFT_PARTNER_SECRET as X-Draft-Ts + X-Draft-Sig
|
||||
if (p.startsWith('/api/partner/draft/') && req.method === 'POST') {
|
||||
const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > 64000) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); });
|
||||
const sg = draftpartner.verify(req.headers, raw); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
||||
const op = p.slice('/api/partner/draft/'.length);
|
||||
if (!['pool', 'adopt', 'release', 'status'].includes(op)) return json(res, 404, { error: 'unknown op' });
|
||||
const r = await draftpartner.handle(op, sg.body);
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (p === '/api/admin/draft' && req.method === 'GET') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, await draftpartner.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());
|
||||
}
|
||||
// an adoption made for a member (Marty 2026-11-14: sponsors who lost people when the contract sponsor won get a few from the
|
||||
// tank). The same tank.adopt as the member's own button: their eligibility and cap, the adoptee's email and chat. No payments-topic
|
||||
// post per pickup (a batch would flood it).
|
||||
if (p === '/api/admin/tank/adopt' && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req);
|
||||
if (!b.adopter || !b.who) return json(res, 400, { error: 'adopter and who' });
|
||||
if (fraud.excluded(b.adopter)) return json(res, 403, { error: 'Adoptions are not available on that account.' });
|
||||
const r = await tank.adopt(String(b.adopter).toLowerCase(), b.who, b.note);
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
// -- admin Traffic tab: page views + join-page views + signups + $20 buyers, by referring
|
||||
// domain / first-touch source, by landing page, by angle and by day (Marty, 2026-09-12)
|
||||
// login-ad showings per Central day, dashboard vs games (2026-10-18: a week of combined sign-ins before the cap decision)
|
||||
@@ -4706,6 +4915,7 @@ const server = http.createServer(async (req, res) => {
|
||||
name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member',
|
||||
ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels
|
||||
email: L.level === 1 ? m.email : null, // directs only
|
||||
src: L.level === 1 ? (m.joinedRef || null) : null, via: L.level === 1 ? (m.joinedVia || null) : null, // where a direct came from (2026-11-12)
|
||||
joined: m.created,
|
||||
lastSeen: m.lastSeen || 0,
|
||||
wallet: !!m.address, activated: !!m.memberId,
|
||||
@@ -4737,6 +4947,8 @@ const server = http.createServer(async (req, res) => {
|
||||
try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; }
|
||||
try { out.badges = await ads.milestonesOf(a.email); } catch (e) { out.badges = []; }
|
||||
try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; }
|
||||
// your own directs: contact + origin (Marty, 2026-11-12). Levels 2 and 3 belong to someone else's direct relationship: no email.
|
||||
try { if (await accounts.isDownlineOf(s.email, a.email, 1)) { out.direct = true; out.email = a.email; out.src = a.joinedRef || null; out.via = a.joinedVia || null; } } catch (e) {}
|
||||
return json(res, 200, out);
|
||||
}
|
||||
// -- broadcast a message to your downline (1/day), on-site inbox + email
|
||||
@@ -6086,6 +6298,7 @@ const server = http.createServer(async (req, res) => {
|
||||
if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12)
|
||||
if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html'));
|
||||
if (p === '/games') return sendFile(res, path.join(PUBLIC_DIR, 'games.html'));
|
||||
if (p === '/chasing-unicorns') return sendFile(res, path.join(PUBLIC_DIR, 'chasing-unicorns.html')); // promo-tool lead magnet: a fake dashboard that teaches the red flags (Marty, 2026-11-12)
|
||||
if (p === '/presentation') return sendFile(res, path.join(PUBLIC_DIR, 'presentation.html')); // narrated Build Wide presentation, captions in 6 languages (2026-10-15) // public games list (2026-10-10) // member guide: how earning works (2026-09-12)
|
||||
// -- badge share page + image: /b/<username>/<key> (OG preview = the member's composed badge) (Marty, 2026-09-13)
|
||||
m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)\.jpg$/.exec(p);
|
||||
@@ -6105,11 +6318,11 @@ const server = http.createServer(async (req, res) => {
|
||||
+ '<meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="' + url + '"><meta name="robots" content="noindex">'
|
||||
+ '<meta property="og:type" content="website"><meta property="og:site_name" content="InstantAdPay"><meta property="og:title" content="' + esc(title) + '"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:url" content="' + url + '"><meta property="og:image" content="' + img + '"><meta property="og:image:width" content="1024"><meta property="og:image:height" content="1024">'
|
||||
+ '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' + esc(title) + '"><meta name="twitter:description" content="' + esc(desc) + '"><meta name="twitter:image" content="' + img + '">'
|
||||
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261101th">'
|
||||
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln">'
|
||||
+ '<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=20261023ov"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
|
||||
+ '<script src="/assets/common.js?v=20261114ns"></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);
|
||||
}
|
||||
@@ -6171,7 +6384,7 @@ const server = http.createServer(async (req, res) => {
|
||||
let a = await accounts.byUsername(tok); if (!a) a = await accounts.byCode(tok);
|
||||
// a deleted or never-seen name is a real 404, never a bare "Banner wall" page at 200 (a soft 404 Google kept indexed, 2026-10-30)
|
||||
if (!a) {
|
||||
const nf = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>No wall under that name | InstantAdPay</title><meta name="robots" content="noindex"><link rel="icon" type="image/png" href="/logo-icon.png">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261101th"></head><body><section><div class="wrap" style="max-width:720px;text-align:center;padding:60px 0"><h1>No wall under that name</h1><p class="muted">This member page does not exist or was removed.</p><p><a class="btn" href="/">Go to InstantAdPay</a></p></div></section></body></html>';
|
||||
const nf = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>No wall under that name | InstantAdPay</title><meta name="robots" content="noindex"><link rel="icon" type="image/png" href="/logo-icon.png">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln"></head><body><section><div class="wrap" style="max-width:720px;text-align:center;padding:60px 0"><h1>No wall under that name</h1><p class="muted">This member page does not exist or was removed.</p><p><a class="btn" href="/">Go to InstantAdPay</a></p></div></section></body></html>';
|
||||
res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Robots-Tag': 'noindex' }));
|
||||
return res.end(nf);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,12 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const db = require('./db');
|
||||
|
||||
const CAP_OPEN = 2; // open adoptions per adopter
|
||||
// How many people an adopter may hold from the tank AT ONE TIME (Marty 2026-11-11, for the ~1,200 BTC4Hits imports, 6 then 10 the same day; was 2 open
|
||||
// adoptions): open adoptions whose person has not switched payouts on yet (no member id). Activating frees the slot at once; the
|
||||
// 7-day window closes the rest as before. Site setting tankAdoptCap, default 10.
|
||||
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; }
|
||||
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)
|
||||
@@ -67,7 +72,7 @@ const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Numbe
|
||||
const impl = () => db.enabled() ? D : J;
|
||||
|
||||
let ads = null;
|
||||
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; ads = opts.ads || null; if (opts.site) siteUrl = opts.site; follow = opts.follow || null; store = opts.store || null; J.load();
|
||||
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; ads = opts.ads || null; if (opts.site) siteUrl = opts.site; follow = opts.follow || null; store = opts.store || null; if (opts.capOpen) capFn = opts.capOpen; J.load();
|
||||
hooks = opts.hooks || {}; RS.st = null; RS.load(); }
|
||||
// every sponsor change the tank makes is deliberate: recorded (when, how, the sponsor before) so it follows to LinkSpin
|
||||
// until the member is bound on a contract (sponsorfollow.js). Without the follow glue (tests) it is a plain write.
|
||||
@@ -81,14 +86,35 @@ const countAll = async email => (await impl().countFor(email)) + remoteCount(ema
|
||||
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
||||
const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email));
|
||||
const inTank = a => !a.sponsorRef && !a.memberId; // arrived with no sponsor (or fell back), still free
|
||||
// Rule 3 (Marty 2026-11-14): never offer anyone locked on ANY network contract or whom the network hub already knows a sponsor
|
||||
// for (hooks.networkHeld = hubsync.heldAmong, wired only with HUB_ENABLED). A hook that throws holds everyone it was asked
|
||||
// about: the conservative side. No hook (flag off, tests) = nothing held, the tank as before.
|
||||
const lc = v => String(v || '').trim().toLowerCase();
|
||||
async function heldSet(accts) {
|
||||
if (!hooks.networkHeld || !accts.length) return new Map();
|
||||
try { return (await hooks.networkHeld(accts)) || new Map(); } catch (e) { console.error('tank networkHeld', e.message); return new Map(accts.map(a => [lc(a.email), 'unknown'])); }
|
||||
}
|
||||
// release / rescue / expiry: 'locked' | 'unknown' | null (hooks.networkLocked = hubsync.lockedAnywhere)
|
||||
const HELD_WHY = { locked: 'they are locked on a network contract', sponsored: 'it already knows a sponsor for them', unknown: 'nothing (it is not answering)' };
|
||||
async function lockedWhy(email) {
|
||||
if (!hooks.networkLocked) return null;
|
||||
try { return (await hooks.networkLocked(email)) || null; } catch (e) { return 'unknown'; }
|
||||
}
|
||||
|
||||
// waiting list: newest sign-in first so a live one is easy to spot
|
||||
async function waiting() {
|
||||
const all = await accounts.listAll(5000);
|
||||
const rows = all.filter(a => inTank(a) && !remoteOpen(a.email)); // one network tank: someone adopted on LinkSpin is not waiting here
|
||||
// one network tank (Marty 2026-11-14: the InstantAdPay and LinkSpin tanks should show the same people): waiting accounts that
|
||||
// never signed in here (BTC4Hits and LinkSpin arrivals) count too, as on LinkSpin; quiet accounts the hub made (joinedVia
|
||||
// 'hub') count too since 2026-11-14 (Marty: the unsponsored old VBB / Downline Banners members go into the holding tank; adopting
|
||||
// one sends the normal adoption email). Rule 3 still keeps out anyone the hub reports locked or sponsored. The weekly email
|
||||
// only counts the tank, it never mails it.
|
||||
const all = await accounts.listAll(1e6, { shells: true });
|
||||
const cand = all.filter(a => inTank(a) && !remoteOpen(a.email)); // one network tank: someone adopted on LinkSpin is not waiting here
|
||||
const held = await heldSet(cand); const rows = cand.filter(a => !held.has(lc(a.email))); // rule 3: locked or sponsored elsewhere
|
||||
// what each of them has earned by surfing on their own, no sponsor (Marty, 2026-09-29), so an adopter can spot the workers
|
||||
const tot = ads && ads.earnedTotals ? await ads.earnedTotals(rows.map(a => a.email)) : {};
|
||||
return rows.map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0,
|
||||
via: a.joinedVia || null, // the door they came in by (the 5xYourTeam draft card shows it)
|
||||
wallet: !!a.address, activated: !!a.memberId, // in the tank "activated" is always false (payouts on = out of the tank); wallet can still be linked
|
||||
earned: (tot[a.email] || {}).earned || 0, balance: (tot[a.email] || {}).balance || 0,
|
||||
// wallet linked = ready to switch on payouts, held for an adopter (24-hour clock, autoAssign after that)
|
||||
@@ -109,8 +135,27 @@ 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);
|
||||
if (open.length >= CAP_OPEN) return { ok: false, reason: 'You have ' + CAP_OPEN + ' open adoptions. Help one of them link a wallet or buy, and a slot frees up.', full: true };
|
||||
const open = await impl().open(a.email); const held = await holding(open); 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 };
|
||||
}
|
||||
|
||||
// 5xYourTeam coaches (Marty 2026-11-15: "not a fan of people adopting if they have nothing vested"; a $10 5x position qualifies,
|
||||
// no IAP $20 package needed). draftpartner.js has already checked the signed claim from 5xYourTeam (p.positions); this is the
|
||||
// InstantAdPay side of the same gate: a real account here with a wallet linked, not suspended or flagged, someone on THIS
|
||||
// contract in their line (them or an upline with payouts on, else a pick who starts here would be walked up to the company, the
|
||||
// one thing the tank exists to stop; the nameSponsor rule), and room under the same people-held-at-once cap as every adopter.
|
||||
async function partnerEligibility(email, p) {
|
||||
const a = await accounts.byEmail(email);
|
||||
if (!a) return { ok: false, code: 'coach_unknown', reason: 'This coach has no InstantAdPay account yet. Sign in on InstantAdPay once (network sign-in) and link the same wallet.' };
|
||||
if (!(Number(p && p.positions) >= 1)) return { ok: false, code: 'not_vested', reason: 'Only 5xYourTeam position holders can draft and coach.' };
|
||||
if (!a.address) return { ok: false, code: 'no_wallet', reason: 'Link a wallet on InstantAdPay first. A coach needs a linked wallet.' };
|
||||
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: '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 };
|
||||
return { ok: true, account: a, open };
|
||||
}
|
||||
|
||||
@@ -122,37 +167,47 @@ async function view(email) {
|
||||
const a = await accounts.byEmail(ad.adoptee);
|
||||
mine.push({ id: ad.id, name: a ? nameOf(a) : mask(ad.adoptee), email: ad.adoptee, ts: ad.ts, expires: ad.expires, lastSeen: a ? (a.lastSeen || 0) : 0, wallet: !!(a && a.address), address: (a && a.address) || null, bought: !!(a && a.memberId) });
|
||||
}
|
||||
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, graceHours: GRACE_MS / 3600000, waiting: await waiting(), mine };
|
||||
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, graceHours: GRACE_MS / 3600000, waiting: await waiting(), mine };
|
||||
}
|
||||
|
||||
async function adopt(adopterEmail, who, note, opts) {
|
||||
const auto = !!(opts && opts.auto); // the 24-hour safety net (autoAssign): same path, a different record note, both sides emailed
|
||||
// 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 e = String(adopterEmail || '').toLowerCase();
|
||||
const el = await eligibility(e);
|
||||
if (!el.ok) return { error: el.reason };
|
||||
const el = partner ? await partnerEligibility(e, partner) : 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(/^@/, '');
|
||||
const list = await waiting();
|
||||
const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key);
|
||||
if (!target) return { error: 'That member is no longer in the tank.' };
|
||||
if (target.email === e) return { error: 'That is you.' };
|
||||
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()) + '.' }; // 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.' };
|
||||
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' }; // the safety net never leaves anyone to the company
|
||||
if (!target) return { error: 'That member is no longer in the tank.', code: 'gone' };
|
||||
if (target.email === e) return { error: 'That is you.', code: 'self' };
|
||||
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) { // 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');
|
||||
if (r.error) return r;
|
||||
const now = Date.now();
|
||||
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + '. You joined InstantAdPay without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.');
|
||||
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, status: 'open', note: (opts && opts.recordNote) || text });
|
||||
const tgt0 = await accounts.byEmail(target.email); const b4h = !!(tgt0 && (tgt0.joinedVia === 'btc4hits' || tgt0.joinedRef === 'btc4hits')); // a BTC4Hits import (2026-11-11)
|
||||
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + (partner ? ', your coach from 5xYourTeam' : '') + '. ' + (b4h ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor, so I picked you up from the holding tank' + (partner ? ' in The Draft' : '') + '. I will walk you through the first three steps whenever you are ready. Reply here.');
|
||||
const ttl = partner && Number(partner.ttlMs) > 0 ? Number(partner.ttlMs) : TTL_MS;
|
||||
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + ttl, status: 'open', note: (opts && opts.recordNote) || text });
|
||||
{ const rr = RS.load().ready[target.email]; if (rr && !rr.done) { rr.done = now; rr.adoptedBy = e; RS.save(); } } // the hold lifts: their sponsor resolves now
|
||||
payTrack(target.email, e, ad.id, auto); // switch-on-payouts reminders at 24 h and 72 h (payTick)
|
||||
if (!partner) payTrack(target.email, e, ad.id, auto); // switch-on-payouts reminders at 24 h and 72 h (payTick); a draft pick gets the adoption email only (Marty 2026-11-15)
|
||||
const link = activateLink();
|
||||
try { await messages.sendChat(me.memberId || 0, e, target.email, text + '\n\n' + chatPayLine(link)); } catch (err) {}
|
||||
if (mailer && mailer.hasKey()) {
|
||||
try {
|
||||
await mailer.send(target.email, nameOf(me) + ' is now your sponsor on InstantAdPay',
|
||||
'You joined InstantAdPay without a sponsor. ' + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + '\n\n' + mailPayBlock(nameOf(me), link, !!target.wallet) + '\n\nReply in your member area: ' + siteUrl + '/my#messages\n\nInstantAdPay');
|
||||
(b4h ? 'BTC4Hits has closed, and your BTC4Hits account came over to InstantAdPay with the same email. ' : 'You joined InstantAdPay without a sponsor. ') + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + '\n\n' + mailPayBlock(nameOf(me), link, !!target.wallet) + '\n\nReply in your member area: ' + siteUrl + '/my#messages\n\nInstantAdPay');
|
||||
} catch (err) {}
|
||||
if (auto) {
|
||||
try {
|
||||
@@ -161,7 +216,7 @@ async function adopt(adopterEmail, who, note, opts) {
|
||||
} catch (err) {}
|
||||
}
|
||||
}
|
||||
return { ok: true, auto, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name };
|
||||
return { ok: true, auto, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name, adoptee: target.email };
|
||||
}
|
||||
|
||||
// pay it forward: give one of your own free referrals to the tank
|
||||
@@ -172,6 +227,8 @@ async function release(ownerEmail, directEmail) {
|
||||
const toks = [owner.code, owner.username, owner.memberId ? String(owner.memberId) : null].filter(Boolean).map(String);
|
||||
if (!toks.includes(String(direct.sponsorRef || ''))) return { error: 'That member is not in your line.' };
|
||||
if (direct.memberId) return { error: 'That member has already bought; on-chain sponsorship cannot move.' };
|
||||
const lk = await lockedWhy(d); // rule 3: someone a network contract holds never goes to the tank
|
||||
if (lk) return { error: lk === 'locked' ? nameOf(direct) + ' is locked to a sponsor on a network contract, so they cannot go to the holding tank.' : 'The network record for ' + nameOf(direct) + ' cannot be checked right now. Try again in a few minutes.' };
|
||||
// picked up from the tank recently? then it is not theirs to drop yet (Bradley churned three in 80 seconds, 2026-09-13)
|
||||
const openAds = (await impl().open(null)).filter(ad => ad.adoptee === d);
|
||||
let young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS);
|
||||
@@ -198,10 +255,14 @@ 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)
|
||||
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; }
|
||||
if (await impl().countFor(ad.adoptee) >= MAX_ADOPTIONS) { await impl().setStatus(ad.id, 'expired'); kept++; continue; }
|
||||
const lk = await lockedWhy(ad.adoptee); // rule 3: a person a network contract holds stays with the adopter, never back in the tank
|
||||
if (lk === 'unknown') continue; // the hub is not answering: try again next hour
|
||||
if (lk === 'locked') { await impl().setStatus(ad.id, 'expired'); kept++; continue; }
|
||||
await setSponsor(ad.adoptee, '', 'expire', 'adoption window ended');
|
||||
await impl().setStatus(ad.id, 'expired'); back++;
|
||||
}
|
||||
@@ -266,11 +327,14 @@ async function markContacted(sponsorEmail, leadEmail) {
|
||||
async function rescueSweep() {
|
||||
const now = Date.now();
|
||||
let warned = 0, rescued = 0, dead = 0;
|
||||
for (const a of await accounts.listAll(5000)) {
|
||||
const all = await accounts.listAll(5000);
|
||||
await heldSet(all.filter(a => !a.memberId && !a.address && a.sponsorRef)); // one batched hub call warms the cache for lockedWhy below
|
||||
for (const a of all) {
|
||||
if (a.memberId || a.address || !a.sponsorRef) continue; // bound, wallet, or already in the tank
|
||||
if (await impl().hasRecord(a.email)) continue; // adopted / rescued before: the tank's window rules
|
||||
const pv = store && store.get(a.email);
|
||||
if (remoteCount(a.email) || (pv && pv.by !== 'admin')) continue; // adopted / released / rescued on LinkSpin: the tank's window rules there
|
||||
if (await lockedWhy(a.email)) continue; // rule 3: locked on a network contract (or the hub is not answering): no warning, no move
|
||||
const sp = await sponsorOf(a);
|
||||
if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day
|
||||
if (now - (a.created || 0) < 86400000) continue;
|
||||
@@ -379,7 +443,7 @@ async function previousSponsors(email) {
|
||||
async function alignToNetwork(a) {
|
||||
if (!a || !inTank(a) || !hooks.network) return null;
|
||||
const e = String(a.email || '').toLowerCase(); if (!e) return null;
|
||||
const n = hooks.network(e, a.address || null); if (!n || !n.sponsorEmail) return null;
|
||||
const n = await Promise.resolve(hooks.network(e, a.address || null)).catch(() => null); if (!n || !n.sponsorEmail) return null; // the hub's answer is async
|
||||
const spEmail = String(n.sponsorEmail).toLowerCase(); if (spEmail === e) return null;
|
||||
if ((await previousSponsors(e)).has(spEmail)) return null; // never back to someone they were released or rescued from
|
||||
const sp = await accounts.byEmail(spEmail);
|
||||
@@ -390,7 +454,7 @@ async function alignToNetwork(a) {
|
||||
for (let i = 0; cur && i < 60; i++) { if (cur.email === e || seen.has(cur.email)) return null; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
|
||||
const fresh = await accounts.byEmail(e); if (!fresh || !inTank(fresh)) return null;
|
||||
const r = await accounts.setSponsorRef(e, token); if (r && r.error) return null;
|
||||
const st = RS.load(); const why = 'aligned to network sponsor ' + nameOf(sp) + ' from LinkSpin (' + (n.via || 'email') + ')';
|
||||
const st = RS.load(); const why = 'aligned to network sponsor ' + nameOf(sp) + (/hub/.test(n.via || '') ? ' (' + n.via + ')' : ' from LinkSpin (' + (n.via || 'email') + ')');
|
||||
st.aligned.push({ email: e, to: sp.email, toName: nameOf(sp), via: n.via || 'email', at: clock(), why });
|
||||
if (st.aligned.length > 300) st.aligned = st.aligned.slice(-300);
|
||||
if (st.ready[e] && !st.ready[e].done) { st.ready[e].done = clock(); st.ready[e].aligned = sp.email; }
|
||||
@@ -441,16 +505,22 @@ async function autoAssignRun() {
|
||||
due.push([e, rec, a]);
|
||||
}
|
||||
due.sort((x, y) => x[1].readyAt - y[1].readyAt);
|
||||
const netHeld = await heldSet(due.map(x => x[2]));
|
||||
let pool = null;
|
||||
for (const [e, rec, a] of due) {
|
||||
if (netHeld.has(e)) { // rule 3: never auto-assigned; the admin hears once (their network sponsor has no usable account here yet, or the hub is not answering)
|
||||
out.held++;
|
||||
if (!rec.networkHeldAlerted) { rec.networkHeldAlerted = clock(); RS.save(); if (hooks.adminAlert) { try { await hooks.adminAlert(BRAND + ' holding tank: ' + nameOf(a) + ' (' + e + ') is held and NOT auto-assigned: the network hub says ' + (HELD_WHY[netHeld.get(e)] || netHeld.get(e)) + ', and that sponsor could not be used here. Set their sponsor in Admin if it should be someone here.'); } catch (err) {} } }
|
||||
continue;
|
||||
}
|
||||
if (!pool) pool = await rotation(e);
|
||||
let done = null;
|
||||
for (const c of pool) {
|
||||
if (c.a.email === e) continue;
|
||||
if ((await impl().open(c.a.email)).length >= CAP_OPEN) continue;
|
||||
if ((await holding(await impl().open(c.a.email))).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) + '. 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.';
|
||||
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.';
|
||||
const r = await adopt(c.a.email, a.username || e, msg, { auto: true, recordNote: 'auto-assigned after 24 hours in the tank' });
|
||||
if (r && r.ok) { done = { adoptee: e, adopter: c.a.email, adopterName: r.adopterName, adopteeName: r.adopteeName }; break; }
|
||||
}
|
||||
@@ -464,7 +534,7 @@ async function autoAssignRun() {
|
||||
out.held++;
|
||||
if (!rec.noAdopterAlerted) {
|
||||
rec.noAdopterAlerted = clock(); RS.save();
|
||||
if (hooks.adminAlert) { try { await hooks.adminAlert('InstantAdPay holding tank: ' + nameOf(a) + ' (' + e + ') linked a wallet ' + Math.round((now - rec.readyAt) / 3600000) + ' hours ago and nobody is eligible to take them (own $20+ package, fewer than ' + CAP_OPEN + ' open adoptions, signed in within 7 days, not suspended or on a no-payout chain). They stay on hold, never under the company. Adopt them from My line > Holding tank, or set their sponsor in Admin.'); } catch (err) {} }
|
||||
if (hooks.adminAlert) { try { await hooks.adminAlert('InstantAdPay holding tank: ' + nameOf(a) + ' (' + e + ') linked a wallet ' + Math.round((now - rec.readyAt) / 3600000) + ' hours ago and nobody is eligible to take them (own $20+ package, fewer than ' + capOpen() + ' tank members held, signed in within 7 days, not suspended or on a no-payout chain). They stay on hold, never under the company. Adopt them from My line > Holding tank, or set their sponsor in Admin.'); } catch (err) {} }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -475,10 +545,12 @@ async function autoAssignRun() {
|
||||
// run the safety net. `fresh` = members who became ready and were not announced yet (server.js posts them).
|
||||
async function readyTick() {
|
||||
const st = RS.load(); const fresh = []; let aligned = 0;
|
||||
for (const a of await accounts.listAll(5000)) {
|
||||
if (!inTank(a)) continue;
|
||||
const tankers = (await accounts.listAll(5000)).filter(inTank);
|
||||
const netHeld = await heldSet(tankers); // one batched hub call; alignToNetwork below reads the same cache
|
||||
for (const a of tankers) {
|
||||
if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; }
|
||||
if (remoteOpen(a.email)) continue;
|
||||
if (netHeld.has(lc(a.email))) continue; // rule 3: not announced, no 24-hour clock while the network holds them
|
||||
const rec = markReady(a);
|
||||
// linkedNow: the member was on the site when they became ready, so they linked the wallet just now; otherwise the
|
||||
// wallet predates this tank visit (e.g. a dormant member returned by a sponsor; Marty 2026-10-29: the notice read as a
|
||||
@@ -635,11 +707,16 @@ async function nameSponsor(email, who, opts) {
|
||||
return { ok: true, name: nameOf(sp), sponsorEmail: sp.email, member: name };
|
||||
}
|
||||
|
||||
// the open adoptions of one person (draftpartner.js checks a pick's adoption is still the open one), and closing one
|
||||
async function openOf(email) { const e = String(email || '').toLowerCase(); return (await impl().open(null)).filter(ad => ad.adoptee === e); }
|
||||
async function closeAdoption(id, status) { await impl().setStatus(id, status); }
|
||||
|
||||
async function adminView() {
|
||||
const recent = await impl().recent(200);
|
||||
const names = {};
|
||||
for (const ad of recent) for (const em of [ad.adoptee, ad.adopter]) if (!(em in names)) { const a = await accounts.byEmail(em); names[em] = a ? nameOf(a) : em; }
|
||||
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
|
||||
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 = { 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, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
|
||||
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,
|
||||
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 };
|
||||
|
||||
Reference in New Issue
Block a user