Compare commits
35 Commits
1a13f53b9c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| f4e54b7243 | |||
| d322971d7d | |||
| 543bdefda2 | |||
| 8ae98be870 | |||
| 7ca7514c42 | |||
| 50bd2e3557 | |||
| 1d5dd057e0 | |||
| 68825e694e | |||
| 66581fb621 | |||
| d662a382ac | |||
| 0b45058b6a | |||
| d86ab29302 | |||
| f8f05e22b5 | |||
| 52f0a5496b | |||
| e57efd9e7c | |||
| f000dfc7e4 | |||
| 0e4e744fe7 | |||
| 2c39ef5e40 | |||
| 3213cdfa0b | |||
| 0d91ab87d9 | |||
| 8c9d72a768 | |||
| f1c8ba33c8 | |||
| c65e57dadc | |||
| d471a5664d | |||
| 218bb10145 | |||
| 72160c6a10 | |||
| 71e2e2b487 | |||
| 78bf53c48e | |||
| 7e113f055d | |||
| 94067cf000 | |||
| 8e6b5674ae | |||
| ade472cbc8 | |||
| 0e031f477e | |||
| 027107b0fd | |||
| ccfaacc935 |
@@ -160,7 +160,7 @@ const J = {
|
||||
return Object.values(this.db.byEmail)
|
||||
.filter(a => set.has(String(a.sponsorRef || '')))
|
||||
.sort((a, b) => b.created - a.created)
|
||||
.slice(0, 200).map(pub);
|
||||
.slice(0, 2000).map(pub);
|
||||
},
|
||||
async linkWallet(e, a) {
|
||||
const acct = this.db.byEmail[e];
|
||||
@@ -329,7 +329,7 @@ const D = {
|
||||
const clean = refs.filter(Boolean).map(String);
|
||||
if (!clean.length) return [];
|
||||
const rows = await db.q('SELECT * FROM accounts WHERE sponsor_ref IN (' + clean.map(() => '?').join(',')
|
||||
+ ') ORDER BY created DESC LIMIT 200', clean);
|
||||
+ ') ORDER BY created DESC LIMIT 2000', clean);
|
||||
return rows.map(rowPub);
|
||||
},
|
||||
async linkWallet(e, a) {
|
||||
@@ -501,14 +501,20 @@ async function sponsorOf(email) {
|
||||
let s = null;
|
||||
try { s = await byCode(ref); } catch (e) {}
|
||||
if (!s) { try { s = await byUsername(ref); } catch (e) {} }
|
||||
if (!s && /^\d+$/.test(ref)) { try { s = await byMemberId(Number(ref)); } catch (e) {} }
|
||||
if (!s && /^\d+$/.test(ref)) { try { s = await impl().byMemberId(Number(ref)); } catch (e) {} } // a numeric ref is a member id; byMemberId exists only on the exports object, so the bare name threw and was swallowed (2026-11-17)
|
||||
return s || null;
|
||||
}
|
||||
// is `memberEmail` anywhere in `sponsorEmail`'s downline (to `depth` levels)?
|
||||
// walks UP from the member through their sponsors (exact and uncapped): the old walk down the sponsor's line read
|
||||
// listByReferrer, which returns the newest directs only, so a big sponsor could not message an older direct (2026-11-17)
|
||||
async function isDownlineOf(sponsorEmail, memberEmail, depth = 3) {
|
||||
const target = String(memberEmail || '').toLowerCase();
|
||||
const levels = await downline(sponsorEmail, depth);
|
||||
return levels.some(L => L.members.some(m => String(m.email || '').toLowerCase() === target));
|
||||
const want = String(sponsorEmail || '').toLowerCase(); let cur = String(memberEmail || '').toLowerCase();
|
||||
if (!want || !cur || want === cur) return false;
|
||||
for (let i = 0; i < depth; i++) {
|
||||
const s = await sponsorOf(cur); if (!s || !s.email) return false;
|
||||
const e = String(s.email).toLowerCase(); if (e === want) return true; if (e === cur) return false; cur = e;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
async function getChatSettings(email) {
|
||||
const a = await byEmail(email);
|
||||
|
||||
@@ -26,7 +26,10 @@ function rates() {
|
||||
try { saved = JSON.parse(fs.readFileSync(RATES_FILE(), 'utf8')); } catch (e) {}
|
||||
return Object.assign({
|
||||
bannerBatch: 10, bannerCreditsPerBatch: 2,
|
||||
textBatch: 10, textCreditsPerBatch: 1,
|
||||
// TEXT ADS ON-SITE (Marty, 2026-11-20): 1 credit per 100 views (was 1 per 10). Text ads draw clicks at the same rate
|
||||
// here and on Network Ad Space (about 1 per 2,500 views), so the on-site price now matches the network one and a text
|
||||
// click costs about the same wherever it comes from. Going forward only, like the 10-27 and 11-12 changes.
|
||||
textBatch: 100, textCreditsPerBatch: 1,
|
||||
// Login ads are a flat slot buy: one price, 30 days, unlimited impressions, no
|
||||
// delivery guarantee. Same total as the old 100/day x 30, but with a known end and
|
||||
// no daily drain against inventory that may not exist that day.
|
||||
@@ -99,7 +102,9 @@ function rates() {
|
||||
// TEXT ADS (Marty, 2026-11-12): Network Ad Space shows text ads in huge volume for very few clicks (about 1 per 4,000
|
||||
// views), so text budgets were gone in about a week. Text network views cost 1/synRateDivisorText of the on-site rate
|
||||
// instead (1 credit = 100 network views). Banners keep synRateDivisor. Going forward only, like the 10-27 change.
|
||||
synRateDivisorText: 10
|
||||
// 2026-11-20: on-site text moved to the same 100 views per credit, so text is one price everywhere: the divisor is 1
|
||||
// and nas.impressionsPerCredit('text') is 100 (network text stays 1 credit = 100 views, nothing changes there).
|
||||
synRateDivisorText: 1
|
||||
}, saved);
|
||||
}
|
||||
function setRates(patch) {
|
||||
@@ -1818,7 +1823,7 @@ async function reconcileNas() {
|
||||
// whole credits as they accrue: the cumulative served count carries the fraction, so nothing is lost or double-charged
|
||||
const creditsDue = Math.floor(st.served / ipc) - Math.floor(prev / ipc);
|
||||
if (creditsDue > 0) {
|
||||
const res = await chargeCredits(c.id, creditsDue, { net: 'Network views (1/' + synDiv(c.type) + ' rate)' });
|
||||
const res = await chargeCredits(c.id, creditsDue, { net: synDiv(c.type) > 1 ? 'Network views (1/' + synDiv(c.type) + ' rate)' : 'Network views' });
|
||||
charged = res.charged || 0;
|
||||
if (res.exhausted) { exhausted = true; await setNasServed(c.id, st.served); await stopNas(c.id, c.nasAdId); }
|
||||
}
|
||||
|
||||
@@ -58,7 +58,9 @@ const J = {
|
||||
this.sessions.set(token, Object.assign({}, s, fields));
|
||||
this.save();
|
||||
},
|
||||
async drop(token) { this.sessions.delete(token); this.save(); }
|
||||
async drop(token) { this.sessions.delete(token); this.save(); },
|
||||
async renew(token) { const s = this.sessions.get(token); if (!s) return; s.expires = Date.now() + SESSION_TTL; s.issued = Date.now(); this.save(); },
|
||||
async dropBy(email, address) { let n = 0; for (const [t, s] of this.sessions) if ((email && s.email === email) || (address && String(s.address || '').toLowerCase() === address)) { this.sessions.delete(t); n++; } if (n) this.save(); return n; }
|
||||
};
|
||||
|
||||
// ---- MySQL session mode ----
|
||||
@@ -84,7 +86,9 @@ const D = {
|
||||
vals.push(token);
|
||||
await db.q('UPDATE sessions SET ' + sets.join(',') + ' WHERE token=?', vals);
|
||||
},
|
||||
async drop(token) { await db.q('DELETE FROM sessions WHERE token=?', [token]); }
|
||||
async drop(token) { await db.q('DELETE FROM sessions WHERE token=?', [token]); },
|
||||
async renew(token) { await db.q('UPDATE sessions SET expires=? WHERE token=?', [Date.now() + SESSION_TTL, token]); },
|
||||
async dropBy(email, address) { const r = await db.q('DELETE FROM sessions WHERE ' + (email && address ? 'email=? OR LOWER(address)=?' : email ? 'email=?' : 'LOWER(address)=?'), [email, address].filter(Boolean)); return Number(r.affectedRows || 0); }
|
||||
};
|
||||
const impl = () => db.enabled() ? D : J;
|
||||
|
||||
@@ -143,7 +147,7 @@ async function verifyChallenge(address, signature) {
|
||||
async function mintSession(fields) { return impl().mint(fields || {}); }
|
||||
async function updateSession(token, fields) { return impl().update(token, fields || {}); }
|
||||
function sessionCookie(token) {
|
||||
return `iap.sid=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL / 1000}${IS_PROD ? '; Secure' : ''}`;
|
||||
return `iap.sid=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.max(SESSION_TTL / 1000, 30 * 86400)}${IS_PROD ? '; Secure' : ''}`; // the cookie outlives the session; the server's sliding expiry decides (2026-11-15)
|
||||
}
|
||||
function clearCookie() { return 'iap.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
|
||||
// onSeen (2026-10-26): told the email + request of every resolved session (conversion tracking keeps the soft keys a member
|
||||
@@ -153,6 +157,9 @@ async function fromRequest(req) {
|
||||
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
|
||||
if (!m) return null;
|
||||
const s = await impl().get(decodeURIComponent(m[1]));
|
||||
// renewed on use (2026-11-15, the network hub era: sessions are SESSION_TTL_HOURS long, 168 = 7 days, and slide while the member
|
||||
// is active; the login ad keeps its own clock, loginadclock.js). At most one write an hour per session.
|
||||
if (s && Number(s.expires) && Number(s.expires) - Date.now() < SESSION_TTL - Math.min(3600000, SESSION_TTL / 4)) { try { await impl().renew(s.token || decodeURIComponent(m[1])); } catch (e) {} }
|
||||
if (s && s.email && seenFn) { try { seenFn(s.email, req); } catch (e) {} }
|
||||
return s;
|
||||
}
|
||||
@@ -177,4 +184,5 @@ async function logout(req) {
|
||||
if (s) await impl().drop(s.token);
|
||||
}
|
||||
|
||||
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, onSeen, refreshMemberId, logout };
|
||||
async function endSessions(email, address) { return impl().dropBy(email ? String(email).toLowerCase() : null, address ? String(address).toLowerCase() : null); } // hub: blocked, erased, signed out everywhere
|
||||
module.exports = { endSessions, init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, onSeen, refreshMemberId, logout };
|
||||
|
||||
@@ -110,7 +110,7 @@ function head(o) {
|
||||
+ '</head><body><div class="wrap bl">';
|
||||
}
|
||||
function tail() {
|
||||
return '</div><script src="/assets/common.js?v=20261115nr"></script><script src="/assets/blog-page.js?v=20261101th"></script></body></html>';
|
||||
return '</div><script src="/assets/common.js?v=20261117nw"></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>';
|
||||
|
||||
@@ -24,7 +24,10 @@ let HERO_SALE = null; // () => gamepass.cfg().heroes + names (server.js): the bo
|
||||
let PASS_TIERS = null; // () => the live pass tiers (server.js, from gamepass.cfg): the tier fact follows the sovTiers switch
|
||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||
|
||||
// Network Weekend (2026-11-17, promodays.js): a date-gated fact and answer; empty outside the window, so nothing to undo after it
|
||||
let WEEKEND = null;
|
||||
function init(opts) {
|
||||
WEEKEND = opts && opts.weekend && typeof opts.weekend.fact === 'function' ? opts.weekend : null;
|
||||
if (opts && typeof opts.gameLive === 'function') GAME_LIVE = opts.gameLive;
|
||||
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn;
|
||||
if (opts && typeof opts.bixLive === 'function') BIX_LIVE = opts.bixLive; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; HERO_SALE = typeof opts.heroSale === 'function' ? opts.heroSale : null; const ready = kb.init({ dataDir: DATA_DIR, seeds: seeds() });
|
||||
@@ -47,13 +50,13 @@ function key() {
|
||||
function enabled() { return !!key(); }
|
||||
|
||||
// ---- canned answers: instant, free, always in voice ----
|
||||
const KNOWLEDGE_DATE = '2026-11-15'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const KNOWLEDGE_DATE = '2026-11-23'; // 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.' },
|
||||
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 sign-in now lasts 7 days on each site and renews while you use it; the login sponsor ad still shows every few hours. 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'],
|
||||
@@ -151,7 +154,7 @@ const CANNED = [
|
||||
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.' },
|
||||
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. Video App Income (short promo videos made from a topic) was added to this tab on 2026-11-23, with banners in web and social sizes, lines, headlines, an email and posts.' },
|
||||
{ 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.' },
|
||||
@@ -172,9 +175,9 @@ const CANNED = [
|
||||
a: 'A login ad is your page shown full screen to members right after they sign in, on the dashboard and in the connected games. A slot is a flat buy: 1,000 purchased credits for 30 days of unlimited sign-in impressions, paid once up front and never charged per day. Earned credits cannot pay for it. Up to 6 member slots run at once, because they all share the same sign-ins. When all 6 are taken you can reserve the next slot in Members > Campaigns: you pay the same price now, and your place in line is first paid, first served. Your 30 days only start when your turn comes, and the form shows your place and an estimated start date in Central time. That date is an estimate, because a slot can end early if its owner archives it. When your ad starts you get a notice on site and an email. Until it starts you can edit the link, image or headline for free, or cancel it and get every credit back. Once it has started, normal slot rules apply. A freed slot always goes to the line first, so a paused slot can only be resumed when a slot is open with nobody waiting.' },
|
||||
// 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being
|
||||
// signed out, and the honest answer reads far better than letting it look like a fault.
|
||||
{ id: 'session-4h', title: 'Why am I signed out after 4 hours?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'],
|
||||
{ id: 'session-4h', title: 'How long does a sign-in last?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'],
|
||||
re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i,
|
||||
a: 'That is deliberate, not a fault. To keep resources optimised we do not keep anyone signed in longer than 4 hours. After that your session ends and you sign in again with a fresh code - nothing about your account, your credits or your line is affected. You will see the login sponsor ad on the way back in, and that is part of what keeps the free side of the platform paid for.' },
|
||||
a: 'A sign-in lasts 7 days and renews while you use the site, and signing in on any network site signs you in on the others. If you are signed out, sign in again with a fresh code or open the site from another network site you are signed in on - nothing about your account, your credits or your line is affected. The login sponsor ad shows again every few hours whether or not you signed in; that is part of what keeps the free side of the platform paid for. Signing out on a site signs you out of that site only; Sign out everywhere ends it on every network site.' },
|
||||
{ id: 'one-account', title: 'One account per person', q: ['Can I open a second account?', 'Can my wife have an account?', 'Can I refer myself?'], tags: ['account', 'second account', 'duplicate', 'terms', 'qualified start'],
|
||||
re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i,
|
||||
a: 'One account per person, and that is in the Terms (https://instantadpay.com/terms). A second account under another email, name or wallet is not allowed, and neither is referring yourself through one. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, on the Buy packages tab, where they are visible as yours. A family member who genuinely wants to join can join under your link with their own email. Duplicate accounts can be merged or closed and any credits or prizes earned through them are forfeited; payments the contract already made cannot be reversed.' },
|
||||
@@ -191,7 +194,7 @@ const CANNED = [
|
||||
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 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 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.' },
|
||||
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 are one price everywhere since November 20: 1 credit buys 100 text ad views, here or on the network (text ads get clicked about as often in both places, so a click costs about the same wherever it comes from). 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 for banners and "Network views" lines for text ads in Credit activity (older text lines say "Network views (1/10 rate)").' },
|
||||
{ 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.' },
|
||||
@@ -211,6 +214,15 @@ const CANNED = [
|
||||
{ id: 'pif', title: 'Pay it forward (PIF)', q: ['How do I PIF someone?', 'Can I buy a package for my referral?', 'Should I fund someone from the tank?'], tags: ['pif', 'pay it forward', 'gift', 'holding tank'],
|
||||
re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i,
|
||||
a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' },
|
||||
{ id: 'socialtube-earn', title: 'Earning credits by watching on Social Tube', q: ['Can I earn credits on Social Tube?', 'What is Earn by watching on Social Tube?', 'Do Social Tube watches count toward my daily limit?'], tags: ['social tube', 'earn by watching', 'socialtube'],
|
||||
re: /(social ?tube.{0,60}\b(earn|credit|watch|paid|limit|cap)|\b(earn|credit|paid)\w*.{0,40}social ?tube)/i,
|
||||
a: 'Yes. Social Tube (socialtube.club) is a video site in the same network. Its Earn page plays the same watch-to-earn video ads you see here in Shorts and Watch videos. Sign in there with your network account, watch a video for its full time, and the credits land in your InstantAdPay balance at the same rate as watching here. InstantAdPay does the timing and the crediting, so the rules are identical: one daily limit shared between the two sites, each video pays once a day, and you are never shown your own video. Your credit activity shows those lines as Watched a video on Social Tube.' },
|
||||
{ id: 'vai-video-ad', title: 'Video App Income: the Run this on InstantAdPay button', q: ['What is the Run this on InstantAdPay button?', 'How do I advertise something I made on Video App Income here?', 'Can a Social Tube page be advertised on InstantAdPay?'], tags: ['video app income', 'social tube', 'run this on instantadpay'],
|
||||
re: /(run (this|it|my video) on instantadpay|(video app income|videoappincome|social ?tube) video.{0,40}\b(ad|advertis|campaign|promot)|\b(ad|advertis|campaign|promot)\w*.{0,40}(video app income|videoappincome|social ?tube) video)/i,
|
||||
a: 'Yes. On Video App Income, open the Share tab, find the video and tap Run this on InstantAdPay. It opens Campaigns here with a Video ad (watch to earn) already filled in: your video, its title, and your Social Tube page as the place the button leads. Nothing is bought for you. You choose the watch length and the budget and press the button yourself, and it is paid with your InstantAdPay ad credits like any other campaign. Members here are paid credits to watch it for the full time, and a tall phone-shaped video plays in Shorts. Two things to know: if you remake or delete that video on Video App Income its file changes, so pause the campaign and start a new one from the new video; and paid views are views, not sales, so nothing about results is promised.' },
|
||||
{ id: 'sponsor-video-invite', title: 'An email saying my sponsor made me a video', q: ['I got an email that my sponsor made me a video, is it real?', 'What is Video App Income?', 'How do I stop invite emails from my sponsor?'], tags: ['video app income', 'sponsor invite', 'invite email', 'made you a video'],
|
||||
re: /(made (me|you) a video|video app income|videoappincome|invite(d)? (email|from my sponsor)|email from my sponsor)/i,
|
||||
a: 'That email is real if it names your sponsor. Video App Income is another site in the network that makes short promo videos from a phone. A sponsor there can send each of their own direct referrals one invite, once, and it is delivered by InstantAdPay so it comes from an address you already know. It shows a video your sponsor made, or a short one that shows how the app works, and says plainly that they earn a share if you buy credits there. Your first video there is free, nothing is promised, and you do not have to join. Your email address was not given to your sponsor or to Video App Income: InstantAdPay sent the note on their behalf. Each person gets this invite one time only. To stop all InstantAdPay emails except sign-in codes and receipts, use the Stop these emails link at the bottom of the message. Separately: if you asked Video App Income to confirm your email, the 6-digit code arrives in an email that says it was sent by InstantAdPay, because InstantAdPay is the mail service for the network. That is expected. Type the code into Video App Income within 15 minutes; if you did not ask for it, ignore it.' },
|
||||
{ id: 'who-invited', title: 'Who invited you? (naming your sponsor)', q: ['How do I add the person who invited me?', 'I joined without a link, can I name my sponsor?', 'What is the Who invited you card?'], tags: ['who invited you', 'invited', 'holding tank', 'no sponsor', 'sponsor link'],
|
||||
re: /(who invited|invited (me|by)|joined without a (link|sponsor)|forgot (the|my|to use).{0,12}(link|sponsor)|(add|name|set|enter|pick|choose) (my |a )?sponsor|nobody invited)/i,
|
||||
a: 'If you joined without a sponsor link, your Overview shows a Who invited you? card. Type the username of the person who invited you, confirm it, and they become your sponsor, here and on LinkSpin, and they get a notice. Do it before you switch on payouts or buy, because your sponsor locks on the contract at that point. It has to be a real member: not you, not someone in your own line, and not someone who has not switched on payouts with nobody above them who has (ask them to switch on first). Once you have a sponsor or a member number the card goes away. Nobody invited you? Tap Nobody invited me and stay in the holding tank; a small link on the Overview brings the card back while you are still there. Nothing on the site waits for your answer. New sign-ups cannot be adopted by hand for their first 24 hours, so you have a day to tell us before a member can pick you up.' },
|
||||
@@ -220,6 +232,9 @@ const CANNED = [
|
||||
{ id: 'tank-activate-link', title: 'Switch on payouts after you were picked up (one-tap link)', q: ['I got a Switch on payouts link from my new sponsor', 'How do I switch on payouts after I was adopted?'], tags: ['holding tank', 'switch on payouts', 'adopted', 'one tap', 'reminder'],
|
||||
re: /((switch on|turn on|activate) payouts? (link|email|reminder)|activate=1|(picked (me )?up|adopted( me)?).*(switch on|activate)|one.?tap.*(payouts|activate)|reminder.*switch on payouts)/i,
|
||||
a: 'When a member picks you up from the holding tank (or the site assigns you to one after 24 hours), the chat and the email you get both carry a Switch on payouts link: instantadpay.com/my?activate=1#wallet. Tap it, sign in if asked, and your wallet opens with your new sponsor already filled in. It is one free transaction, no package needed, and it locks that sponsor in as yours on the contract. No wallet linked yet? The same link asks you to link one first (one free signature) and then carries on. On a phone without a wallet browser, the wallet picker opens and hands you to your wallet app to confirm. Nobody, not even the site, can switch payouts on for you: it has to come from your own wallet. If you have not done it 24 hours after you were picked up you get one reminder email (and your sponsor gets a note to give you a nudge), and one last reminder at 72 hours. They stop as soon as your payouts are on or you buy a package.' },
|
||||
{ id: 'tank-batches', title: 'Holding tank batches (coming soon)', q: ['Will the site send me people from the holding tank?', 'How do I get fed leads?', 'What are holding tank batches?'], tags: ['holding tank', 'batches', 'fed leads', 'auto-assign', 'coming soon'],
|
||||
re: /(holding tank batch|fed leads|get (fed )?leads from the (holding )?tank|batch(es)? (of people )?from the (holding )?tank)/i,
|
||||
a: 'Coming soon, not switched on yet: holding tank batches. The plan is that active members who bought their own package receive a batch of people from the holding tank every 2 days, people who joined without a sponsor and become your referrals to welcome and help. The planned ladder: your own $20 package on InstantAdPay or $25 on LinkSpin = 10 people at a time; a counted monthly refuel or a higher package ($50 or more) = 20; both engines refueled in the same cycle, or the top package = 25; then 5 more for every further refuel month in a row, up to 50. You would need to sign in at least once a week, and anyone you have not contacted within 7 days (a chat, or Contacted them on their row in My line) goes back to the tank for another member. These are leads you can sponsor, not income: what they do next depends on them and on your follow-up. Until it is switched on, adopt by hand from Members > My line > Holding tank as today, and the 24-hour safety net keeps running as it does now.' },
|
||||
{ id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'unsponsored'],
|
||||
re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/i,
|
||||
a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come once they have been here 24 hours. A new sign-up shows an Opens in badge until then, with no Adopt button, so they have a day to tell us who invited them (the 24-hour safety net for wallet-linked members still runs on its own clock). To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold up to 10 people from the tank at one time (counting the ones who have not switched on payouts yet) and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances. Members who have linked a wallet show a Ready to activate badge with the hours left and sit at the top of the list: their payouts are on hold until someone adopts them, and after 24 hours the site assigns them to the next eligible adopter in turn (own $20 package, fewer than 10 people held from the tank who have not switched on payouts yet, signed in within the last 7 days). Adopters take turns, so the one assigned least recently goes first.' },
|
||||
@@ -243,7 +258,7 @@ const CANNED = [
|
||||
a: 'InstantAdPay has light and dark themes (added 2026-11-02). In the member area use the Light, Dark or Auto control in the header, or the Appearance card on your Profile. Dark is the original look, Light is a bright green-grey workspace with the same layout, and Auto follows your device setting and switches with it. Your choice is saved on your account, so it follows you to any device once you sign in, and it applies to the public pages and your wall too. Nothing changes until you pick one. Both themes pass the accessibility contrast standard for text.' },
|
||||
{ id: 'promo-tools', title: 'Promo tools', q: ['What is in Promo tools?', 'Where are the email swipes and banners?'], tags: ['promo tools', 'social posts', 'swipes', 'banners', 'objections'],
|
||||
re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i,
|
||||
a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, an Objection handling bank with the truth plus a ready-to-send reply, and a Games tab with a kit for every network game plus the EnjoyBestGames arcade (enjoybestgames.com, hundreds of free games; only the featured Polygon games pay, and your ?r= link cookies visitors as your referral for 30 days). Everything is personalized with your invite link.' },
|
||||
a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus 600x300 wide cards and 250x250 small squares, square, story and Telegram sizes, download or copy URL), your Banner wall link, an Objection handling bank with the truth plus a ready-to-send reply, and a Games tab with a kit for every network game plus the EnjoyBestGames arcade (enjoybestgames.com, hundreds of free games; only the featured Polygon games pay, and your ?r= link cookies visitors as your referral for 30 days). Everything is personalized with your invite link.' },
|
||||
{ id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this transaction will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning', 'walletconnect'],
|
||||
re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
|
||||
a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (SafePal and most other wallets have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again.' },
|
||||
@@ -323,8 +338,8 @@ const SYN_N = () => { try { return Math.max(1, Math.floor(Number(require('./ads'
|
||||
// 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 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); }
|
||||
: '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() === 1 ? ' Text ads are one price everywhere: 1 credit buys 100 text ad views, here or on the network.' : 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 (Marty 2026-11-20): one price everywhere, 1 credit = 100 text ad views on-site AND on Network Ad Space (on-site text was 1 credit per 10 views until 2026-11-20; network text was already 1 credit per 100 views since 2026-11-12), because text ads get clicked about as often in both places; network text credit log lines now read "Network views" (older ones "Network views (1/10 rate)"); live text network divisor: ' + SYN_T() + ', 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
|
||||
@@ -369,31 +384,33 @@ function systemPrompt(kbBlock) {
|
||||
|
||||
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.
|
||||
- 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 2 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 (7 days, renewed while active), 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.
|
||||
${WEEKEND ? (() => { try { return WEEKEND.fact() || ''; } catch (e) { return ''; } })() : ''}${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.
|
||||
- HELP DESK (LIVE 2026-10-16): members open Help in the dashboard (/my#help) to send Marty a support ticket (pick a category, a subject, the message, up to 2 screenshots), see each ticket's status (Open, Waiting on you, Closed) and read and answer his replies; a badge shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at https://instantadpay.com/support (name, email, category, subject, message) and gets an email with the ticket number (like IAP-1042) and a private link to view and reply, no sign-in needed. support@instantadpay.com also reaches Marty. Replying to a closed ticket opens it again. In this chat, "Send this to support" turns the conversation into a ticket. Only Marty answers, so replies are not instant; never promise a response time.
|
||||
- PRESENTATION (2026-10-15): instantadpay.com/presentation is a public page (no sign-in) with the narrated InstantAdPay presentation, about six minutes, Marty's voice, captions in 6 languages (English, Italiano, Français, Español, Deutsch, Português) chosen with pills under the player. Sixteen parts: the platform, ad reach, the nine games that pay POL, the $20 split ($10 / $4 / $2 / $4 platform, same transaction), three rules, packages, the 2-then-5 unlock, pass-up, wide versus narrow ($800 vs $36, an illustration), Qualified Start, the Pipeline, LinkSpin (pre-launch Nov 1), one wallet across the network, the first week, and 'the target is five'. Share link: Members > Promo tools > 'Share the presentation' copies instantadpay.com/presentation?ref=<username>; ?ref sets the same 30-day sponsor cookie as the invite link, the page shows 'Shared with you by @name' with avatar and a Join button to /join/<username>. It is in the site menu as 'Presentation'. BUILD WIDE VIDEO: first card in Promo tools > Videos ('Build wide: watch the payments flow'), matched link ?v=wide.
|
||||
- WIRED WEDNESDAY: every Wednesday, Central time (midnight to midnight), any ad package of $20 or more (Activation and up; no $10 pack exists) earns +25% bonus credits wired into the buyer's balance the moment the purchase settles, purchased-grade (usable on every format incl. login ads), credit log label "Wired Wednesday". First one: Wednesday 2026-09-30. Page: instantadpay.com/wednesday. Credits buy ad delivery, never money.
|
||||
- CONVERSION LINKAGE (LIVE 2026-11-07, reporting only: it never changes sponsors, payouts, credits or anything on chain): a LinkSpin click id (lsclk or lsid in the address) arriving on any InstantAdPay page is kept 30 days in a first-party cookie (last click wins) and travels with the code request, and is stored with the account at sign-up, in-game sign-in included when the game passes it on. InstantAdPay then reports sign-up, wallet link and each package purchase (value = the USD price on the chain event, linked positions included) to LinkSpin, which counts join and wallet once per click and each purchase on its own, for the click's owner. The landing tag adds the click id to links to instantadpay.com, linkspin.app and the share domains, also inside a member's own redirect link; a spin link or Banner Spin pointed straight at those sites carries it with no goal needed. 30 days from the click to the event, same as goals. The first account on a click owns it. The click owner's own account and own clicks are never counted. People who joined before 2026-11-07 cannot be matched afterwards. Shown on the Conversion tracking card (with goals, 30 days) and in LinkSpin under Reports, Conversions.
|
||||
- CONVERSION TRACKING (LIVE 2026-10-23): Campaigns > Conversion tracking in /my#campaigns. Every click on a member's ad (through /api/ads/click) gets a click id added to the target address as lsclk=<id>; the advertiser adds a goal (name like subscriber or sale, optional default value), puts the LinkSpin landing tag (t.js) on the page the ad points to and the goal pixel (cv.gif image, or the cv.js script) on the thank-you page. LinkSpin (sister site, same email) counts the goals; matching order: click id in the address (url, surest), the id the landing tag stored (stored), LinkSpin's cookie (cookie), a 24-hour match on hashed IP plus browser (soft, least sure). Each goal counts once per click, only within 30 days of a real click, only for the pixel owner's own ads; the advertiser's own clicks (signed in, or from a browser they sign in from; their linked positions share their email so count as them too) and the Send a test conversion button count as tests, never in the numbers; the card shows 'N from your own clicks, kept as tests'. SEND A TEST CONVERSION (2026-10-26) loads the member's real LinkSpin pixel in test mode from their browser (falls back to the signed partner call if the browser blocks it), so Last test updates. Each campaign row shows goals and COST PER GOAL (30 DAYS) in credits (2026-10-26: the credits the campaign spent in the last 30 days, from the credit activity log, divided by its goals in the same 30 days; a campaign started inside the window uses its spend since start; never quote it in dollars). Autoresponder tip: set the Aweber or GetResponse thank-you (success) page to a page on the member's own site carrying the goal pixel (Aweber: Thank You Page: custom page; GetResponse: Thank-you page: custom URL); if they cannot, the cookie or the 24-hour match can still count it, less surely. Privacy: the click id is random and nothing personal is sent. SETUP GUIDE (public, 2026-10-24): https://instantadpay.com/conversion-tracking (LinkSpin's copy: https://linkspin.app/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, Last test updates, then remove it), what to do without code on the thank-you page, how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest). Send members there for any setup question.
|
||||
- FIVE DOLLAR FRIDAY: every Friday, Central time, any ad package of $5 or more earns +20% bonus credits, credited the moment the purchase settles (credit log shows the label). First one: Friday 2026-09-25. Since 2026-10-23 the same $5+ Friday package also gives a FREE 7-day Game Pass automatically (once per member per Friday; not a second week when that package itself fulfils a pass order; the Game Pass badge posts the first time). Five Fridays in a row = the Five Fridays badge. The point: the whole network buys on the same day, every pack pays its sponsor line in the same transaction, so every line gets paid at once. No income promises.
|
||||
- SESSIONS LAST 4 HOURS. Sign-ins expire after 4 hours and the member signs in again with a fresh 6-digit code. This is intentional and we say so plainly: it keeps resources optimised, and the login sponsor ad shown on the way back in is part of what pays for the free side. Nothing is lost on expiry - credits, line and account are untouched. Never describe it as a bug, an error, or something to report.
|
||||
- SESSIONS LAST 7 DAYS (since 2026-11-15) and renew while the member is active; the network hub keeps one sign-in across every network site, and Sign out everywhere ends all of them. The login sponsor ad no longer depends on signing in: it shows on the next member page once the last finished view is more than a few hours old (a site setting, 3 hours by default). That ad is part of what pays for the free side. Nothing is lost when a session ends - credits, line and account are untouched. Never describe it as a bug.
|
||||
- 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. 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.
|
||||
- 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 600x300, 250x250, 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; Video App Income kit added 2026-11-23) 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 9 or more sizes per angle (including 600x300 and 250x250), 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 SafePal or another wallet without the hard block. The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again.
|
||||
- WALL OWNERSHIP LADDER: the public wall has 3 positions. Position 1 = the member's line banner. Positions 2 and 3 show upline banners (then house ads) UNTIL the member earns them: 2 qualifying buyers ($20+) unlock position 2, 5 unlock position 3; a fully qualified member's wall is 100% their own links/offers (set in Profile > Your wall: label, https link, optional banner image). Empty unlocked slots fall back to upline banners, then house ads.
|
||||
- LINE BANNER (free, set in Profile): every member can set a destination URL (must allow framing) plus an optional banner image. It is shown to their next THREE levels of new members during welcome tours (position 1 for directs, 2, 3 below), and on their public BANNER WALL at /wall/<username> — a shareable page showing their line ladder with their join link. Free viral traffic that compounds as the team grows; no credits spent.
|
||||
- Ad packages: Micro $5/500 credits, Starter $10/1,000, Activation $20/2,000, Builder $50/5,500, Growth $100/12,000, Leader $250/32,500, Elite $500/70,000. Dollar-priced, settled in POL (Polygon) at the live Chainlink rate. 1 credit = 1 cent of ad delivery.
|
||||
- AI AD WRITER (LIVE 2026-11-17): on Advertise > create a campaign, pick Text ad, put your link in Target URL and tap "Write my ad from my link": the network ad writer reads that page and suggests 3 text ads (headline up to 60, ad text up to 140) using only what the page says (no made-up claims, numbers or income promises); tapping one fills the headline and ad text to edit; nothing is created until you create the campaign. 5 writes a day per member (reset at midnight Central); the same page again within 24 hours is free. The same writer is on ViralAdSource, ViralAdBlitz and LinkSpin.
|
||||
- Live formats: display banners (per impression), text ads (per impression), full-screen LOGIN ADS (per day: right after a member signs in they land on a sponsor interstitial — they click "Open Ad", the advertiser's page opens in a NEW tab, a countdown runs on the interstitial, and at zero a "Go to dashboard" button appears. Just a CTA link is enough; an optional banner image can be the clickable creative. No framing requirement since it opens in its own tab), WATCH-TO-EARN VIDEO ADS (advertiser uploads an MP4/WebM or gives a direct https .mp4/.webm link and picks a required watch length — 10s/30s/60s — which sets the per-view price; viewers watch in an escape-proof player under Earn credits > Watch videos, the watch time is enforced on the server clock, and they earn credits per completed watch; you never see your own videos), and solo ads. Banner ads also require a size (standard IAB sizes like 728x90, 300x250). Video watching is capped at 8 a day per member and pays 1, 2 or 4 credits for a 10, 30 or 60 second watch. FEATURED LINKS (live): a headline + link in the Featured strip at the top of every member's Overview, booked for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead, at most 10 links sharing any day; flat buy paid when booked; the row shows days left and 'runs through <date>', counts views (one per viewer per hour) and clicks, and offers Extend run. VERIFIED-VISIT PACKS (live): 3 credits per visit, minimum 20 visits, paid up front; each visit is a distinct member who opens the site in a new tab, stays 8 seconds and passes a check, at most 20 visits per member per day; the row shows 'N of M visits delivered' and Buy more visits adds to the pack; the visitor earns 1 credit.
|
||||
- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): say "SafePal or any other crypto wallet" and never recommend MetaMask by name (Marty 2026-11-13; a wallet app with several accounts serves Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase.
|
||||
- PROHIBITED CONTENT (2026-10-30, Terms section 8, /terms#prohibited): gambling, casinos, betting, lotteries, sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing, counterfeit goods; misleading financial promises. Refused at save time in bios, social links, line banners, wall offers and every campaign field. A bio may not contain a URL or a domain (links go in the social fields). Profile text, avatar and social links appear on the public wall ONLY for members who have bought a package; a free account's wall shows the name, the line's ads and the join button. Link-farm accounts (created to plant links in profile fields) are removed without notice with their profile text.
|
||||
- INTRO VIDEO ON THE WALL: Profile > social links has an "Intro video" field (YouTube, Vimeo or direct .mp4 link). It embeds on the member's public wall page (/wall/<username>) right under their bio, above the three-level line and the join button.
|
||||
- BTC4HITS (2026-11-11): members of the closed BTC4Hits rotator site with a deliverable email were imported as waiting accounts (no wallet, no password, nothing mailed), with their BTC4Hits sponsor when that sponsor was also imported or already a member; the rest join the holding tank when they first sign in. They sign in here with the same email (code sign-in), or on LinkSpin at linkspin.app/from/btc4hits, where their active rotators became spin links. Pro status and old BTC4Hits commissions do not carry over.
|
||||
- HOLDING TANK BATCHES (COMING SOON, NOT LIVE, approved in principle 2026-11-15; Marty switches it on after reviewing a preview): active members (signed in within 7 days) who bought their own $20+ package on InstantAdPay or $25+ on LinkSpin would receive a batch from the holding tank every 2 days: 10 at a time; 20 with a counted refuel streak or a higher package ($50+); 25 with both engines refueled this cycle or the top package; +5 per further consecutive refuel month, up to 50. People not contacted within 7 days go back to the tank. It is separate from the 5xYourTeam draft (its own cap) and from the hand adoptions (still max 10 held). NEVER say it is live; say it is coming soon. Leads to sponsor, never income.
|
||||
- HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; new sign-ups cannot be adopted by hand for 24 hours from sign-up (they show an Opens in badge and no Adopt button); a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 10 held at one time, counting those not yet switched on payouts, 7-day window; if the person never links a wallet or buys, they fall back into the tank; a person can be adopted twice at most). Adopting sets the sponsor, opens a chat and emails the member; their first purchase then binds to the adopter on-chain. Members can also "Release to tank" one of their own free referrals (pay it forward), but NOT someone they adopted less than 3 days ago: an adoption is a commitment, and a dropped adoption still counts toward that person's two-adoption lifetime limit. Releases are posted to the feed and Telegram like pickups. Admin sees the tank under Members.
|
||||
- WHO INVITED YOU (2026-11-07, Marty approved): a member with no sponsor and no member number sees a Who invited you? card on their Overview. They type a username, confirm in an in-page box, and that member becomes their sponsor (it follows to LinkSpin, lifts the activation hold, and the sponsor gets a new-referral email and notice). Refused: themselves, a username that does not exist, someone in their own line, a member who cannot take new members, a member with no payouts on and nobody above them on the contract, and anyone who already has a sponsor or a member number. Nobody invited me hides the card (a small Overview link brings it back while they are in the tank) and changes nothing else. It never blocks the site. It is not an adoption: no 7-day window and it does not count toward the two.
|
||||
- SIGN-UP GRACE (2026-11-07): for 24 hours from sign-up nobody can adopt a member by hand. The 24-hour auto-assign is unchanged and runs from the wallet link, so a member who links a wallet in their first hour is matched about 24 hours after linking, with at most a short hand-adoption window first. Members back in the tank later have no grace.
|
||||
@@ -463,6 +480,8 @@ ${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${w
|
||||
- Transparency: live ledger at /ledger streams every chain event, and EVERY transaction row carries a clickable "verify" link — to the public block explorer when the chain has one, or to the built-in transaction viewer at /tx/<hash> (block, time, from/to, value, gas, decoded events, read live from the node). Plain-language contract review at /contract; the verified source is public.
|
||||
- The contract cannot be paused, upgraded, or drained. The operator can only manage the ad catalog ($1-$500 bounds, 24h price timelock) and rotate keys.
|
||||
|
||||
- VIDEO APP INCOME VIDEOS AS VIDEO ADS (2026-11-22): a member of Video App Income (a network site that makes short phone videos, shown publicly on Social Tube, socialtube.club) can tap "Run this on InstantAdPay" on that site's Share tab. It opens /my#campaigns with the Video ad (watch to earn) form filled in with their video file, its title and their Social Tube page as the target. Nothing is purchased automatically: the member picks the watch length and budget and submits; it costs their InstantAdPay credits at the normal video rates. Portrait videos play in Shorts. If the video is remade or deleted on Video App Income its file address changes, so the campaign should be paused and a new one made. No results are promised.
|
||||
- EARN BY WATCHING ON SOCIAL TUBE (2026-11-22): Social Tube (socialtube.club, the network's video gallery) has an Earn page that plays InstantAdPay's watch-to-earn video ads. A member signs in there with the network account, watches for the full time, and earns the SAME InstantAdPay credits as in Shorts / Watch videos here. InstantAdPay picks the video, times it, charges the advertiser and credits the viewer, so the daily video limit is ONE limit shared by both sites, each video pays once per day, and nobody is served their own video. Credit activity reads "Watched a video on Social Tube". Advertisers do nothing extra: every live video campaign can also be watched there.
|
||||
PAGES (the ONLY addresses that exist; never invent others): home https://instantadpay.com, member dashboard https://instantadpay.com/my with tabs as hashes: /my#overview, /my#line (My line, holding tank, prospects), /my#pipeline, /my#buy (Buy packages, Qualified Start, Buy POL with a card), /my#campaigns (New campaign, campaign rows, Credit activity), /my#earn (Watch ads, Watch videos, Verified visits, Inbox), /my#earnings (Trace a payment, payouts, referrals, purchases), /my#promo (Your links, Social posts, Text a friend, Email swipes, Banners, Wall, Objections, Videos, Toolkit), /my#training, /my#games (PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Spooky Doors in season), /games (public list of every game), /my#wallet, /my#profile, /my#help (Help: support tickets). Public: /support (contact form for anyone signed out or locked out; support@instantadpay.com also works), /join/<username> (invite page, ?v=angle), /wall/<username>, /b/<username>/<badge>, /handout/<username>, /ledger, /tx/<hash>, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix.
|
||||
|
||||
RULES:
|
||||
@@ -523,15 +542,23 @@ async function answer(message, historyText) { const r = await answerRaw(message,
|
||||
async function answerRaw(message, historyText) {
|
||||
const msg = String(message || '').trim();
|
||||
if (!msg) return { error: 'Say something first.' };
|
||||
// Network Weekend: inside the window a weekend or Friday question gets the live answer (the Five Dollar Friday entry says +20%)
|
||||
if (WEEKEND) { try { const w = WEEKEND.answer(msg); if (w) return { reply: w, canned: true, kb: 'network-weekend' }; } catch (e) {} }
|
||||
// fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down
|
||||
let hit = null, kbOk = true;
|
||||
let hit = null, kbOk = true, other = [];
|
||||
try {
|
||||
await kb.load();
|
||||
// another network site named (and this one not): this site's instant answers stand aside, except a hand-off (2026-11-15)
|
||||
const other = /instant ?ad ?pay|\biap\b/i.test(msg) ? [] : kb.namesOther(msg, process.env.HUB_SITE || 'iap');
|
||||
other = /instant ?ad ?pay|\biap\b/i.test(msg) ? [] : kb.namesOther(msg, process.env.HUB_SITE || 'iap');
|
||||
hit = await kb.fastPath(msg);
|
||||
if (hit && other.length && !hit.handoff) hit = null;
|
||||
} catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
||||
// a hand-off answers from its exact pattern before anything else; then meaning (2026-11-16, netkb.route): the hub's semantic match
|
||||
// over the network KB answers, keeps or overrules the pattern hit and picks the prompt context. Hub or model slow or down: null,
|
||||
// and the pattern + BM25 path below runs exactly as before.
|
||||
let sem = null;
|
||||
if (kbOk && !(hit && hit.handoff)) { try { sem = await netkb.route(msg, { fast: hit, own: await kb.own(), prefer: other }); } catch (e) { sem = null; } }
|
||||
if (sem) hit = sem.hit;
|
||||
if (hit && hit.id === 'refuel' && !REFUEL_ON()) return { reply: REFUEL_OFF_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'polminer' || hit.id === 'c-polminer') && !pmLive()) return { reply: POLMINER_SOON_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'turkeydrop' || hit.id === 'c-turkeydrop') && !tdLive()) return { reply: tdAnswer(), canned: true, kb: hit.id };
|
||||
@@ -540,13 +567,13 @@ async function answerRaw(message, historyText) {
|
||||
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 || 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 (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, sem ? { via: sem.via } : {}, hit.handoff ? { handoff: true } : {});
|
||||
if (!kbOk) for (const c of 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)
|
||||
let kbBlock = '', kbIds = [];
|
||||
try {
|
||||
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
|
||||
const hits = await kb.context(query, 5);
|
||||
const hits = sem && sem.hits.length ? sem.hits : await kb.context(query, 5); // the semantic context when the hub answered (2026-11-16)
|
||||
const hitsOk = hits.filter(h => (pmLive() || !/^(c-)?polminer$/.test(String(h.entry && h.entry.id))) && (wwLive() || !/^(c-)?warpwares$/.test(String(h.entry && h.entry.id))) && (bixLive() || !isBixId(h.entry && h.entry.id)) && (tdLive() || !/^(c-)?turkeydrop$/.test(String(h.entry && h.entry.id)))); // not live yet: keep its answer out of the prompt
|
||||
kbBlock = kb.promptBlock(hitsOk); kbIds = hitsOk.map(h => h.entry.id);
|
||||
} catch (e) { console.error('kb search', e.message); }
|
||||
|
||||
@@ -82,6 +82,7 @@ async function bootstrap() {
|
||||
catch (e) { if (!['ER_DUP_FIELDNAME', 'ER_DUP_KEYNAME'].includes(e.code)) throw e; }
|
||||
};
|
||||
await alterSafe('ALTER TABLE promo_codes ADD COLUMN funder VARCHAR(190) NULL'); // member-funded partner codes (Nexus), 2026-09-14
|
||||
await alterSafe('ALTER TABLE promo_codes ADD COLUMN starts BIGINT NOT NULL DEFAULT 0'); // a code dormant until this time (Network Weekend, 2026-11-17)
|
||||
await alterSafe('ALTER TABLE accounts ADD COLUMN username VARCHAR(30) NULL');
|
||||
await alterSafe('ALTER TABLE accounts ADD UNIQUE KEY uq_username (username)');
|
||||
await alterSafe('ALTER TABLE accounts ADD COLUMN member_id INT NULL');
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
// and someone on this contract in their line (tank.partnerEligibility); free members cannot adopt
|
||||
// - the pool = tank.waiting() (rule 3 already applied: nobody the hub reports locked on any contract or sponsored, nobody adopted
|
||||
// on LinkSpin) minus spam / suspended / flagged, throwaway or mistyped email domains, and anyone adopted twice already
|
||||
// - max 10 open picks a coach (and the tank's people-held-at-once cap); max 2 adoptions per person (every pick counts, both sites)
|
||||
// - max 10 open picks a coach (site setting fiveXDraftCap, its own cap since 2026-11-15, not the tank's); max 2 adoptions per person (every pick counts, both sites)
|
||||
// - a pick that has not STARTED (payouts on or a first purchase) in 3 days goes back to the pool; a coach cannot release one in its
|
||||
// first 48 hours; a person who has had their 2 adoptions stays with the coach (the tank sweep rule); started picks stay
|
||||
// - never anyone locked on a network contract: asked fresh at adopt and at every return; a hub that does not answer refuses / waits
|
||||
@@ -109,7 +109,10 @@ async function ensureTables() {
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // every partner call, with its reason
|
||||
}
|
||||
|
||||
async function init(opts) { R = opts; if (R.tank && R.tank.GRACE_MS) RULES.graceMs = R.tank.GRACE_MS; await ensureTables(); }
|
||||
// the draft's own cap (Marty 2026-11-15: "5x your team's draft is a different thing altogether"): site setting fiveXDraftCap (default 10),
|
||||
// counted over open draft picks only; the member's own tank adoptions and holding tank batches never share it (tank.partnerEligibility)
|
||||
const capOf = () => { const n = Math.round(Number(R && R.maxOpen ? R.maxOpen() : 10)); return n >= 1 && n <= 100 ? n : 10; };
|
||||
async function init(opts) { R = opts; if (R.tank && R.tank.GRACE_MS) RULES.graceMs = R.tank.GRACE_MS; Object.defineProperty(RULES, 'maxOpen', { get: capOf, enumerable: true, configurable: true }); await ensureTables(); }
|
||||
|
||||
// ---- signature ----
|
||||
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('draft.v1.' + ts + '\n' + raw).digest('hex'); }
|
||||
|
||||
@@ -59,7 +59,7 @@ function steps(E, h, campIds, ticketIds, memberMsgIds) {
|
||||
for (const t of ['account_signals', 'daily_views', 'digests', 'drips', 'earned_credits', 'nudges', 'solo_inbox', 'visit_seen', 'visit_repeat', 'video_seen', 'credit_log', 'promo_redemptions', 'positions']) del(t, 'email=?', [E]);
|
||||
del('prospects', 'owner_email=?', [E]); del('pipeline_notes', 'owner_email=? OR person=?', [E, E]); del('lead_marks', '`lead`=? OR sponsor=?', [E, E]);
|
||||
upd('ad_reports', "reporter=''", [], 'reporter=?', [E]); upd('promo_codes', 'funder=NULL', [], 'funder=?', [E]);
|
||||
del('adoptions', 'adoptee=? OR adopter=?', [E, E]);
|
||||
del('adoptions', 'adoptee=? OR adopter=?', [E, E]); del('tank_batch_picks', 'adoptee=? OR sponsor=?', [E, E]); // holding tank batches (2026-11-15)
|
||||
del('event_marks', 'k LIKE ?', [like(E)]); del('doc_claims', 'k LIKE ?', [like(E)]);
|
||||
del('sponsor_messages', 'from_email=?', [E]);
|
||||
upd('sponsor_messages', 'to_email=?', [tomb], "to_email=? AND kind='chat'", [E]); // the other member's own words stay theirs
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
//
|
||||
// Settings (siteConfig): fridayPromo '1'|'0', fridayBonusPct (20), fridayStart 'YYYY-MM-DD' (first
|
||||
// Friday, 2026-09-25). Everything reads the chain index, never a marketing counter.
|
||||
// Promo days (promodays.js, 2026-11-17): a Friday in the promo map (Black Friday 11-27) pays max(fridayBonusPct, the day's pct),
|
||||
// ONE bonus per tx, under the day's name; the Thursday notice and email, the kickoff and the wrap-up carry that day's copy.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -16,7 +18,12 @@ const TZ = 'America/Chicago';
|
||||
const dayOf = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
|
||||
const weekdayOf = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, weekday: 'short' });
|
||||
const hourOf = ts => Number(new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour: 'numeric', hour12: false }));
|
||||
const isFriday = ts => weekdayOf(ts) === 'Fri';
|
||||
const isFriday = ts => weekdayOf(ts) === 'Fri';
|
||||
// test clock (2026-11-17): env IAP_TEST_NOW (ISO) for the view and the scheduled moments; ignored when NODE_ENV=production
|
||||
const clock = () => { const o = process.env.NODE_ENV !== 'production' && process.env.IAP_TEST_NOW; const t = o ? Date.parse(o) : NaN; return Number.isNaN(t) ? Date.now() : t; };
|
||||
// the promo-day overlay (X.promodays): the effective percent and name for a Friday purchase or moment
|
||||
const pctAt = (ts, cents) => Math.max(cfg().pct, (X.promodays && X.promodays.fridayPct(ts, cents)) || 0);
|
||||
const nameAt = ts => (X.promodays && X.promodays.fridayName(ts)) || 'Five Dollar Friday';
|
||||
|
||||
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'friday.json'); S = load(); }
|
||||
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { granted: {}, posts: {}, badges: {}, sent: {} }; } }
|
||||
@@ -65,26 +72,29 @@ function stats(dayKey) {
|
||||
}
|
||||
// public view
|
||||
function view() {
|
||||
const c = cfg(); const now = Date.now(); const live = liveNow(now); const next = nextFriday(now);
|
||||
return { on: c.on, pct: c.pct, live, today: live ? stats(dayOf(now)) : null, nextFriday: next, nextLabel: next ? labelOf(next) : null, start: c.start };
|
||||
const c = cfg(); const now = clock(); const live = liveNow(now); const next = nextFriday(now);
|
||||
const nextTs = next ? Date.parse(next + 'T12:00:00Z') : 0; // midday UTC = morning Central of that Friday
|
||||
return { on: c.on, pct: live ? pctAt(now) : (next ? pctAt(nextTs) : c.pct), name: live ? nameAt(now) : (next ? nameAt(nextTs) : 'Five Dollar Friday'), live, today: live ? stats(dayOf(now)) : null, nextFriday: next, nextLabel: next ? labelOf(next) : null, start: c.start };
|
||||
}
|
||||
|
||||
// the bonus: once per purchase tx, on a Friday on or after the start
|
||||
async function onEvent(ev) {
|
||||
if (!ev || ev.type !== 'Purchase' || !liveNow(ev.ts) || ev.priceCents < 500) return null;
|
||||
if (S.granted[ev.tx]) return null;
|
||||
const c = cfg(); const bonus = Math.round((Number(ev.creditAmount) || 0) * c.pct / 100);
|
||||
const c = Object.assign({}, cfg(), { pct: pctAt(ev.ts, ev.priceCents) }); const nm = nameAt(ev.ts); const bonus = Math.round((Number(ev.creditAmount) || 0) * c.pct / 100);
|
||||
if (bonus <= 0) return null;
|
||||
const a = await X.accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null;
|
||||
const usd = ('$' + (ev.priceCents / 100).toFixed(2)).replace(/\.00$/, '');
|
||||
await X.ads.addEarned(a.email, bonus, { purchased: true, log: { kind: 'bonus', note: 'Five Dollar Friday: +' + c.pct + '% on your ' + usd + ' package', ref: 'fdf:' + String(ev.tx).slice(0, 30) } });
|
||||
await X.ads.addEarned(a.email, bonus, { purchased: true, log: { kind: 'bonus', note: nm + ': +' + c.pct + '% on your ' + usd + ' package', ref: 'fdf:' + String(ev.tx).slice(0, 30) } });
|
||||
S.granted[ev.tx] = { day: dayOf(ev.ts), memberId: ev.buyerId, bonus, at: Date.now() }; save();
|
||||
try { await X.notify(ev.buyerId, 'Five Dollar Friday: +' + bonus + ' bonus credits', 'Your ' + usd + ' package landed on a Five Dollar Friday, so ' + bonus + ' bonus credits (+' + c.pct + '%) were added to your balance. Every pack bought on a Friday gets this. See your balance: https://instantadpay.com/my#campaigns', 'notice'); } catch (e) {}
|
||||
try { await X.notify(ev.buyerId, nm + ': +' + bonus + ' bonus credits', nm !== 'Five Dollar Friday'
|
||||
? 'Your ' + usd + ' package landed on ' + nm + ', so ' + bonus + ' bonus ad credits (+' + c.pct + '%) were added to your balance, in place of the usual Five Dollar Friday +20%. Ad credits buy advertising, not income. See your balance: https://instantadpay.com/my#campaigns\n\nEvery Network Weekend deal across the network: https://instantadpay.com/weekend'
|
||||
: 'Your ' + usd + ' package landed on a Five Dollar Friday, so ' + bonus + ' bonus credits (+' + c.pct + '%) were added to your balance. Every pack bought on a Friday gets this. See your balance: https://instantadpay.com/my#campaigns', 'notice'); } catch (e) {}
|
||||
// the wave, every ten packs
|
||||
const st = stats(dayOf(ev.ts));
|
||||
if (st.packs > 0 && st.packs % 10 === 0 && !S.posts[st.day + ':' + st.packs]) {
|
||||
S.posts[st.day + ':' + st.packs] = Date.now(); save();
|
||||
X.telegram('\u{1F4B5} <b>Five Dollar Friday</b> · <b>' + st.packs + ' packs</b> so far today from ' + st.buyers + ' buyers, <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members in the same transactions.\nEvery $5+ pack today earns +' + c.pct + '% credits: https://instantadpay.com/my#buy').catch(() => {});
|
||||
X.telegram('\u{1F4B5} <b>' + nm + '</b> · <b>' + st.packs + ' packs</b> so far today from ' + st.buyers + ' buyers, <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members in the same transactions.\nEvery $5+ pack today earns +' + c.pct + '% credits: https://instantadpay.com/my#buy').catch(() => {});
|
||||
}
|
||||
return bonus;
|
||||
}
|
||||
@@ -107,25 +117,28 @@ function earnedBadge(memberId) {
|
||||
// Saturday 00:xx CT wrap-up of the Friday that just ended
|
||||
async function tick() {
|
||||
const c = cfg(); if (!c.on) return;
|
||||
const now = Date.now(); const day = dayOf(now); const wd = weekdayOf(now); const h = hourOf(now);
|
||||
const now = clock(); const day = dayOf(now); const wd = weekdayOf(now); const h = hourOf(now);
|
||||
const next = nextFriday(now);
|
||||
if (wd === 'Thu' && h >= 18 && next && !S.sent['thu:' + next] && await claimOnce('fri:thu:' + next)) {
|
||||
S.sent['thu:' + next] = now; save();
|
||||
const subject = 'Tomorrow is Five Dollar Friday';
|
||||
const text = 'Tomorrow is Five Dollar Friday on InstantAdPay.\n\nAny ad package of $5 or more bought on Friday (Central time) earns +' + c.pct + '% bonus credits, added the moment the purchase settles. Your $5 pays your sponsor line the second it clears, and your line’s $5s pay you. Friday is when we all push at once.\n\nGame Pass too: the same Friday purchase gives you a free 7-day Game Pass for every game in the network (once per Friday, added automatically), and the $5 pack lands as 600 credits that you keep for your ads.\n\nLine up your pack: https://instantadpay.com/my#buy\nWatch the wave on the live ledger: https://instantadpay.com/ledger';
|
||||
const promo = X.promodays && X.promodays.thursdayCopy(next); // Thanksgiving 11-26: the Black Friday copy instead, one message
|
||||
const subject = promo ? promo.subject : 'Tomorrow is Five Dollar Friday';
|
||||
const text = promo ? promo.text : 'Tomorrow is Five Dollar Friday on InstantAdPay.\n\nAny ad package of $5 or more bought on Friday (Central time) earns +' + c.pct + '% bonus credits, added the moment the purchase settles. Your $5 pays your sponsor line the second it clears, and your line’s $5s pay you. Friday is when we all push at once.\n\nGame Pass too: the same Friday purchase gives you a free 7-day Game Pass for every game in the network (once per Friday, added automatically), and the $5 pack lands as 600 credits that you keep for your ads.\n\nLine up your pack: https://instantadpay.com/my#buy\nWatch the wave on the live ledger: https://instantadpay.com/ledger';
|
||||
await broadcast(subject, text);
|
||||
}
|
||||
if (wd === 'Fri' && h >= c.kickHour && day >= c.start && !S.sent['kick:' + day] && await claimOnce('fri:kick:' + day)) {
|
||||
S.sent['kick:' + day] = now; save();
|
||||
X.telegram('\u{1F4B5} <b>It’s Five Dollar Friday.</b> Any ad package from $5 up earns <b>+' + c.pct + '% credits</b> today, and every pack pays its sponsor line in the same transaction. Game Pass day too: the same purchase gives you a free 7-day Game Pass for every game (once per Friday, automatic), and the $5 pack lands as 600 credits you keep for ads. Buy yours, then watch the ledger fill up: https://instantadpay.com/my#buy').catch(() => {});
|
||||
if (nameAt(now) !== 'Five Dollar Friday') X.telegram('\u{1F4B5} <b>It’s ' + nameAt(now) + '. Network Weekend is live</b>, midnight to midnight Central through Cyber Monday. Any ad package from $5 up earns <b>+' + pctAt(now) + '% bonus ad credits</b> today, and every pack pays its sponsor line in the same transaction. The same purchase gives you a free 7-day Game Pass. Ad credits buy advertising, not income. Every deal on the network: https://instantadpay.com/weekend').catch(() => {});
|
||||
else X.telegram('\u{1F4B5} <b>It’s Five Dollar Friday.</b> Any ad package from $5 up earns <b>+' + c.pct + '% credits</b> today, and every pack pays its sponsor line in the same transaction. Game Pass day too: the same purchase gives you a free 7-day Game Pass for every game (once per Friday, automatic), and the $5 pack lands as 600 credits you keep for ads. Buy yours, then watch the ledger fill up: https://instantadpay.com/my#buy').catch(() => {});
|
||||
}
|
||||
if (wd === 'Sat' && h < 3) {
|
||||
const fri = dayOf(now - 86400000);
|
||||
if (isFriday(now - 86400000) && fri >= c.start && !S.sent['wrap:' + fri] && await claimOnce('fri:wrap:' + fri)) {
|
||||
S.sent['wrap:' + fri] = now; save();
|
||||
const st = stats(fri); const top = await topLines(fri);
|
||||
X.telegram('\u{1F3C1} <b>Five Dollar Friday wrap-up</b> (' + labelOf(fri) + ')\n<b>' + st.packs + ' packs</b> from ' + st.buyers + ' buyers · $' + st.usd.toFixed(0) + ' in ad packages · <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members · ' + st.bonusCredits.toLocaleString() + ' bonus credits handed out'
|
||||
+ (top.length ? '\nBiggest lines today: ' + top.map(t => t.who + ' (' + t.packs + ')').join(', ') : '') + '\nNext one is a week away. Line it up: https://instantadpay.com/my#buy').catch(() => {});
|
||||
const wn = nameAt(now - 86400000); const promoFri = wn !== 'Five Dollar Friday';
|
||||
X.telegram('\u{1F3C1} <b>' + wn + ' wrap-up</b> (' + labelOf(fri) + ')\n<b>' + st.packs + ' packs</b> from ' + st.buyers + ' buyers · $' + st.usd.toFixed(0) + ' in ad packages · <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members · ' + st.bonusCredits.toLocaleString() + ' bonus credits handed out'
|
||||
+ (top.length ? '\nBiggest lines today: ' + top.map(t => t.who + ' (' + t.packs + ')').join(', ') : '') + (promoFri ? '\nNetwork Weekend carries on: +20% on $5+ packs Saturday and Sunday, +30% on $20+ on Cyber Monday. Every deal: https://instantadpay.com/weekend' : '\nNext one is a week away. Line it up: https://instantadpay.com/my#buy')).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -140,7 +153,7 @@ async function topLines(dayKey) {
|
||||
// on-site notice + email to every active member (quiet 45+ days skipped, drip unsubscribes honoured)
|
||||
async function broadcast(subject, text) {
|
||||
let all = []; try { all = await X.accounts.listAll(5000); } catch (e) { return; }
|
||||
const now = Date.now(); let n = 0;
|
||||
const now = clock(); let n = 0;
|
||||
for (const a of all) {
|
||||
if (!a.email) continue;
|
||||
if (now - (a.lastSeen || a.created || 0) > 45 * 86400000) continue;
|
||||
|
||||
@@ -192,10 +192,14 @@ function extend(e, via, extra, now, tier) {
|
||||
tier = tierOk(tier) ? tier : 'weekly';
|
||||
const c = cfg(); const tc = c.tiers[tier]; const t = now || Date.now(); const cur = passes.get(e) || { until: 0, bought: [] };
|
||||
const T = tiersOf(cur);
|
||||
const until = Math.max(t, T[tier]) + tc.days * 86400000; T[tier] = until; // renewing early loses nothing: from max(now, until)
|
||||
const bought = [Object.assign({ ts: t, via, tier, usd: tc.price / 100, days: tc.days }, extra || {})].concat(cur.bought || []).slice(0, 200);
|
||||
// Network Weekend (2026-11-17, promodays.js passBonusDays): a tier pass PAID by a package fulfilled Fri 11-27 00:00 CT to Fri 12-04
|
||||
// 00:00 CT gets bonus days (Explorer/Champion +15 = 45, Legend +60 = 425); comps and the weekly pass never do
|
||||
const bonus = via === 'package' && R && typeof R.bonusDays === 'function' ? Math.max(0, Number(R.bonusDays(tier, t)) || 0) : 0;
|
||||
const days = tc.days + bonus;
|
||||
const until = Math.max(t, T[tier]) + days * 86400000; T[tier] = until; // renewing early loses nothing: from max(now, until)
|
||||
const bought = [Object.assign({ ts: t, via, tier, usd: tc.price / 100, days }, bonus ? { bonusDays: bonus } : {}, extra || {})].concat(cur.bought || []).slice(0, 200);
|
||||
passes.set(e, writeTiers(cur, T, { bought, ts: t }));
|
||||
return { until, days: tc.days, tier };
|
||||
return { until, days, tier, bonusDays: bonus };
|
||||
}
|
||||
function waitingOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind !== 'hero' && o.kind !== 'stackpro') out.push(Object.assign({ order: k }, o, { tier: tierOk(o.tier) ? o.tier : 'weekly' })); return out; }
|
||||
function waitingOrder(e, tier) { return waitingOrders(e).find(o => o.tier === (tier || 'weekly')) || null; }
|
||||
@@ -232,7 +236,8 @@ function view(email, now, opts) {
|
||||
// the tier rows this member sees: weekly always; a higher tier while on sale, in the admin preview, or to a current holder (holders
|
||||
// keep their pass when a sale is switched off, they just cannot buy more)
|
||||
const passRows = TIERS.filter(k => k === 'weekly' || c.tiers[k].sale || admin || T[k] > t).map(k => {
|
||||
const tc = c.tiers[k]; return { tier: k, name: TIER_NAMES[k], perks: TIER_DEF[k].perks, price: tc.price, usd: tc.price / 100, days: tc.days, package: packageFor(tc.price / 100),
|
||||
const tc = c.tiers[k]; const bd = k !== 'weekly' && R && typeof R.bonusDays === 'function' ? Math.max(0, Number(R.bonusDays(k, t)) || 0) : 0;
|
||||
return { tier: k, name: TIER_NAMES[k], perks: TIER_DEF[k].perks, price: tc.price, usd: tc.price / 100, days: tc.days + bd, bonusDays: bd, package: packageFor(tc.price / 100),
|
||||
active: T[k] > t, until: T[k] > t ? T[k] : null, waiting: !!waitingOrder(e, k), sale: !!tc.sale, open: k === 'weekly' ? c.enabled : tierOpen(c, k, admin) };
|
||||
});
|
||||
const tiered = passRows.some(r => r.tier !== 'weekly');
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// The network AI ad writer, asked through the hub (Marty 2026-11-17: "the AI generation of the ads worked really well. Let's go
|
||||
// ahead and do it on the other sites too."). The hub reads the member's page, asks the model and filters the copy
|
||||
// (network-hub lib/adwriter.js); this file only signs the call for this site's signed-in member and passes the answer on.
|
||||
// status(member?) -> {on, daily, left?} (cached 60 s; on: false when the hub is unset, unreachable or switched off)
|
||||
// write(member, url, limits) -> {ok, options: [{headline, line?}], url, cached, left} | {error (member-friendly), code, status, left?}
|
||||
// Signed as HUB_SITE with HUB_SECRET: X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body), like every /v1 call.
|
||||
// AI_WRITER=0 hides the button on this site. Nothing is posted: the member picks an option, edits it and saves it themselves.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DEFAULT_SITE = 'iap';
|
||||
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const secret = () => String(process.env.HUB_SECRET || '').trim();
|
||||
const site = () => String(process.env.HUB_SITE || DEFAULT_SITE).trim();
|
||||
const configured = () => !/^(0|false|no|off)$/i.test(String(process.env.AI_WRITER || '').trim()) && !!hubUrl() && secret().length >= 32;
|
||||
|
||||
async function call(route, body, timeoutMs) {
|
||||
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(hubUrl() + route, { method: 'POST', body: raw, signal: AbortSignal.timeout(timeoutMs),
|
||||
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': site(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
|
||||
let j = null; try { j = await r.json(); } catch (e) { j = null; }
|
||||
return { status: r.status, body: j || {} };
|
||||
}
|
||||
|
||||
let st = { at: 0, v: { on: false, daily: 0 } };
|
||||
async function status(member) {
|
||||
if (!configured()) return { on: false, daily: 0 };
|
||||
if (!member && Date.now() - st.at < 60000) return st.v;
|
||||
try {
|
||||
const r = await call('/v1/adwriter/status', member ? { member: String(member) } : {}, 3000);
|
||||
const v = r.status === 200 && r.body && typeof r.body.on === 'boolean' ? r.body : { on: false, daily: 0 };
|
||||
if (!member) st = { at: Date.now(), v: { on: v.on, daily: v.daily || 0 } };
|
||||
return v;
|
||||
} catch (e) { if (!member) st = { at: Date.now() - 45000, v: { on: false, daily: 0 } }; return { on: false, daily: 0 }; } // a down hub is asked again in 15 s
|
||||
}
|
||||
// the button shows only when the hub says the writer is on (60 s cache, never waits on a slow hub for long)
|
||||
async function enabled() { return (await status()).on === true; }
|
||||
|
||||
async function write(member, url, limits) {
|
||||
if (!configured()) return { error: 'The ad writer is switched off right now. You can still write your ad yourself.', code: 'off', status: 503 };
|
||||
try {
|
||||
const r = await call('/v1/adwriter', { member: String(member), url: String(url || '').trim().slice(0, 600), limits }, 75000);
|
||||
const b = r.body || {};
|
||||
if (r.status === 200 && b.ok && Array.isArray(b.options)) return { ok: true, options: b.options, url: b.url, cached: !!b.cached, left: b.left };
|
||||
if (r.status === 401 || r.status === 403 || !b.message) { console.error('hubadwriter: hub answered ' + r.status + ' ' + String(b.error || '')); return { error: 'The ad writer is busy right now. Try again in a minute, or write your ad yourself.', code: 'hub', status: 502 }; }
|
||||
return { error: String(b.message), code: b.error || b.code || 'error', status: r.status >= 400 && r.status < 600 ? r.status : 502, left: b.left };
|
||||
} catch (e) {
|
||||
console.error('hubadwriter: ' + (e.name === 'TimeoutError' || e.name === 'AbortError' ? 'timeout' : String(e.message).slice(0, 120)));
|
||||
return { error: 'The ad writer did not answer in time. Try again in a minute, or write your ad yourself.', code: 'hub', status: 504 };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { status, enabled, write, configured, _reset: () => { st = { at: 0, v: { on: false, daily: 0 } }; } };
|
||||
@@ -145,6 +145,14 @@ async function apply(ev) {
|
||||
if (ev.type === 'member.joined') return memberJoined(ev);
|
||||
if (ev.type === 'wallet.connected') return walletConnected(ev);
|
||||
if (ev.type === 'member.erased') return memberErased(ev);
|
||||
// network sign-in (2026-11-15): a member the hub blocked, or who chose "Sign out everywhere" on any site, is signed out here too
|
||||
if (ev.type === 'member.blocked' || ev.type === 'member.signedout') {
|
||||
if (!R.endSessions) return 'ignored';
|
||||
const p = await resolve({ id: ev.personId }); if (!p || !p.email) return 'ignored';
|
||||
const n = await R.endSessions(p.email, p.wallet || null);
|
||||
note({ type: ev.type === 'member.blocked' ? 'blocked-signed-out' : 'signed-out-everywhere', sessions: n });
|
||||
return n ? 'applied' : 'ignored';
|
||||
}
|
||||
// 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.
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
h += '</div><script src="/assets/common.js?v=20261117nw"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
return h;
|
||||
}
|
||||
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Outbound mail via SendGrid v3 (domain-authenticated instantadpay.com).
|
||||
// Outbound mail via SendGrid v3 (domain-authenticated instantadpay.com; links in bodies go out on the share domain, see mailLinks).
|
||||
// Key sources: SENDGRID_KEY env, else DATA_DIR/sendgrid.key in the volume.
|
||||
// No key = email sign-in stays feature-flagged off in production.
|
||||
const fs = require('fs');
|
||||
@@ -19,6 +19,17 @@ function hasKey() { return !!key(); }
|
||||
// codes and mail to the admin is skipped for anyone who unsubscribed, carries
|
||||
// the signed unsubscribe link (appended unless the body already has one) and
|
||||
// RFC 8058 one-click List-Unsubscribe headers. New senders inherit this.
|
||||
// Links in mail go on the share domain (2026-11-17, Spamhaus DBL): instantadpay.com is on the DBL, so every URL to it in a body
|
||||
// (and the List-Unsubscribe header) counts against each email. One rewrite here covers every sender; the share host passes
|
||||
// /my, /ledger, /join/<tok>, ... through to the same page and answers /unsubscribe and /banners/* itself. The From address
|
||||
// and any name@instantadpay.com in the text stay as they are. MAIL_BASE='' turns it off.
|
||||
const MAIL_BASE = String(process.env.MAIL_BASE == null ? 'https://instantadpay.link' : process.env.MAIL_BASE).trim().replace(/\/+$/, '');
|
||||
const IAP_LINK_RE = /(?<![@\w.-])(?:https?:\/\/)?(?:www\.)?instantadpay\.com(?![\w-])/gi;
|
||||
function mailLinks(s) {
|
||||
if (!MAIL_BASE || s == null) return s;
|
||||
const bare = MAIL_BASE.replace(/^https?:\/\//, '');
|
||||
return String(s).replace(IAP_LINK_RE, m => /^https?:/i.test(m) ? MAIL_BASE : bare);
|
||||
}
|
||||
function isAdmin(to) { const a = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); return !!a && String(to).trim().toLowerCase() === a; }
|
||||
|
||||
async function send(to, subject, text, html, opts) { // html optional (2026-10-01): sent alongside the plain text, never instead of it
|
||||
@@ -29,6 +40,7 @@ async function send(to, subject, text, html, opts) { // html optional (2026-10-0
|
||||
try { if (await drip.isUnsubscribed(to)) return false; } catch (e) { console.error('mailer opt-out check', e.message); }
|
||||
try { unsub = drip.unsubUrl(to); } catch (e) { console.error('mailer unsub link', e.message); }
|
||||
}
|
||||
unsub = mailLinks(unsub); text = mailLinks(text); if (html) html = mailLinks(html); subject = mailLinks(subject);
|
||||
if (unsub && !String(text).includes('/unsubscribe?')) text = text + '\n\n--\nStop these emails: ' + unsub;
|
||||
if (unsub && html && !String(html).includes('/unsubscribe?')) {
|
||||
const foot = '<p style="font-size:12px;color:#888;margin-top:24px">Stop these emails: <a href="' + unsub + '" style="color:#888">unsubscribe</a></p>';
|
||||
@@ -39,7 +51,7 @@ async function send(to, subject, text, html, opts) { // html optional (2026-10-0
|
||||
if (html) content.push({ type: 'text/html', value: html });
|
||||
const msg = {
|
||||
personalizations: [{ to: [{ email: to }] }],
|
||||
from: FROM,
|
||||
from: opts && opts.fromName ? { email: FROM.email, name: String(opts.fromName).slice(0, 60) } : FROM, // same authenticated address; another network site's name on mail sent for it (siteinvite.js code mail, 2026-11-21)
|
||||
subject,
|
||||
content
|
||||
};
|
||||
@@ -68,4 +80,4 @@ function sendCode(to, code) {
|
||||
+ 'InstantAdPay\nAdvertise and earn instantly. Locked in code, not promises.\nhttps://instantadpay.com', null, { transactional: true });
|
||||
}
|
||||
|
||||
module.exports = { init, hasKey, send, sendCode };
|
||||
module.exports = { init, hasKey, send, sendCode, mailLinks };
|
||||
|
||||
@@ -40,7 +40,8 @@ const CATID_CRYPTO = Number(process.env.NAS_CATID || 5);
|
||||
// how many NAS impressions one IAP credit buys, per format. IAP charges credits
|
||||
// on its own surfaces at these same rates, so NAS delivery draws the same pool.
|
||||
function impressionsPerCredit(type) {
|
||||
return type === 'banner' ? 5 : type === 'text' ? 10 : type === 'video' ? 0 : 0;
|
||||
// text 100 since 2026-11-20 (was 10, with a 1/10 network divisor on top): the on-site text price moved to 100 views per credit
|
||||
return type === 'banner' ? 5 : type === 'text' ? 100 : type === 'video' ? 0 : 0;
|
||||
}
|
||||
function nasKind(type) {
|
||||
// pid encodes text(1)/banner(2); adtype is a separate small int — 1 is the
|
||||
@@ -76,7 +77,7 @@ async function pushCampaign(c, opts = {}) {
|
||||
Name, Email, PaymentDetails, EDate, sp, width, height, BannerURL, pid, ref_by, catid)
|
||||
VALUES (?,?,?,?,?,?,0,1,?,?,?,?,?,?,'',?,?,?,?,0,?)`,
|
||||
// clicks route through our redirect so they count and carry the network site as the referrer
|
||||
[token, c.title || null, c.type === 'text' ? (c.body || null) : null, 'https://instantadpay.com/api/ads/click/' + c.id,
|
||||
[token, c.title || null, c.type === 'text' ? (c.body || null) : null, (process.env.NAS_CLICK_BASE || 'https://instantadpay.link') + '/api/ads/click/' + c.id,
|
||||
assigned, assigned, now, kind.adtype,
|
||||
opts.name || 'InstantAdPay member', opts.email || 'ads@instantadpay.com',
|
||||
'InstantAdPay campaign #' + c.id, edate,
|
||||
@@ -122,7 +123,7 @@ async function deactivate(nasAdId) {
|
||||
// point an existing NAS ad at our click redirect (migration for rows pushed before 2026-09-10)
|
||||
async function setClickUrl(nasAdId, campaignId) {
|
||||
if (!enabled()) return { skipped: 'flag-off' };
|
||||
await q('UPDATE sponsorads SET WebsiteURL=? WHERE ID=?', ['https://instantadpay.com/api/ads/click/' + Number(campaignId), Number(nasAdId)]);
|
||||
await q('UPDATE sponsorads SET WebsiteURL=? WHERE ID=?', [(process.env.NAS_CLICK_BASE || 'https://instantadpay.link') + '/api/ads/click/' + Number(campaignId), Number(nasAdId)]);
|
||||
return { ok: true };
|
||||
}
|
||||
async function topUp(nasAdId, addImpressions, days) {
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// Network deals for this site's "Network Weekend" ribbon (Marty 2026-11-17). One source: the hub's public GET /v1/network-deals
|
||||
// (HUB_URL). Cached 2 minutes, refreshed in the background, never waits on a slow hub (2.5 s timeout); hub down = no ribbon.
|
||||
// The same file lives in every network site. Never RM Circle, never the games (the hub list never names them).
|
||||
// The page (/assets/netweekend.js) switches the ribbon on and off by its own clock at startsAt / endsAt, so a cached copy never
|
||||
// shows early or late. setLocal(fn) lets a site rewrite its own deal line from live data (for example a price read from chain),
|
||||
// so the ribbon never shows a number the contract does not charge: fn(deal) returns the deal, a changed copy, or null to drop it.
|
||||
const TTL = 2 * 60 * 1000;
|
||||
let cache = { at: 0, body: { events: [] } };
|
||||
let inflight = null;
|
||||
let local = null;
|
||||
|
||||
const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, '');
|
||||
const safeUrl = u => (/^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(u || '')) ? String(u) : '');
|
||||
const str = (v, n) => String(v == null ? '' : v).slice(0, n || 300);
|
||||
function clean(j) {
|
||||
if (!j || !Array.isArray(j.events)) return null;
|
||||
return { events: j.events.slice(0, 5).filter(e => e && e.id && !Number.isNaN(Date.parse(e.startsAt)) && !Number.isNaN(Date.parse(e.endsAt))).map(e => ({
|
||||
id: str(e.id, 60), name: str(e.name, 60), tagline: str(e.tagline, 160), url: safeUrl(e.url), startsAt: e.startsAt, endsAt: e.endsAt,
|
||||
days: e.days && typeof e.days === 'object' ? Object.fromEntries(Object.entries(e.days).slice(0, 20).map(([k, v]) => [str(k, 10), str(v, 40)])) : {},
|
||||
deals: (Array.isArray(e.deals) ? e.deals : []).slice(0, 40).map(d => {
|
||||
const x = { site: str(d.site, 30), name: str(d.name, 80), url: safeUrl(d.url), text: str(d.text), endsAt: Number.isNaN(Date.parse(d.endsAt)) ? e.endsAt : d.endsAt };
|
||||
if (d.note) x.note = str(d.note, 120);
|
||||
if (d.byDay && typeof d.byDay === 'object') x.byDay = Object.fromEntries(Object.entries(d.byDay).slice(0, 20).map(([k, v]) => [str(k, 10), str(v)]));
|
||||
return x;
|
||||
})
|
||||
})) };
|
||||
}
|
||||
function refresh() {
|
||||
if (inflight || process.env.NETWORK_DEALS_HUB === '0') return inflight;
|
||||
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500);
|
||||
inflight = fetch(hubUrl() + '/v1/network-deals', { signal: ac.signal })
|
||||
.then(r => (r.ok ? r.json() : null))
|
||||
.then(j => { const b = clean(j); if (b) cache = { at: Date.now(), body: b }; else cache.at = Date.now(); })
|
||||
.catch(() => { cache.at = Date.now() - TTL + 30 * 1000; }) // hub down: try again in 30 s, keep the last good copy
|
||||
.finally(() => { clearTimeout(t); inflight = null; });
|
||||
return inflight;
|
||||
}
|
||||
function current() { if (Date.now() - cache.at > TTL) refresh(); return cache.body; }
|
||||
function setLocal(fn) { local = typeof fn === 'function' ? fn : null; }
|
||||
function withLocal(body, self) {
|
||||
if (!local) return body;
|
||||
return { events: body.events.map(e => Object.assign({}, e, { deals: e.deals.map(d => {
|
||||
if (d.site !== self) return d;
|
||||
try { const r = local(Object.assign({}, d)); return r === undefined ? d : r; } catch (err) { return d; }
|
||||
}).filter(Boolean) })) };
|
||||
}
|
||||
// GET /api/network-deals: public, short cache, the same answer on every page. self = this site's network id (NETWORK_SITE_ID).
|
||||
async function handle(req, res, self) {
|
||||
if (!cache.at) { try { await refresh(); } catch (e) {} } // first ask after a boot waits for the hub once (2.5 s cap)
|
||||
const me = String(self || process.env.NETWORK_SITE_ID || '').trim().toLowerCase();
|
||||
const body = Object.assign({ self: me }, withLocal(current(), me));
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=60', 'X-Content-Type-Options': 'nosniff' });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
module.exports = { current, handle, refresh, setLocal, clean, _set: b => { cache = { at: Date.now(), body: clean(b) || { events: [] } }; } };
|
||||
@@ -6,6 +6,17 @@
|
||||
// The merged set is kept in memory and in DATA_DIR/netkb-cache.json (a MySQL document through docstore where the site has
|
||||
// DOCSTORE_URL; written only when the version changes), so a hub outage at boot still answers about the other sites.
|
||||
// Off when HUB_URL or a 32+ character HUB_SECRET is missing, or NETKB=0: the chatbot then answers about this site only.
|
||||
//
|
||||
// SEMANTIC MATCHING (Marty 2026-11-16): the hub matches a question by meaning against the whole network KB with the free core2
|
||||
// embeddings model (POST HUB_URL/v1/kb/match). match() asks it with a strict timeout (NETKB_MATCH_MS, default 1500) and fails
|
||||
// soft: an error or a timeout answers null and the next MATCH_PAUSE_MS skip the hub, so the chat never waits on a slow model and
|
||||
// the site's own BM25 retrieval (kb.js) answers as before. route() turns a match into the chatbot's decision:
|
||||
// - this site's own entry, raw score >= SEM.answer with a clear lead (or the instant-answer pattern agrees): the answer itself
|
||||
// - the instant-answer pattern hit kept when the match agrees (its entry within SEM.agree of the top), or when the match has
|
||||
// no idea (top below SEM.unsure); this site's own entries rank first unless another site is named or clearly closer
|
||||
// - otherwise no instant answer (the regex is overruled by meaning); the entries >= SEM.context feed the AI prompt
|
||||
// suggest() gives the support desk's new-ticket form the closest help answers (KB entries only) the same way, BM25 as the fallback.
|
||||
// Off with NETKB_MATCH=0. Thresholds measured on bge-large-en-v1.5 over the network KB (2026-11-16). Tests: qa/netkb-semantic.test.mjs
|
||||
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline
|
||||
// Banners, Stack POL). Keep them identical.
|
||||
'use strict';
|
||||
@@ -24,10 +35,10 @@ const siteName = () => String(process.env.HUB_SITE || (O && O.site) || '').trim(
|
||||
const enabled = () => process.env.NETKB !== '0' && !!hubUrl() && secret().length >= 32 && !!siteName();
|
||||
const cacheFile = () => (O && O.dataDir ? path.join(O.dataDir, 'netkb-cache.json') : null);
|
||||
|
||||
async function call(method, route, body, headers) {
|
||||
async function call(method, route, body, headers, timeoutMs) {
|
||||
const raw = body === undefined ? '' : JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(15000),
|
||||
const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(timeoutMs || 15000),
|
||||
headers: Object.assign({ 'Content-Type': 'application/json', 'X-Hub-Site': siteName(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, headers || {}) });
|
||||
let j = null; if (r.status !== 304) { try { j = await r.json(); } catch (e) {} }
|
||||
return { status: r.status, body: j };
|
||||
@@ -90,6 +101,92 @@ function sites() {
|
||||
return Object.entries(merged.sites || {}).filter(([k]) => k !== me).map(([k, s]) => ({ site: k, name: s.name || k, url: s.url || '', go: (O && typeof O.linkFor === 'function' && s.url ? O.linkFor(s.url) : '') || s.url || '', count: s.count || 0 }));
|
||||
}
|
||||
|
||||
// ---- semantic matching (2026-11-16)
|
||||
const SEM = { answer: Number(process.env.NETKB_SEM_ANSWER) || 0.84, margin: 0.02, context: Number(process.env.NETKB_SEM_CONTEXT) || 0.68, unsure: 0.70, band: 0.08, away: 0.06, agree: 0.10, floor: 0.60 };
|
||||
const MATCH_PAUSE_MS = 30000;
|
||||
let matchDownUntil = 0;
|
||||
const mstats = { matches: 0, matchErrors: 0, matchSkipped: 0, matchLastMs: 0, matchLastError: null, semAnswer: 0, semAgree: 0, semRegex: 0, semVeto: 0, semContext: 0 };
|
||||
const matchOn = () => enabled() && process.env.NETKB_MATCH !== '0';
|
||||
// -> the hub's answer {confidence, margin, hits: [{site, id, title, answer, score, boosted, home}]} or null (off, down, slow)
|
||||
async function match(q, o) {
|
||||
o = o || {};
|
||||
if (!matchOn()) return null;
|
||||
if (Date.now() < matchDownUntil) { mstats.matchSkipped++; return null; }
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const body = { q: String(q || '').slice(0, 600), k: o.k || 6 };
|
||||
if (o.prefer && o.prefer.length) body.prefer = o.prefer;
|
||||
if (o.only && o.only.length) body.only = o.only;
|
||||
const r = await call('POST', '/v1/kb/match', body, undefined, o.timeoutMs || Number(process.env.NETKB_MATCH_MS) || 1500);
|
||||
mstats.matchLastMs = Date.now() - t0;
|
||||
if (r.status !== 200 || !r.body || !Array.isArray(r.body.hits)) throw new Error('match ' + r.status + ' ' + ((r.body && r.body.error) || ''));
|
||||
mstats.matches++;
|
||||
return r.body;
|
||||
} catch (e) { mstats.matchErrors++; mstats.matchLastError = e.message; matchDownUntil = Date.now() + MATCH_PAUSE_MS; return null; }
|
||||
}
|
||||
// msg + { fast: the instant-answer pattern hit (or null), own: this site's entries, prefer: [site ids the question names] }
|
||||
// -> null (no match: the caller keeps its old path) or { via, hit: own entry to answer with | null, hits: [{entry, score}] for the prompt }
|
||||
async function route(msg, o) {
|
||||
o = o || {};
|
||||
// a question that names another site but asks about "here" is about this site (e.g. "I am on InstantAdPay, does my team carry over here?")
|
||||
const prefer = (o.prefer || []).length && !/\b(here|this site|this one)\b/i.test(msg) ? o.prefer : [];
|
||||
const m = await match(msg, { k: 8, prefer });
|
||||
if (!m) return null;
|
||||
const me = siteName();
|
||||
const own = new Map((o.own || []).map(e => [String(e.id), e]));
|
||||
const rem = new Map(remote().map(e => [e.id, e]));
|
||||
const all = m.hits.map(h => ({ entry: h.site === me ? own.get(String(h.id)) : rem.get(h.site + ':' + h.id), score: Number(h.score) || 0, home: h.site === me })).filter(h => h.entry);
|
||||
let hits = all;
|
||||
const named = prefer.length > 0, fast = o.fast || null;
|
||||
if (!named) { // home-site first: this site's own entries lead; another site's ride behind them only when clearly closer (a thing only that site has)
|
||||
const mine = hits.filter(h => h.home && h.score >= SEM.context);
|
||||
const homeTop = mine.length ? mine[0].score : 0;
|
||||
hits = mine.concat(hits.filter(h => !h.home && h.score >= homeTop + SEM.away));
|
||||
}
|
||||
const top = hits[0];
|
||||
const ctx = top ? hits.filter(h => h.score >= SEM.context && (h.score >= top.score - SEM.band || !h.home)).map(h => ({ entry: h.entry, score: Math.round(h.score * 1000) / 1000 })) : [];
|
||||
const out = (via, hit) => { mstats['sem' + via[0].toUpperCase() + via.slice(1)]++; return { via, hit, hits: ctx, confidence: top ? top.score : 0 }; };
|
||||
if (top && top.home && !named && top.score >= SEM.answer && (Number(m.margin) >= SEM.margin || (fast && String(fast.id) === String(top.entry.id)))) return out('answer', top.entry);
|
||||
if (fast) {
|
||||
const best = all.length ? all[0].score : 0;
|
||||
if (all.some(h => h.home && String(h.entry.id) === String(fast.id) && h.score >= SEM.floor && h.score >= best - SEM.agree)) return out('agree', fast);
|
||||
if (!top || top.score < SEM.unsure) return out('regex', fast);
|
||||
return out('veto', null);
|
||||
}
|
||||
return out('context', null);
|
||||
}
|
||||
|
||||
// support desk suggestions (2026-11-16): the help answers closest to what a signed-in member is typing into a new ticket.
|
||||
// Knowledge-base entries only (published answers, including the ones written from past tickets), never anyone's ticket text.
|
||||
// text + { own: this site's entries, fallback: async q => [{entry}] (BM25) when the hub is slow or down, max }
|
||||
const SUGGEST_MIN = Number(process.env.NETKB_SUGGEST_MIN) || 0.70;
|
||||
const NOT_SUGGESTED = /(^|[-:])support$|^c-refund$/; // the "contact support" entry is no help on the support form itself
|
||||
function suggestItem(e, home, score) {
|
||||
return { id: String(e.id), title: e.title, answer: String(e.answer || '').slice(0, 900), site: home ? '' : (e.siteName || e.site || ''),
|
||||
link: home ? (e.link || '') : (e.go || e.siteUrl || ''), fromTicket: !!(home && e.source === 'ticket'), score: score == null ? null : Math.round(score * 1000) / 1000 };
|
||||
}
|
||||
async function suggest(text, o) {
|
||||
o = o || {};
|
||||
const q = String(text || '').replace(/\s+/g, ' ').trim().slice(0, 600);
|
||||
if (q.replace(/[^A-Za-z0-9]/g, '').length < 10) return { items: [], via: 'short' };
|
||||
const me = siteName(); const own = new Map((o.own || []).map(e => [String(e.id), e]));
|
||||
const keep = (e, home) => e && !(home && e.handoff) && !NOT_SUGGESTED.test(String(e.id));
|
||||
let items = [], via = 'none';
|
||||
const m = await match(q, { k: 8, timeoutMs: o.timeoutMs || 2000 });
|
||||
if (m) {
|
||||
via = 'semantic'; const top = m.hits.length ? Number(m.hits[0].score) : 0; const rem = new Map(remote().map(e => [e.id, e]));
|
||||
for (const h of m.hits) {
|
||||
if (h.score < SUGGEST_MIN || h.score < top - 0.08) continue;
|
||||
const home = h.site === me; const e = home ? own.get(String(h.id)) : rem.get(h.site + ':' + h.id);
|
||||
if (keep(e, home)) items.push(suggestItem(e, home, h.score));
|
||||
}
|
||||
} else if (typeof o.fallback === 'function') {
|
||||
via = 'bm25';
|
||||
try { for (const x of (await o.fallback(q)) || []) { const e = x && x.entry; const home = !!e && !e.site; if (keep(e, home)) items.push(suggestItem(e, home, null)); } } catch (e) {}
|
||||
}
|
||||
return { items: items.slice(0, o.max || 3), via };
|
||||
}
|
||||
|
||||
// opts: { dataDir, site (hub site id), name, url, entries: async () => [...], linkFor: url => tracked link }
|
||||
function init(opts) {
|
||||
O = opts || {}; readCache();
|
||||
@@ -99,8 +196,9 @@ function init(opts) {
|
||||
timer = setInterval(async () => { await refresh().catch(() => {}); if (!publishedHash) await publish().catch(() => {}); }, Math.max(1000, Number(process.env.NETKB_REFRESH_MS) || REFRESH_MS));
|
||||
if (timer.unref) timer.unref();
|
||||
}
|
||||
function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt }, stats); }
|
||||
function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt, semantic: matchOn(), sem: SEM }, stats, mstats); }
|
||||
function _set(m) { merged = m; } // tests
|
||||
|
||||
const version = () => merged.version || '';
|
||||
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, _set };
|
||||
function _matchReset() { matchDownUntil = 0; } // tests
|
||||
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, match, route, suggest, SEM, _set, _matchReset };
|
||||
|
||||
@@ -36,7 +36,7 @@ function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list;
|
||||
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
|
||||
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
|
||||
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
|
||||
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', viraladblitz: 'nwvab', fivex: 'nw5x', downlinehydra: 'nwdh', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
||||
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', viraladblitz: 'nwvab', viraladsource: 'nwvas', yourprogrambuilder: 'nwypb', fivex: 'nw5x', downlinehydra: 'nwdh', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
||||
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
|
||||
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||
function selfId(req, l) {
|
||||
|
||||
@@ -24,6 +24,30 @@
|
||||
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
|
||||
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
|
||||
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
|
||||
//
|
||||
// THE HUB AS THE PROVIDER (Marty approved 2026-11-15; off unless HUB_SSO=on, with HUB_URL, HUB_SECRET (32+) and HUB_SITE or C.hubSite).
|
||||
// The network hub keeps one network sign-in per browser in its own cookie (7 days, renewed on use). With it on:
|
||||
// /sso/start asks the hub (GET <hub>/sso/check?site=<HUB_SITE>&st&to&m) instead of one other site; the hub answers
|
||||
// /sso/in?h=<token> ("h1." token, HMAC-SHA256 with this site's HUB_SECRET under 'hubsso.v1.', iss 'hub', aud = this site,
|
||||
// 60 s, single use, bound to the state cookie) or /sso/in?none=1&hub=1, and then the old pairwise path is tried once as the
|
||||
// fallback (until every site is switched).
|
||||
// Push: a signed-in member's page load (a real top-level navigation only) with no matching nsso.hp cookie goes once through
|
||||
// <hub>/sso/set?site&t=<this site's token for the member> and straight back, so signing in on any site signs in the hub.
|
||||
// Only when the hub answered /health in the last 2 minutes: a hub that is down never takes a page with it.
|
||||
// Activity (Marty 2026-11-15, DownlineHydra "Wake it", the CRM score): a signed-in member's page load pings POST <hub>/v1/activity
|
||||
// {email|wallet, kind 'visit'} at most once per member per day, fire and forget (HUB_URL + HUB_SECRET; HUB_ACTIVITY=0 turns it off).
|
||||
// signOutEverywhere(session): POST <hub>/v1/sso/signout; the hub ends every hub sign-in of that person and tells hooked sites.
|
||||
//
|
||||
// ONE SITES LIST + THE WAY BACK (Marty 2026-11-17: "I logged in to Instant Ad Pay from Viral Ad Source, and it never had a return
|
||||
// path back"). Before, each provider (IAP, LinkSpin) kept its own hand-written `wallets` list; a site missing from it (5xYourTeam
|
||||
// 11-15, ViralAdSource 11-17) was refused at /sso/check and the member was dropped on the provider's dashboard with no way back.
|
||||
// Sites list: a provider also knows every site in the hub's public GET <hub>/v1/sso-sites (HUB_SSO_SITES there; the same list the
|
||||
// hub signs in for). Read at start, every 5 minutes, and once more (2 s at most) when an unknown site asks. Hand-written entries win.
|
||||
// Return links: any provider page with ?return=<site>&to=/path (a known site only, never an open redirect) remembers the way back
|
||||
// in nsso.ret (1 day) and reloads without the two parameters. Signed in already: straight back. After the email-code sign-in (and
|
||||
// after the username step for a new account) the provider's dashboard goes to /sso/resume, which finishes it: /go/<site>?to=/path.
|
||||
// No wallet yet (a wallet site needs one): with C.walletPath the member goes to the provider's wallet step first (nsso.wait), and
|
||||
// afterWallet(req) gives the wallet-link answer its next hop, /sso/resume. The same holds for a deliberate tap (nsso.back).
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
@@ -34,16 +58,53 @@ 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 GO_STATE_AGE = 3600; // seconds: the state cookie on a deliberate tap (time to sign in, pick a username and link a wallet on the provider first; 20 minutes until 2026-11-17)
|
||||
const BACK_AGE = 3600; // seconds: the provider remembers an unfinished deliberate check while the member signs in (20 minutes until 2026-11-17)
|
||||
const RET_AGE = 86400; // seconds: a ?return=<site> link remembers the way back (2026-11-17)
|
||||
const TRIED_AGE = 120; // seconds: one silent check per browser per 2 minutes (loop guard only; 30 minutes until 2026-11-15)
|
||||
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
|
||||
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
||||
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', fivex: '5xYourTeam' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15); fivex = 5xYourTeam (2026-11-15)
|
||||
const WALLET_RE = /^0x[0-9a-f]{40}$/;
|
||||
const PUSH_AGE = 6 * 86400; // seconds: this browser's member is signed in on the hub (the hub's own sign-in lasts 7 days)
|
||||
const HUB_BASE = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const HUB_KEY = () => String(process.env.HUB_SECRET || '').trim();
|
||||
const HUB_NAME = () => String(process.env.HUB_SITE || (C && (C.hubSite || C.self)) || '').trim().toLowerCase();
|
||||
const hubCreds = () => /^https?:\/\/[a-z0-9.:-]+$/i.test(HUB_BASE()) && HUB_KEY().length >= 32 && /^[a-z0-9_-]{1,64}$/.test(HUB_NAME());
|
||||
const hubOn = () => String(process.env.HUB_SSO || '').trim().toLowerCase() === 'on' && hubCreds();
|
||||
let hubSeen = 0, hubChecked = 0, hubAsking = null; // last good /health answer, last time we asked
|
||||
// true when the hub answered /health in the last 2 minutes. Asked at most once a minute; while the answer is unknown (first use, or
|
||||
// the last good answer is old) the caller waits for that one question (2 s at most), so a hub that is down costs one page 2 s a minute.
|
||||
async function hubUp() {
|
||||
const now = Date.now();
|
||||
if (now - hubChecked >= 60000 && !hubAsking && typeof fetch === 'function') {
|
||||
hubChecked = now;
|
||||
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, 2000);
|
||||
hubAsking = fetch(HUB_BASE() + '/health', { signal: ac ? ac.signal : undefined }).then(r => { if (r.ok) hubSeen = Date.now(); }).catch(() => {}).finally(() => { clearTimeout(tm); hubAsking = null; });
|
||||
}
|
||||
if (hubAsking && Date.now() - hubSeen >= 120000) await hubAsking;
|
||||
return Date.now() - hubSeen < 120000;
|
||||
}
|
||||
|
||||
// the hub's sign-in sites {site: base} (2026-11-17): providers answer every site the hub knows, not only their hand-written list
|
||||
let hubSites = {}, hubSitesAt = 0, hubSitesAsking = null;
|
||||
const SITE_RE = /^[a-z0-9_-]{1,64}$/, BASE_RE = /^https?:\/\/[a-z0-9.:-]+$/i;
|
||||
function loadHubSites() {
|
||||
if (hubSitesAsking) return hubSitesAsking;
|
||||
if (!BASE_RE.test(HUB_BASE()) || typeof fetch !== 'function' || String(process.env.NSSO_HUB_SITES || '') === '0') return Promise.resolve();
|
||||
hubSitesAt = Date.now();
|
||||
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, 2000);
|
||||
hubSitesAsking = fetch(HUB_BASE() + '/v1/sso-sites', { signal: ac ? ac.signal : undefined }).then(r => (r.ok ? r.json() : null)).then(j => {
|
||||
if (!j || !j.sites || typeof j.sites !== 'object') return;
|
||||
const out = {}; for (const [k, v] of Object.entries(j.sites)) { const b = String(v || '').replace(/\/+$/, ''); if (SITE_RE.test(k) && BASE_RE.test(b)) out[k] = b; }
|
||||
hubSites = out;
|
||||
}).catch(() => {}).finally(() => { clearTimeout(tm); hubSitesAsking = null; });
|
||||
return hubSitesAsking;
|
||||
}
|
||||
const freshSites = () => { if (C && C.wallet && Date.now() - hubSitesAt > 5 * 60 * 1000) loadHubSites(); };
|
||||
|
||||
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
|
||||
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } }
|
||||
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() }, walletPath?: the provider's wallet step }
|
||||
|
||||
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||
@@ -88,6 +149,77 @@ function verify(tok, o) {
|
||||
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||
}
|
||||
|
||||
// hub tokens ("h1.", the hub's format): mint for the hub (push), verify from the hub (sign-in)
|
||||
const hmacHub = x => crypto.createHmac('sha256', HUB_KEY()).update('hubsso.v1.' + x).digest();
|
||||
function mintHub(o) {
|
||||
const now = o.now || Date.now();
|
||||
const t = { iss: HUB_NAME(), aud: 'hub', to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
|
||||
if (o.email) t.email = String(o.email).trim().toLowerCase(); else if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
|
||||
const body = b64u(JSON.stringify(t));
|
||||
return 'h1.' + body + '.' + b64u(hmacHub(body));
|
||||
}
|
||||
function verifyHub(tok, o) {
|
||||
if (!hubCreds()) return { error: 'off' };
|
||||
const m = /^h1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
|
||||
if (!m) return { error: 'malformed' };
|
||||
const want = hmacHub(m[1]), got = unb64u(m[2]);
|
||||
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
|
||||
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
|
||||
const now = (o && o.now) || Date.now();
|
||||
if (!p || p.iss !== 'hub' || p.aud !== HUB_NAME()) return { error: 'audience' };
|
||||
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
|
||||
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
|
||||
const st = String((o && o.st) || '');
|
||||
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
|
||||
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
|
||||
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
|
||||
return { ok: true, iss: 'hub', email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||
}
|
||||
// a signed /v1 call to the hub (the scheme every site already uses): hex HMAC-SHA256(HUB_SECRET, ts + newline + body)
|
||||
async function hubCall(route, body, ms) {
|
||||
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
|
||||
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, ms || 5000);
|
||||
try {
|
||||
const r = await fetch(HUB_BASE() + route, { method: 'POST', body: raw, signal: ac ? ac.signal : undefined, headers: { 'Content-Type': 'application/json', 'X-Hub-Site': HUB_NAME(), 'X-Hub-Ts': ts, 'X-Hub-Sig': crypto.createHmac('sha256', HUB_KEY()).update(ts + '\n' + raw).digest('hex') } });
|
||||
let j = null; try { j = await r.json(); } catch (e) {}
|
||||
return { status: r.status, json: j };
|
||||
} finally { clearTimeout(tm); }
|
||||
}
|
||||
const who = s => (s && s.email ? { email: String(s.email).toLowerCase() } : s && s.address && WALLET_RE.test(String(s.address).toLowerCase()) ? { wallet: String(s.address).toLowerCase() } : null);
|
||||
const pushTag = w => b64u(crypto.createHmac('sha256', HUB_KEY()).update('push.' + (w.email || w.wallet)).digest()).slice(0, 22);
|
||||
// once per member per day (memory; a restart may ping once more, the hub counts a visit once per 10 minutes anyway)
|
||||
const pinged = new Map(); let pingDay = '';
|
||||
function activity(w) {
|
||||
if (String(process.env.HUB_ACTIVITY || '') === '0' || !hubCreds() || typeof fetch !== 'function') return;
|
||||
const day = new Date().toISOString().slice(0, 10); if (day !== pingDay) { pinged.clear(); pingDay = day; }
|
||||
const k = w.email || w.wallet; if (pinged.has(k)) return; pinged.set(k, 1);
|
||||
hubCall('/v1/activity', Object.assign({ kind: 'visit' }, w), 5000).then(r => { if (r.status >= 500) pinged.delete(k); }).catch(() => { pinged.delete(k); });
|
||||
}
|
||||
// a signed-in request the site already answers (2026-11-16, Marty: "LinkSpin never reports activity"): /api/me, the dashboard
|
||||
// heartbeat (/api/my/ping) and the admin portal call this, so a Control Room tab kept open for days, a browser that sends no
|
||||
// Sec-Fetch headers and a wallet-only session still count the day's visit. The page-load ping in page() only sees full navigations.
|
||||
// s = {email} and/or {address}. Same once-a-day rule as page(). -> true when a ping was due or already sent today.
|
||||
function seen(s) {
|
||||
try {
|
||||
if (!C || !hubCreds()) return false;
|
||||
const w = who(s && s.email ? s : s && s.address ? { address: s.address } : null); if (!w) return false;
|
||||
activity(w); return true;
|
||||
} catch (e) { return false; }
|
||||
}
|
||||
// a real top-level page load of a page (never an API call, an asset, a fetch, a bot or one of our own hops)
|
||||
function pageLoad(req, p) {
|
||||
if (req.method !== 'GET' || isBot(req)) return false;
|
||||
if (req.headers['sec-fetch-dest'] !== 'document' || (req.headers['sec-fetch-mode'] && req.headers['sec-fetch-mode'] !== 'navigate')) return false;
|
||||
if (/^\/(sso|api|go|assets|art|img|fonts|uploads|admin)(\/|$)/.test(p)) return false;
|
||||
return !/\.[a-z0-9]{1,5}$/i.test(p);
|
||||
}
|
||||
async function signOutEverywhere(s) {
|
||||
const w = who(s); if (!w || !hubCreds()) return { ok: false, reason: !w ? 'signed out' : 'hub off' };
|
||||
try { const r = await hubCall('/v1/sso/signout', w, 8000); return r.status === 200 ? Object.assign({ ok: true }, r.json || {}) : { ok: false, reason: 'hub ' + r.status }; }
|
||||
catch (e) { return { ok: false, reason: 'hub unreachable' }; }
|
||||
}
|
||||
|
||||
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
|
||||
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
|
||||
const used = new Map(); let fileLoaded = false, tableReady = null;
|
||||
@@ -129,7 +261,25 @@ const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/;
|
||||
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(); }
|
||||
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); if (hubOn()) { hubSeen = 0; hubChecked = 0; hubUp().catch(() => {}); } hubSites = {}; hubSitesAt = 0; if (C.wallet) loadHubSites(); }
|
||||
|
||||
// a site this provider answers for: its own list first, then the hub's (never itself, never the peer, which has its own path)
|
||||
function siteBase(x) {
|
||||
if (!C || !C.wallet || !SITE_RE.test(String(x || '')) || x === C.self || x === C.peer) return null;
|
||||
if (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x)) return C.wallets[x];
|
||||
if (Object.prototype.hasOwnProperty.call(hubSites, x)) { const b = hubSites[x]; return () => b; }
|
||||
return null;
|
||||
}
|
||||
// an unknown site asking: ask the hub once more (at most every 30 s, 2 s at most) before refusing
|
||||
async function siteBaseFresh(x) { let b = siteBase(x); if (!b && C && C.wallet && SITE_RE.test(String(x || '')) && Date.now() - hubSitesAt > 30000) { await loadHubSites(); b = siteBase(x); } return b; }
|
||||
const siteName = x => NAMES[x] || ({ viraladsource: 'ViralAdSource', webworthit: 'WebWorthIt', stackpol: 'Stack POL' })[x] || x;
|
||||
const retOf = req => { const m = /^([a-z0-9_-]{1,64})\|(\/.*)$/.exec(cookies(req)['nsso.ret'] || ''); return m ? { site: m[1], to: safePath(m[2], '/') } : null; };
|
||||
// signed in here, on the way back to a site: its wallet step first when the site needs a wallet this account does not have yet
|
||||
async function backHop(s, site, to, set) {
|
||||
let w = null; try { w = await C.wallet(s); } catch (e) {}
|
||||
if ((!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) && C.walletPath) { set.push(ck('nsso.wait', '1', BACK_AGE, true)); log('back: wallet step first', s.email, 'for ' + siteName(site)); return C.walletPath; }
|
||||
return '/go/' + site + '?to=' + encodeURIComponent(to);
|
||||
}
|
||||
|
||||
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
|
||||
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
||||
@@ -138,9 +288,24 @@ const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
||||
async function handle(req, res, u) {
|
||||
if (!C || req.method !== 'GET') return false;
|
||||
const p = u.pathname;
|
||||
if (C.wallet && u.searchParams.has('return') && !/^\/(sso|api|go)(\/|$)/.test(p)) { // a site's "sign in / join on <provider>" link: remember the way back (2026-11-17)
|
||||
const site = String(u.searchParams.get('return') || '').toLowerCase(); const to = safePath(u.searchParams.get('to'), '/');
|
||||
const clean = new URL(u.pathname + u.search, 'http://x.invalid'); clean.searchParams.delete('return'); clean.searchParams.delete('to');
|
||||
const here = safePath(clean.pathname + clean.search, '/');
|
||||
const base = isBot(req) ? null : await siteBaseFresh(site);
|
||||
if (!base) return go(res, here); // unknown site (or a bot): the page itself, nothing remembered
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (s && s.email) { // signed in here already: straight back (wallet step first when the site needs one)
|
||||
const set = []; const hop = await backHop(s, site, to, set);
|
||||
set.push(hop === C.walletPath ? ck('nsso.ret', site + '|' + to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
|
||||
return go(res, hop, set);
|
||||
}
|
||||
log('return link remembered', null, 'for ' + siteName(site));
|
||||
return go(res, here, [ck('nsso.ret', site + '|' + to, RET_AGE, true), ck('nsso.wait', '', 0, true)]);
|
||||
}
|
||||
const peerName = NAMES[C.peer] || C.peer;
|
||||
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
|
||||
const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
|
||||
const walletBase = siteBase; freshSites(); // the hand-written list, then the hub's sign-in sites (2026-11-17)
|
||||
if (goTo && (goTo === C.peer || walletBase(goTo))) {
|
||||
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
|
||||
const to = safePath(u.searchParams.get('to'), '/');
|
||||
@@ -156,29 +321,43 @@ async function handle(req, res, u) {
|
||||
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);
|
||||
const viaHub = hubOn() && !u.searchParams.get('nohub') && (await hubUp());
|
||||
if (!(enabled() || viaHub) || isBot(req) || notPage(req)) return go(res, to);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (s && (s.email || s.address)) return go(res, to); // already signed in here
|
||||
const c = cookies(req);
|
||||
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
|
||||
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off']) && !u.searchParams.get('nohub')) return go(res, to);
|
||||
const st = crypto.randomBytes(16).toString('hex');
|
||||
if (viaHub) { // the hub answers for the whole network; the pairwise provider is the fallback when it has nobody (nsso.via)
|
||||
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true), ck('nsso.via', via || '-', STATE_AGE, true)];
|
||||
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||
return go(res, HUB_BASE() + '/sso/check?site=' + encodeURIComponent(HUB_NAME()) + '&st=' + st + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
||||
}
|
||||
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
||||
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
||||
}
|
||||
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
|
||||
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
|
||||
const clear = [ck('nsso.back', '', 0, true)];
|
||||
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
|
||||
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')), clear);
|
||||
const clear = [ck('nsso.back', '', 0, true), ck('nsso.wait', '', 0, true)];
|
||||
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) { // no deliberate tap waiting: a ?return=<site> link may be (2026-11-17)
|
||||
const ret = retOf(req);
|
||||
if (!ret || !siteBase(ret.site)) return go(res, C.defaultPath, clear.concat(ck('nsso.ret', '', 0, true)));
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (!s || !s.email) return go(res, C.signinPath(C.defaultPath)); // not signed in yet: keep it for after the sign-in
|
||||
const set = clear.slice(); const hop = await backHop(s, ret.site, ret.to, set);
|
||||
set.push(hop === C.walletPath ? ck('nsso.ret', ret.site + '|' + ret.to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
|
||||
log('back to ' + siteName(ret.site), s.email); return go(res, hop, set);
|
||||
}
|
||||
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')) + '&m=go', clear); // m=go: still a deliberate tap (the wallet step when one is missing)
|
||||
}
|
||||
if (p === '/sso/check') {
|
||||
const st = String(u.searchParams.get('st') || '');
|
||||
const to = safePath(u.searchParams.get('to'), '/');
|
||||
const r = String(u.searchParams.get('r') || '');
|
||||
const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
|
||||
const wb = r && r !== C.peer ? await siteBaseFresh(r) : null; // a wallet site asking: the token carries the wallet (the hub's sign-in sites too, 2026-11-17)
|
||||
if (r && r !== C.peer && !wb) { log('check: unknown site asking, nothing sent', null, r.slice(0, 20)); return go(res, C.defaultPath); } // never answer an unknown site as if the peer asked (2026-11-15: 5xYourTeam was sent to LinkSpin)
|
||||
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud;
|
||||
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = siteName(aud);
|
||||
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
||||
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
@@ -191,15 +370,30 @@ async function handle(req, res, u) {
|
||||
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); } }
|
||||
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) {
|
||||
if (u.searchParams.get('m') === 'go' && C.walletPath && !isBot(req)) { // a deliberate tap: link a wallet here first, then /sso/resume finishes the trip (2026-11-17)
|
||||
log('check: no wallet on the account, wallet step first', s.email, 'for ' + forName);
|
||||
const back = new URLSearchParams({ st, to, m: 'go' }); if (r) back.set('r', r);
|
||||
return go(res, C.walletPath, [ck('nsso.back', back.toString(), BACK_AGE, true), ck('nsso.wait', '1', BACK_AGE, true)]);
|
||||
}
|
||||
log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
|
||||
log('token issued', s.email, 'for ' + forName);
|
||||
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
|
||||
}
|
||||
if (p === '/sso/in') {
|
||||
const c = cookies(req);
|
||||
const set = [ck('nsso.st', '', 0, true)];
|
||||
if (u.searchParams.get('none')) { 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 (u.searchParams.get('none')) {
|
||||
const nto = safePath(u.searchParams.get('to'), C.defaultPath);
|
||||
if (u.searchParams.get('hub') && enabled()) { // nobody on the hub: ask the old pairwise provider once (until every site is switched)
|
||||
const via = String(c['nsso.via'] || ''); set.push(ck('nsso.via', '', 0, true));
|
||||
log('none on the hub, trying ' + (NAMES[via] || peerName));
|
||||
return go(res, '/sso/start?nohub=1&mode=' + (u.searchParams.get('m') === 'go' ? 'go' : 'check') + (via && via !== '-' ? '&via=' + encodeURIComponent(via) : '') + '&to=' + encodeURIComponent(nto), set);
|
||||
}
|
||||
log('none: not signed in on ' + (u.searchParams.get('hub') ? 'the hub' : peerName)); return go(res, C.signinPath(nto), set);
|
||||
}
|
||||
const fromHub = !!u.searchParams.get('h');
|
||||
const v = fromHub ? verifyHub(u.searchParams.get('h'), { st: c['nsso.st'] }) : verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
|
||||
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
|
||||
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
|
||||
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
|
||||
@@ -211,21 +405,48 @@ async function handle(req, res, u) {
|
||||
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);
|
||||
if (fromHub) { const w2 = v.wallet && C.from ? { wallet: v.wallet } : { email: v.email }; set.push(ck('nsso.hp', pushTag(w2), PUSH_AGE, true)); } // the hub already has this sign-in
|
||||
log('signed in from ' + (fromHub ? 'the network hub' : (NAMES[v.iss] || peerName)), v.email);
|
||||
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
|
||||
}
|
||||
if (p === '/api/sso/status') {
|
||||
const c = cookies(req); const set = [];
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
const signedIn = !!(s && (s.email || s.address));
|
||||
const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
||||
const out = { peer: hubOn() ? 'the network' : peerName, check: (enabled() || (hubOn() && (await hubUp()))) && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
||||
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
|
||||
return sendJson(res, out, set);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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'];
|
||||
// every GET a site serves passes here first (2026-11-15): a signed-in member's real page load pings the hub's activity once a day and,
|
||||
// with the hub on, tells the hub about this sign-in once (nsso.hp). -> true when it answered (the redirect through the hub).
|
||||
async function page(req, res, u) {
|
||||
if (!C || !hubCreds()) return false;
|
||||
const p = u.pathname;
|
||||
if (!pageLoad(req, p)) return false;
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
const w = who(s); if (!w) return false;
|
||||
activity(w);
|
||||
if (hubOn() && cookies(req)['nsso.hp'] !== pushTag(w) && (await hubUp())) {
|
||||
log('hub: telling the hub about this sign-in', w.email || null);
|
||||
return go(res, HUB_BASE() + '/sso/set?site=' + encodeURIComponent(HUB_NAME()) + '&t=' + mintHub(Object.assign({ to: p + u.search }, w)), [ck('nsso.hp', pushTag(w), PUSH_AGE, true)]);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
module.exports = { init, handle, enabled, pendingBack, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
|
||||
// true when this browser came here from a deliberate network tap (nsso.back) or a ?return=<site> link (nsso.ret) and still has to
|
||||
// finish it after signing in. False while it waits on the wallet step (nsso.wait): the dashboard must not bounce it back and forth.
|
||||
const pendingBack = req => { const c = cookies(req); return !!(c['nsso.back'] || retOf(req)) && !c['nsso.wait']; };
|
||||
// the wallet was just linked: the next hop when a way back is waiting (2026-11-17), else null
|
||||
const afterWallet = req => { const c = cookies(req); return c['nsso.back'] || retOf(req) ? '/sso/resume' : null; };
|
||||
// the name of the site a member is on the way back to, for a line on the provider's dashboard; null when none
|
||||
function backName(req) {
|
||||
const c = cookies(req); const ret = retOf(req);
|
||||
if (ret) return siteName(ret.site);
|
||||
if (!c['nsso.back']) return null;
|
||||
const r = new URLSearchParams(c['nsso.back']).get('r'); return siteName(r || (C && C.peer) || '') || null;
|
||||
}
|
||||
|
||||
module.exports = { init, handle, page, seen, enabled, pendingBack, afterWallet, backName, siteBase, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES, hubOn, hubCreds, signOutEverywhere, mintHub, verifyHub, _hubSeen: t => { hubSeen = t == null ? Date.now() : t; hubChecked = Date.now(); }, _pinged: pinged, _hubSites: o => { if (o) { hubSites = o; hubSitesAt = Date.now(); } return hubSites; } };
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
// Promo days (Marty 2026-11-17, "Network Weekend", Black Friday to Cyber Monday 2026): a reusable date-to-percent bonus map, cloned
|
||||
// from Five Dollar Friday (friday.js). Any package bought on a mapped Central day, at or above that day's minimum, earns that day's
|
||||
// bonus percent of its on-chain credits (purchased-grade, labelled in the credit log), once per purchase tx across app copies
|
||||
// (marks.js, MySQL), with a purchase notice that names the day. Future holidays = a new map in the promoDays setting, no code.
|
||||
//
|
||||
// The 2026 map (DEFAULT_DAYS): Fri 11-27 Black Friday +40% $5+, Sat 11-28 and Sun 11-29 +20% $5+, Mon 11-30 Cyber Monday +30% $20+.
|
||||
// Each day is midnight to midnight Central. A mapped day that is a Friday is paid by friday.js at max(fridayBonusPct, the day's pct)
|
||||
// (fridayPct below), so Black Friday is ONE bonus per tx at 40%, the free 7-day Game Pass perk still fires, and nobody flips
|
||||
// fridayBonusPct by hand; normal Five Dollar Friday (+20%) resumes on 12-04 by itself.
|
||||
//
|
||||
// Also here, all date-gated to the weekend window (weekendStart..weekendEnd, Fri 11-27 00:00 CT to Tue 12-01 00:00 CT):
|
||||
// - Weekend Starter Bundle: a $20+ pack also gets the LinkSpin code (setting weekendLinkspinCode, default WEEKEND500) in its notice
|
||||
// - Builder Bundle: a $100+ pack is listed for DownlineHydra (GET /api/network/weekend-builders); DH grants Pro, 25 comps
|
||||
// - Game Pass bonus days for tier passes fulfilled Fri 11-27 00:00 CT to Fri 12-04 00:00 CT (passBonusDays, read by gamepass.js)
|
||||
// - the chatbot fact and answer, the /api/promodays view for the strip, Overview card and /weekend page
|
||||
//
|
||||
// Settings (siteConfig): promoDaysOn '1'|'0' (kill switch), promoDays (JSON {"YYYY-MM-DD": {pct, minCents, name}}), weekendStart /
|
||||
// weekendEnd / weekendPassEnd (ISO), weekendLinkspinCode, weekendBuilderCap (24: DH keeperGrantsLeft 49 on 11-17, minus 5 PRO_PENDING, keeps a 20-grant reserve), promoMailBase (link base for emails, default the share domain instantadpay.link).
|
||||
// Test clock: env IAP_TEST_NOW (ISO), ignored when NODE_ENV=production. Copy rules: no em dashes, Central times, no income promises.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let X = {}, FILE = null, S = null;
|
||||
const TZ = 'America/Chicago';
|
||||
const dayOf = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
|
||||
const weekdayOf = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, weekday: 'short' });
|
||||
const CREDITS_LINE = 'Ad credits buy advertising, not income.';
|
||||
|
||||
const DEFAULT_DAYS = {
|
||||
'2026-11-27': { pct: 40, minCents: 500, name: 'Black Friday' },
|
||||
'2026-11-28': { pct: 20, minCents: 500, name: 'Network Weekend Saturday' },
|
||||
'2026-11-29': { pct: 20, minCents: 500, name: 'Network Weekend Sunday' },
|
||||
'2026-11-30': { pct: 30, minCents: 2000, name: 'Cyber Monday' }
|
||||
};
|
||||
const DEFAULTS = {
|
||||
weekendStart: '2026-11-27T00:00:00-06:00', weekendEnd: '2026-12-01T00:00:00-06:00', weekendPassEnd: '2026-12-04T00:00:00-06:00',
|
||||
weekendLinkspinCode: 'WEEKEND500', weekendStarterMinCents: 2000, weekendBuilderMinCents: 10000, weekendBuilderCap: 24,
|
||||
passBonus: { explorer: 15, champion: 15, legend: 60 } // days on top of the tier's own (30, 30, 365)
|
||||
};
|
||||
|
||||
function now() {
|
||||
const o = process.env.NODE_ENV !== 'production' && process.env.IAP_TEST_NOW; const t = o ? Date.parse(o) : NaN;
|
||||
return Number.isNaN(t) ? Date.now() : t;
|
||||
}
|
||||
function init(opts) { X = opts || {}; FILE = path.join(opts.dataDir, 'promodays.json'); S = load(); }
|
||||
function load() { try { return Object.assign({ granted: {}, bundles: {} }, JSON.parse(fs.readFileSync(FILE, 'utf8'))); } catch (e) { return { granted: {}, bundles: {} }; } }
|
||||
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
|
||||
async function claimOnce(key) { try { return X.marks ? await X.marks.claim(key) : true; } catch (e) { return true; } }
|
||||
|
||||
function cfg() {
|
||||
const c = (X.siteConfig && X.siteConfig()) || {};
|
||||
let days = DEFAULT_DAYS;
|
||||
if (c.promoDays) { try { const j = typeof c.promoDays === 'string' ? JSON.parse(c.promoDays) : c.promoDays; if (j && typeof j === 'object') days = j; } catch (e) { console.error('promoDays setting is not valid JSON, using the built-in map'); } }
|
||||
const ms = (k) => { const t = Date.parse(c[k] || DEFAULTS[k]); return Number.isNaN(t) ? Date.parse(DEFAULTS[k]) : t; };
|
||||
return {
|
||||
on: String(c.promoDaysOn == null ? '1' : c.promoDaysOn) === '1',
|
||||
days, start: ms('weekendStart'), end: ms('weekendEnd'), passEnd: ms('weekendPassEnd'),
|
||||
lsCode: String(c.weekendLinkspinCode || DEFAULTS.weekendLinkspinCode).toUpperCase().replace(/[^A-Z0-9_-]/g, '').slice(0, 24),
|
||||
starterMin: Number(c.weekendStarterMinCents) || DEFAULTS.weekendStarterMinCents,
|
||||
builderMin: Number(c.weekendBuilderMinCents) || DEFAULTS.weekendBuilderMinCents,
|
||||
builderCap: Math.max(0, Number(c.weekendBuilderCap == null ? DEFAULTS.weekendBuilderCap : c.weekendBuilderCap) || 0),
|
||||
mailBase: String(c.promoMailBase || 'https://instantadpay.link').replace(/\/+$/, ''), // instantadpay.com is on the Spamhaus DBL (still listed 2026-11-17): email links use the share domain
|
||||
passBonus: DEFAULTS.passBonus,
|
||||
tiersOn: String(c.sovTiers) === '1' // the tier passes are only on sale with sovTiers; the pass bonus days are only said while they are
|
||||
};
|
||||
}
|
||||
// the mapped day at ts, or null: { day, pct, minCents, name }
|
||||
function dayAt(ts) {
|
||||
const c = cfg(); if (!c.on) return null;
|
||||
const d = dayOf(ts); const e = c.days[d];
|
||||
if (!e || !(Number(e.pct) > 0)) return null;
|
||||
return { day: d, pct: Number(e.pct), minCents: Math.max(0, Number(e.minCents) || 0), name: String(e.name || 'Promo day').slice(0, 60) };
|
||||
}
|
||||
// friday.js asks: the promo percent for a Friday purchase (0 = none), so Black Friday is paid there, once, at the higher rate
|
||||
function fridayPct(ts, cents) { const d = dayAt(ts); return d && weekdayOf(ts) === 'Fri' && (cents == null || cents >= d.minCents) ? d.pct : 0; }
|
||||
function fridayName(ts) { const d = dayAt(ts); return d && weekdayOf(ts) === 'Fri' ? d.name : ''; }
|
||||
function inWeekend(ts) { const c = cfg(); return c.on && ts >= c.start && ts < c.end; }
|
||||
function weekendLive(t) { return inWeekend(t == null ? now() : t); }
|
||||
// Game Pass bonus days for a tier pass fulfilled at ts (gamepass.js extend, via 'package' only; comps never get them)
|
||||
function passBonusDays(tier, ts) {
|
||||
const c = cfg(); if (!c.on || !(ts >= c.start && ts < c.passEnd)) return 0;
|
||||
return Number(c.passBonus[tier]) || 0;
|
||||
}
|
||||
const usdOf = cents => ('$' + (cents / 100).toFixed(2)).replace(/\.00$/, '');
|
||||
const tsOf = ev => (Number(ev.ts) > 1e12 ? Number(ev.ts) : (Number(ev.ts) > 0 ? Number(ev.ts) * 1000 : Date.now()));
|
||||
|
||||
// the bonus on a mapped non-Friday day (Fridays are paid by friday.js), and the bundle notices on any weekend day
|
||||
async function onEvent(ev) {
|
||||
if (!ev || ev.type !== 'Purchase') return null;
|
||||
const ts = tsOf(ev); const cents = Number(ev.priceCents) || 0;
|
||||
const out = { bonus: 0, starter: false, builder: false };
|
||||
const d = dayAt(ts);
|
||||
if (d && weekdayOf(ts) !== 'Fri' && cents >= d.minCents && !S.granted[ev.tx] && await claimOnce('pd:' + ev.tx)) {
|
||||
const bonus = Math.round((Number(ev.creditAmount) || 0) * d.pct / 100);
|
||||
const a = bonus > 0 && X.accounts ? await X.accounts.byMemberId(ev.buyerId) : null;
|
||||
if (a && a.email) {
|
||||
await X.ads.addEarned(a.email, bonus, { purchased: true, log: { kind: 'bonus', note: d.name + ': +' + d.pct + '% on your ' + usdOf(cents) + ' package', ref: 'pd:' + String(ev.tx).slice(0, 30) } });
|
||||
S.granted[ev.tx] = { day: d.day, memberId: ev.buyerId, bonus, pct: d.pct, at: Date.now() }; save();
|
||||
out.bonus = bonus;
|
||||
try { await X.notify(ev.buyerId, d.name + ': +' + bonus + ' bonus credits', 'Your ' + usdOf(cents) + ' package landed on ' + d.name + ', so ' + bonus + ' bonus ad credits (+' + d.pct + '%) were added to your balance. ' + CREDITS_LINE + ' See your balance: https://instantadpay.com/my#campaigns\n\nEvery Network Weekend deal across the network: https://instantadpay.com/weekend', 'notice'); } catch (e) {}
|
||||
}
|
||||
}
|
||||
if (inWeekend(ts) && cents >= cfg().starterMin && !S.bundles[ev.tx] && await claimOnce('pdb:' + ev.tx)) {
|
||||
const c = cfg(); const builder = cents >= c.builderMin;
|
||||
const wallet = builder ? await walletOf(ev) : '';
|
||||
S.bundles[ev.tx] = { memberId: ev.buyerId, cents, at: ts, builder, wallet }; save();
|
||||
out.starter = true; out.builder = builder;
|
||||
const lines = ['Your ' + usdOf(cents) + ' package came in during Network Weekend, so it carries the Weekend Starter Bundle: a ' + '500-credit LinkSpin code, ' + c.lsCode + '. Enter it at https://linkspin.app (same email as here, one per account).'];
|
||||
if (builder) lines.push('It is also a Builder Bundle: DownlineHydra Pro is on its way to the wallet that paid' + (wallet ? ' (' + wallet.slice(0, 6) + '...' + wallet.slice(-4) + ')' : '') + ', free, while the first ' + c.builderCap + ' comps last. If that wallet already holds Pro, nothing changes. It lands within the hour; check https://downlinehydra.com.');
|
||||
lines.push(CREDITS_LINE);
|
||||
try { await X.notify(ev.buyerId, 'Network Weekend: your bundle extras', lines.join('\n\n'), 'notice'); } catch (e) {}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// the buying position's wallet: the chain index first (MemberActivated), then a contract read
|
||||
async function walletOf(ev) {
|
||||
const id = Number(ev.buyerId) || 0; if (!id || !X.chain) return '';
|
||||
try { for (const e of X.chain.recentEvents(1e9)) if (e.type === 'MemberActivated' && Number(e.id) === id && e.account) return String(e.account).toLowerCase(); } catch (e) {}
|
||||
try { const m = await X.chain.member(id); return m && m.account ? String(m.account).toLowerCase() : ''; } catch (e) { return ''; }
|
||||
}
|
||||
// GET /api/network/weekend-builders (DownlineHydra pulls it): every $100+ package in the window, from the chain index, never a counter
|
||||
async function builders() {
|
||||
const c = cfg(); const out = [];
|
||||
let evs = []; try { evs = X.chain.recentEvents(1e9); } catch (e) {}
|
||||
for (const ev of evs) {
|
||||
if (ev.type !== 'Purchase' || (Number(ev.priceCents) || 0) < c.builderMin) continue;
|
||||
const ts = tsOf(ev); if (!(ts >= c.start && ts < c.end)) continue;
|
||||
const wallet = (S.bundles[ev.tx] && S.bundles[ev.tx].wallet) || await walletOf(ev);
|
||||
if (wallet) out.push({ wallet, txHash: ev.tx, usdCents: Number(ev.priceCents), at: new Date(ts).toISOString() });
|
||||
}
|
||||
return { start: new Date(c.start).toISOString(), end: new Date(c.end).toISOString(), cap: c.builderCap, builders: out.sort((a, b) => a.at < b.at ? -1 : 1) };
|
||||
}
|
||||
|
||||
// the public view for the strip, Overview card and /weekend page
|
||||
function view(t) {
|
||||
const c = cfg(); t = t == null ? now() : t;
|
||||
const d = dayAt(t); const live = inWeekend(t);
|
||||
// nothing about the deals is published before Thanksgiving Thursday 00:00 CT (24 h before the start)
|
||||
if (t < c.start - 86400000) return { on: c.on, live: false, today: null, days: [], startsAt: new Date(c.start).toISOString(), endsAt: new Date(c.end).toISOString(), published: false };
|
||||
const list = Object.entries(c.days).sort().map(([k, v]) => ({ day: k, name: v.name, pct: Number(v.pct), minUsd: (Number(v.minCents) || 0) / 100 }));
|
||||
let st = null;
|
||||
if (d) { let packs = 0, usd = 0; try { for (const ev of X.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.priceCents >= d.minCents && dayOf(tsOf(ev)) === d.day) { packs++; usd += ev.priceCents / 100; } } catch (e) {}
|
||||
st = { packs, usd, bonusCredits: Object.values(S.granted).filter(g => g.day === d.day).reduce((s, g) => s + g.bonus, 0) }; }
|
||||
return { on: c.on, live, today: d ? { day: d.day, name: d.name, pct: d.pct, minUsd: d.minCents / 100, stats: st } : null, days: list,
|
||||
startsAt: new Date(c.start).toISOString(), endsAt: new Date(c.end).toISOString(), passEndsAt: new Date(c.passEnd).toISOString(),
|
||||
published: true, passBonusLive: c.on && c.tiersOn && t >= c.start && t < c.passEnd, passBonus: c.passBonus, lsCode: live ? c.lsCode : null, builderCap: c.builderCap, note: CREDITS_LINE };
|
||||
}
|
||||
|
||||
// Thanksgiving: friday.js sends this instead of the normal Thursday copy when tomorrow is a mapped Friday (one message)
|
||||
function thursdayCopy(nextFridayKey) {
|
||||
const c = cfg(); const d = c.on && c.days[nextFridayKey]; if (!d) return null;
|
||||
const B = c.mailBase;
|
||||
return { subject: d.name + ' starts at midnight: Network Weekend',
|
||||
text: 'Network Weekend starts tonight at midnight Central and runs Black Friday to Cyber Monday, midnight to midnight.\n\n'
|
||||
+ 'On InstantAdPay:\n'
|
||||
+ 'Black Friday (Fri 11-27): +40% bonus ad credits on any $5+ pack, and the same pack gives you a free 7-day Game Pass.\n'
|
||||
+ 'Saturday and Sunday: +20% bonus ad credits on any $5+ pack.\n'
|
||||
+ 'Cyber Monday (Mon 11-30): +30% bonus ad credits on any $20+ pack.\n'
|
||||
+ 'Any $20+ pack also gets a 500-credit LinkSpin code. Any $100+ pack also gets DownlineHydra Pro free, while the first ' + c.builderCap + ' comps last.\n'
|
||||
+ 'Code NETWORKWEEKEND: 300 bonus ad credits, one per account, from midnight.\n\n'
|
||||
+ 'Every pack still pays its sponsor line in the same transaction, at the full price. ' + CREDITS_LINE + '\n\n'
|
||||
+ 'Every network site has its own weekend deal: ' + B + '/weekend\n'
|
||||
+ 'Line up your pack: ' + B + '/my#buy' };
|
||||
}
|
||||
// the chatbot (chatbot.js): a fact for the system prompt and one answer, only while the weekend (or the Game Pass days) is on
|
||||
function chatFact(t) {
|
||||
const c = cfg(); t = t == null ? now() : t;
|
||||
if (!c.on || t < c.start - 86400000 || t >= (c.tiersOn ? c.passEnd : c.end)) return '';
|
||||
if (t < c.start) return '- NETWORK WEEKEND (starts Fri 2026-11-27 00:00 Central, tomorrow): Black Friday to Cyber Monday, midnight to midnight Central. Not live yet: say it starts at midnight; deals at https://instantadpay.com/weekend.\n';
|
||||
if (t >= c.end) return !c.tiersOn ? '' : '- NETWORK WEEKEND is over (it ended Mon 11-30 at midnight Central). Still on until Thu 12-03 23:59 Central: tier Game Pass bonus days (Explorer and Champion 45 days, Legend 365 + 60). Five Dollar Friday is back to +20% on $5+ from Fri 12-04.\n';
|
||||
return '- NETWORK WEEKEND (LIVE now, Fri 11-27 00:00 to Mon 11-30 23:59 Central, midnight to midnight): Black Friday +40% bonus ad credits on any $5+ pack (instead of the usual Five Dollar Friday +20%, never both) plus the free 7-day Game Pass; Saturday and Sunday +20% on $5+; Cyber Monday +30% on $20+. Weekend Starter Bundle: any $20+ pack gets the LinkSpin code ' + c.lsCode + ' (500 LinkSpin credits, shown on the purchase notice). Builder Bundle: any $100+ pack gets DownlineHydra Pro free for the paying wallet, first ' + c.builderCap + ' comps, nobody is paid on a comp. Code NETWORKWEEKEND: 300 bonus ad credits, paid in 5 daily installments as the member finishes the daily ad set, one per account, new and existing accounts, valid until Mon 11-30 23:59 Central.' + (c.tiersOn ? ' Tier Game Pass bonus days through Thu 12-03 23:59 Central (Explorer and Champion 45 days, Legend 365 + 60).' : '') + ' Every pack pays its sponsor line in full. No price is cut on InstantAdPay. All deals: https://instantadpay.com/weekend. Ad credits buy advertising, not income; never promise income.\n';
|
||||
}
|
||||
const CHAT_RE = /(black friday|cyber monday|network weekend|weekend (deal|sale|bonus|promo|special)s?|thanksgiving|bundle|networkweekend|friday (bonus|promo|deal|special)|five dollar friday)/i;
|
||||
function chatAnswer(msg, t) {
|
||||
const c = cfg(); t = t == null ? now() : t;
|
||||
if (!c.on || !CHAT_RE.test(String(msg || '')) || t < c.start - 86400000 || t >= c.end) return null;
|
||||
if (t < c.start) return 'Network Weekend starts tonight at midnight Central and runs Black Friday to Cyber Monday, midnight to midnight. Black Friday: +40% bonus ad credits on any $5+ pack plus a free 7-day Game Pass. Saturday and Sunday: +20% on $5+. Cyber Monday: +30% on $20+. Any $20+ pack adds a 500-credit LinkSpin code, any $100+ pack adds DownlineHydra Pro while the first ' + c.builderCap + ' comps last, and code NETWORKWEEKEND gives 300 bonus ad credits from midnight. Every deal: https://instantadpay.com/weekend. ' + CREDITS_LINE;
|
||||
const d = dayAt(t);
|
||||
return 'Network Weekend is on now, midnight to midnight Central through Cyber Monday. ' + (d ? 'Today is ' + d.name + ': +' + d.pct + '% bonus ad credits on any ' + usdOf(d.minCents) + '+ pack' + (weekdayOf(t) === 'Fri' ? ' (this replaces the usual Five Dollar Friday +20%), plus a free 7-day Game Pass' : '') + '. ' : '')
|
||||
+ 'Saturday and Sunday are +20% on $5+, Cyber Monday is +30% on $20+. Any $20+ pack also gets the LinkSpin code ' + c.lsCode + ' (500 LinkSpin credits) on your purchase notice, and any $100+ pack gets DownlineHydra Pro free for the paying wallet while the first ' + c.builderCap + ' comps last. Code NETWORKWEEKEND gives 300 bonus ad credits over 5 days of your daily ad set, one per account. Buy under My account > Buy packages: https://instantadpay.com/my#buy. Every deal on the network: https://instantadpay.com/weekend. ' + CREDITS_LINE;
|
||||
}
|
||||
|
||||
module.exports = { init, cfg, dayAt, fridayPct, fridayName, inWeekend, weekendLive, passBonusDays, onEvent, builders, view, thursdayCopy, chatFact, chatAnswer, now, DEFAULT_DAYS, CREDITS_LINE };
|
||||
@@ -4,6 +4,8 @@
|
||||
// the dashboard. One redemption per code per account; every redemption is logged; optional
|
||||
// cap (max uses) and expiry; codes can be switched off. Storage: MySQL promo_codes +
|
||||
// promo_redemptions, or DATA_DIR/promos.json.
|
||||
// Start time (2026-11-17, Network Weekend code NETWORKWEEKEND): `starts` (ms, 0 = at once) keeps a code dormant until then, so a
|
||||
// weekend code can be created ahead and opens by itself. Test clock: env IAP_TEST_NOW, ignored when NODE_ENV=production.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const db = require('./db');
|
||||
@@ -15,6 +17,7 @@ const norm = c => String(c || '').trim().toUpperCase().replace(/[^A-Z0-9_-]/g, '
|
||||
const STEPS = 5;
|
||||
const WINDOW_DAYS = 30;
|
||||
const stepOf = credits => Math.ceil(Number(credits) / STEPS);
|
||||
const nowMs = () => { const o = process.env.NODE_ENV !== 'production' && process.env.IAP_TEST_NOW; const t = o ? Date.parse(o) : NaN; return Number.isNaN(t) ? Date.now() : t; };
|
||||
|
||||
const J = {
|
||||
db: { v: 1, codes: {}, redemptions: [] },
|
||||
@@ -35,8 +38,8 @@ const D = {
|
||||
async get(code) { const r = await db.q('SELECT * FROM promo_codes WHERE code=?', [code]); return r[0] ? row(r[0]) : null; },
|
||||
async list() { return (await db.q('SELECT * FROM promo_codes ORDER BY created DESC')).map(row); },
|
||||
async put(c) {
|
||||
await db.q('INSERT INTO promo_codes (code,credits,partner,note,max_uses,expires,active,created,funder) VALUES (?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE funder=VALUES(funder), credits=VALUES(credits), partner=VALUES(partner), note=VALUES(note), max_uses=VALUES(max_uses), expires=VALUES(expires), active=VALUES(active)',
|
||||
[c.code, c.credits, c.partner || null, c.note || null, c.maxUses || 0, c.expires || 0, c.active ? 1 : 0, c.created || Date.now(), c.funder || null]);
|
||||
await db.q('INSERT INTO promo_codes (code,credits,partner,note,max_uses,expires,active,created,funder,starts) VALUES (?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE funder=VALUES(funder), credits=VALUES(credits), partner=VALUES(partner), note=VALUES(note), max_uses=VALUES(max_uses), expires=VALUES(expires), active=VALUES(active), starts=VALUES(starts)',
|
||||
[c.code, c.credits, c.partner || null, c.note || null, c.maxUses || 0, c.expires || 0, c.active ? 1 : 0, c.created || Date.now(), c.funder || null, c.starts || 0]);
|
||||
return this.get(c.code);
|
||||
},
|
||||
async uses(code) { const r = await db.q('SELECT COUNT(*) n FROM promo_redemptions WHERE code=?', [code]); return Number(r[0].n); },
|
||||
@@ -46,7 +49,7 @@ const D = {
|
||||
async markPaid(code, email, paid, lastDay) { await db.q('UPDATE promo_redemptions SET paid=?, last_day=? WHERE code=? AND email=?', [paid, lastDay, code, email]); },
|
||||
async redemptions(code, n) { const rows = code ? await db.q('SELECT * FROM promo_redemptions WHERE code=? ORDER BY ts DESC LIMIT ?', [code, Number(n) || 200]) : await db.q('SELECT * FROM promo_redemptions ORDER BY ts DESC LIMIT ?', [Number(n) || 200]); return rows.map(r => ({ code: r.code, email: r.email, credits: Number(r.credits), via: r.via, ts: Number(r.ts) })); }
|
||||
};
|
||||
const row = r => ({ code: r.code, funder: r.funder || null, credits: Number(r.credits), partner: r.partner || '', note: r.note || '', maxUses: Number(r.max_uses) || 0, expires: Number(r.expires) || 0, active: !!Number(r.active), created: Number(r.created) });
|
||||
const row = r => ({ code: r.code, funder: r.funder || null, credits: Number(r.credits), partner: r.partner || '', note: r.note || '', maxUses: Number(r.max_uses) || 0, expires: Number(r.expires) || 0, active: !!Number(r.active), created: Number(r.created), starts: Number(r.starts) || 0 });
|
||||
const impl = () => db.enabled() ? D : J;
|
||||
|
||||
function init(opts) { DATA_DIR = opts.dataDir; if (!db.enabled()) J.load(); }
|
||||
@@ -54,7 +57,7 @@ async function create(c) {
|
||||
const code = norm(c.code); if (!code || code.length < 3) return { error: 'Code must be 3 to 24 letters or numbers.' };
|
||||
const credits = Math.floor(Number(c.credits)); if (!(credits > 0) || credits > 100000) return { error: 'Credits must be between 1 and 100,000.' };
|
||||
const cur = await impl().get(code);
|
||||
const saved = await impl().put({ code, credits, funder: c.funder ? String(c.funder).toLowerCase() : (cur && cur.funder) || null, partner: String(c.partner || '').slice(0, 80), note: String(c.note || '').slice(0, 200), maxUses: Math.max(0, Math.floor(Number(c.maxUses) || 0)), expires: c.expires ? Number(new Date(c.expires)) || 0 : 0, active: c.active !== false && c.active !== 0 && c.active !== '0', created: cur ? cur.created : Date.now() });
|
||||
const saved = await impl().put({ code, credits, funder: c.funder ? String(c.funder).toLowerCase() : (cur && cur.funder) || null, partner: String(c.partner || '').slice(0, 80), note: String(c.note || '').slice(0, 200), maxUses: Math.max(0, Math.floor(Number(c.maxUses) || 0)), expires: c.expires ? Number(new Date(c.expires)) || 0 : 0, starts: c.starts ? Number(new Date(c.starts)) || 0 : (c.starts === undefined && cur ? cur.starts || 0 : 0), active: c.active !== false && c.active !== 0 && c.active !== '0', created: cur ? cur.created : Date.now() });
|
||||
return { ok: true, code: saved };
|
||||
}
|
||||
async function setActive(code, active) { const c = await impl().get(norm(code)); if (!c) return { error: 'No such code.' }; await impl().put(Object.assign(c, { active: !!active })); return { ok: true }; }
|
||||
@@ -62,7 +65,8 @@ async function setActive(code, active) { const c = await impl().get(norm(code));
|
||||
async function check(code, email) {
|
||||
const k = norm(code); if (!k) return { error: 'Enter a promo code.' };
|
||||
const c = await impl().get(k); if (!c || !c.active) return { error: 'That promo code is not valid.' };
|
||||
if (c.expires && Date.now() > c.expires) return { error: 'That promo code has expired.' };
|
||||
if (c.starts && nowMs() < c.starts) return { error: 'That promo code opens ' + new Date(c.starts).toLocaleString('en-US', { timeZone: 'America/Chicago', weekday: 'long', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central.' };
|
||||
if (c.expires && nowMs() > c.expires) return { error: 'That promo code has expired.' };
|
||||
if (email && await impl().redeemed(k, email)) return { error: 'You already used that promo code.' };
|
||||
if (c.maxUses && (await impl().uses(k)) >= c.maxUses) return { error: 'That promo code has been fully redeemed.' };
|
||||
return null;
|
||||
|
||||
@@ -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=20261112ln">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261118rd">
|
||||
<style>
|
||||
.adm-table{width:100%;table-layout:auto}
|
||||
.adm-table th{cursor:pointer;user-select:none;white-space:nowrap}
|
||||
@@ -652,8 +652,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
||||
<script src="/assets/admin.js?v=20261115la"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-kits.js?v=20261101th"></script>
|
||||
<script src="/assets/tankready.js?v=20261118rd"></script><script src="/assets/admin.js?v=20261120tx"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-kits.js?v=20261101th"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -300,7 +300,13 @@
|
||||
// ready = wallet linked: activation is held (never the company) until someone adopts them or the 24-hour safety net assigns them (2026-10-27)
|
||||
const left = w => { const ms = (w.holdUntil || 0) - Date.now(); if (ms <= 0) return 'assigning now'; const m = Math.round(ms / 60000); return (m >= 60 ? Math.floor(m / 60) + ' h ' + (m % 60) + ' min' : m + ' min') + ' left'; };
|
||||
const rb = w => (w.opensAt > Date.now() ? ' <span class="badge amber" title="New sign-up: hand adoption opens 24 hours after they joined">Opens ' + when(w.opensAt) + '</span>' : '') + (w.ready ? ' <span class="badge" style="background:var(--ok-soft);border-color:var(--ok);color:var(--ok)">Ready to activate · ' + left(w) + '</span>' : '');
|
||||
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + rb(w) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>')
|
||||
// readiness (2026-11-18, network hub): hottest first, stage + heat + last action + how they got here; the hub down = the old table
|
||||
const RD = window.TankReady; const rdOn = RD && r.waiting.some(w => w.rd);
|
||||
const wl = rdOn ? r.waiting.slice().sort((a, b) => RD.score(b) - RD.score(a)) : r.waiting;
|
||||
const rs = r.readiness || {}; const rc = rs.counts || {}; const cnt = o => Object.entries(o || {}).sort((a, b) => b[1] - a[1]).map(([k, v]) => k + ' ' + v).join(', ');
|
||||
$('tankAdmSub').textContent += rs.on ? (rs.ok === false ? ' · readiness: hub not answering (' + (rs.error || '') + ')' : rc.n ? ' · readiness: how they got here ' + cnt(rc.reasons) + ' · stages ' + cnt(rc.stages) + ' · heat ' + cnt(rc.bands) : ' · readiness: loading') : ' · readiness off';
|
||||
const cols = rdOn ? 5 : 4;
|
||||
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th>' + (rdOn ? '<th>Readiness (hottest first)</th>' : '') + '</tr>' + (wl.length ? wl.map(w => '<tr><td>' + esc(w.name) + rb(w) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td>' + (rdOn ? '<td>' + (w.rd ? RD.html(w.rd) : '<span class="muted small">no answer</span>') + '</td>' : '') + '</tr>').join('') : '<tr><td colspan="' + cols + '" class="muted">empty</td></tr>')
|
||||
+ ((r.aligned || []).length ? '<tr><th colspan="4">Aligned to their network sponsor (LinkSpin) instead of the tank</th></tr>' + r.aligned.slice(0, 15).map(x => '<tr><td>' + esc(x.email) + '</td><td>' + esc(x.toName || x.to) + '</td><td class="when">' + when(x.at) + '</td><td class="muted">' + esc(x.via || '') + '</td></tr>').join('') : '');
|
||||
$('tankAdopt').innerHTML = '<tr><th>Member</th><th>Adopted by</th><th>When</th><th>Window ends</th><th>Status</th></tr>' + (r.adoptions.length ? r.adoptions.map(a => '<tr><td>' + esc(a.adopteeName) + '</td><td>' + esc(a.adopterName) + '</td><td class="when">' + when(a.ts) + '</td><td class="when">' + (a.status === 'released' || a.status === 'invited' ? '' : when(a.expires)) + '</td><td>' + esc(a.status) + '</td></tr>').join('') : '<tr><td colspan="5" class="muted">none yet</td></tr>');
|
||||
} catch (e) {}
|
||||
@@ -1146,7 +1152,7 @@
|
||||
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 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'],
|
||||
synRateDivisorText: ['Network rate divisor for TEXT ads (N)', 'Network Ad Space text-ad views cost 1/N of the on-site text rate (1 = the same as on-site, 1 credit per 100 views since 2026-11-20); 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'],
|
||||
|
||||
@@ -58,7 +58,7 @@ window.IAP = (function () {
|
||||
+ '<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="/disclaimer">Earnings Disclaimer</a><a href="/privacy">Privacy</a></div>'
|
||||
+ '<div style="margin-top:10px">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</div>';
|
||||
+ '<div style="margin-top:10px">© 2026 TrustClickz</div>';
|
||||
document.body.appendChild(f);
|
||||
renderNetworkLine(f);
|
||||
}
|
||||
@@ -104,6 +104,12 @@ window.IAP = (function () {
|
||||
// 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();
|
||||
// Network Weekend (2026-11-17): the network ribbon (netweekend.js, every page) and the weekend strip / Overview card (weekend-card.js,
|
||||
// Home and /my). Both switch on and off by date inside the scripts themselves, so outside the window they show nothing.
|
||||
[['/assets/netweekend.js?v=20261117nw', 'iap'], ['/assets/weekend-card.js?v=20261117nw', '']].forEach(([src, site]) => {
|
||||
if (document.querySelector('script[src^="' + src.split('?')[0] + '"]')) return;
|
||||
const t = document.createElement('script'); t.src = src; t.defer = true; if (site) t.setAttribute('data-site', site); document.head.appendChild(t);
|
||||
});
|
||||
async function refreshNavWallet() {
|
||||
try {
|
||||
const me = await (await fetch('/api/me')).json();
|
||||
|
||||
@@ -336,6 +336,8 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
{ k: 'earned', label: 'Surf earnings', v: m => m.earned || 0 },
|
||||
{ k: 'balance', label: 'Earned balance', v: m => m.balance || 0 },
|
||||
{ k: 'name', label: 'Name', v: m => String(m.name || '').toLowerCase(), str: true },
|
||||
// holding tank only (2026-11-18): the network heat score, hottest first by default (a lead the hub has no answer for sorts last)
|
||||
{ k: 'heat', label: 'Heat', v: m => (window.TankReady ? TankReady.score(m) : -1), only: 'tank' },
|
||||
];
|
||||
const LIST_FILTERS = [
|
||||
{ k: 'today', label: 'Active today', t: m => activeToday(m) },
|
||||
@@ -344,8 +346,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
{ k: 'nopay', label: 'Wallet, payouts off', t: m => !!m.wallet && !m.activated },
|
||||
{ k: 'payouts', label: 'Payouts on', t: m => !!m.activated },
|
||||
{ k: 'nowallet', label: 'No wallet', t: m => !m.wallet },
|
||||
{ k: 'pulse', label: 'Warm or hot', t: m => !!(m.rd && m.rd.heat && m.rd.heat.score >= 40), only: 'tank' },
|
||||
];
|
||||
const listState = key => LIST_UI[key] || (LIST_UI[key] = { sort: 'seen', dir: -1, on: new Set(), q: '' });
|
||||
const listState = key => LIST_UI[key] || (LIST_UI[key] = { sort: key === 'tank' ? 'heat' : '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) {
|
||||
@@ -360,9 +363,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
const st = listState(key); const hide = (opts && opts.hide) || [];
|
||||
const bar = document.createElement('div'); bar.className = 'lst-bar';
|
||||
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>'
|
||||
+ '<label class="lst-sort">Sort <select aria-label="Sort by">' + LIST_SORTS.filter(s => !s.only || s.only === key).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-chips">' + LIST_FILTERS.filter(f => !hide.includes(f.k) && (!f.only || f.only === key)).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 || '';
|
||||
@@ -935,6 +938,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
if (name === 'profile') loadLineBanner();
|
||||
if (name === 'line') { buildLineJump(); loadLineage(); loadUplineMessages(); loadCoach(); loadLinkStats(); loadProspects(); }
|
||||
if (name === 'campaigns') ['cTarget', 'cImage', 'cVideoUrl'].forEach(id => { if ($(id)) $(id).value = ''; }); // no residual URL between visits
|
||||
if (name === 'campaigns' && /(^|&)video=/.test(paneQ)) prefillVideoAd(paneQ); // /my#campaigns?video=...: the video ad form filled in (Video App Income's "Run this on InstantAdPay", 2026-11-22)
|
||||
if (name === 'training') { if (/(^|&)g=leader/.test(paneQ)) loadTraining.filter = 'Leader tools'; loadTraining(); }
|
||||
if (name === 'pipeline') loadPipeline();
|
||||
if (name === 'promo') { const ps = /(^|&)s=([a-z]+)/.exec(paneQ || ''); if (ps) setPromoSub(ps[2]); }
|
||||
@@ -990,6 +994,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
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.nssoBackTo && !me.nssoBack && !me.address && !render.walletAsk) { render.walletAsk = true; setTimeout(() => IAP.status(me.nssoBackTo + ' signs you in with your wallet. Link it here on the Wallet tab (one free signature) and you go straight back to ' + me.nssoBackTo + '.'), 2500); } // after the sign-in toasts (daily bonus), and it stays up // waiting on the wallet step (2026-11-17)
|
||||
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)
|
||||
@@ -1019,7 +1024,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
setPane(location.hash.slice(1) || 'overview');
|
||||
$('campGate').hidden = !!me.memberId;
|
||||
$('earnGate').hidden = !!me.memberId;
|
||||
if (me.username && !me.address) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); }
|
||||
if (me.username && !me.address && !render.walletAsk) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); }
|
||||
loadDashboard();
|
||||
if (window.IAPSupport) IAPSupport.badge(); // Help badge: Marty replied to a ticket
|
||||
|
||||
@@ -1343,7 +1348,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
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 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); }
|
||||
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 === 1 ? ' Text ads are one price everywhere: 1 credit buys ' + (Number(r.rates && r.rates.textBatch) || 100) + ' text views, here or on the network.' : 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>'
|
||||
@@ -1542,6 +1547,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
$('cSizeRow').hidden = t !== 'banner';
|
||||
$('cTitleRow').hidden = t !== 'text' && t !== 'solo';
|
||||
$('cBodyRow').hidden = t !== 'text';
|
||||
if ($('cAiRow')) $('cAiRow').hidden = t !== 'text' || !aiWriterOn;
|
||||
$('cSoloRow').hidden = t !== 'solo';
|
||||
$('cSoloHint').hidden = t !== 'solo';
|
||||
$('cVideoRow').hidden = t !== 'video';
|
||||
@@ -1562,6 +1568,28 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
if (t === 'featured') featHint();
|
||||
}
|
||||
$('cType').addEventListener('change', applyType);
|
||||
// the AI ad writer (Marty 2026-11-17): 3 text ads the network hub writes only from the member's own Target URL; picking one fills
|
||||
// the headline and ad text to edit. Shown only when the hub answers it is on.
|
||||
var aiWriterOn = false;
|
||||
(async () => {
|
||||
if (!$('cAiRow')) return;
|
||||
try { const w = await (await fetch('/api/my/adwriter')).json(); aiWriterOn = !!(w && w.on); } catch (e) { aiWriterOn = false; }
|
||||
applyType();
|
||||
const box = $('cAiList'); let opts = [];
|
||||
const escA = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
$('cAiWrite').onclick = async () => {
|
||||
const url = $('cTarget').value.trim(); box.hidden = false;
|
||||
if (!/^https?:\/\/\S+\.\S+/i.test(url)) { box.innerHTML = '<p class="small" style="margin:0">Put your link in the Target URL box first (starting with https://), then tap the button again.</p>'; $('cTarget').focus(); return; }
|
||||
$('cAiWrite').disabled = true; box.innerHTML = '<p class="small muted" style="margin:0">Reading your page and writing 3 ads. This takes a few seconds...</p>';
|
||||
let r; try { r = await api('/api/my/adwriter', { url }); } catch (e) { r = { error: e.message || 'The ad writer did not answer. Try again in a minute.' }; }
|
||||
$('cAiWrite').disabled = false;
|
||||
if (r.error) { box.innerHTML = '<p class="small" style="margin:0">' + escA(r.error) + '</p>'; return; }
|
||||
opts = r.options || [];
|
||||
box.innerHTML = '<p class="small muted" style="margin:0 0 6px">Tap one to use it. Check every word is true for your offer before you create the campaign.' + (typeof r.left === 'number' ? ' Ad writes left today: ' + r.left + '.' : '') + '</p>'
|
||||
+ opts.map((o, i) => '<button type="button" class="btn sec small" data-ai="' + i + '" style="display:block;width:100%;text-align:left;margin:0 0 6px;white-space:normal"><b>' + escA(o.headline) + '</b><br><span class="small">' + escA(o.line || '') + '</span></button>').join('');
|
||||
box.querySelectorAll('button[data-ai]').forEach(b => { b.onclick = () => { const o = opts[Number(b.dataset.ai)]; $('cTitle').value = o.headline; $('cBody').value = o.line || ''; box.hidden = true; IAP.status('Filled in. Edit it as you like, then create your campaign.', 'ok'); }; });
|
||||
};
|
||||
})();
|
||||
let featStartDay = 0; // selected start-day offset (0 = today)
|
||||
async function featHint() {
|
||||
if (!lastRates || !lastRates.featuredDurations) return;
|
||||
@@ -1782,6 +1810,22 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
v.onerror = () => fin(null); setTimeout(() => fin(null), 8000); v.src = url;
|
||||
});
|
||||
}
|
||||
// /my#campaigns?video=<https .mp4>&to=<https page>&title=&cta=&secs= (2026-11-22): a partner site's button opens the watch-to-earn video form
|
||||
// with the member's own video filled in. Fields only: the member still sets the budget and presses the button, and the server validates as usual.
|
||||
function prefillVideoAd(q) {
|
||||
let p; try { p = new URLSearchParams(q); } catch (e) { return; }
|
||||
const video = String(p.get('video') || '');
|
||||
if (!/^https:\/\/[^\s"'<>]{4,300}\.(mp4|webm)$/i.test(video)) return;
|
||||
const ct = $('cType'); if (!ct || !$('cVideoUrl')) return;
|
||||
ct.value = 'video'; ct.dispatchEvent(new Event('change'));
|
||||
const put = (id, v, max) => { v = String(v || '').replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, max); if ($(id) && v) $(id).value = v; };
|
||||
const to = String(p.get('to') || ''); if (/^https:\/\/[^\s"'<>]{4,300}$/i.test(to)) put('cTarget', to, 300);
|
||||
put('cName', p.get('title'), 60); put('cVideoTitle', p.get('title'), 80); put('cCtaLabel', p.get('cta'), 30);
|
||||
$('cVideoUrl').value = video; $('cVideoUrl').dispatchEvent(new Event('change')); // reads the size, so portrait goes to Shorts
|
||||
const want = Number(p.get('secs')), pick = () => { videoHint(); const s = $('cWatchSecs'); if (s && [].some.call(s.options, o => Number(o.value) === want)) { s.value = String(want); videoHint(); } };
|
||||
pick(); setTimeout(pick, 1500); setTimeout(pick, 4000); // the rates may still be loading on a fresh page
|
||||
setTimeout(() => { try { $('cVideoUrl').scrollIntoView({ block: 'center' }); if ($('cBudget')) $('cBudget').focus({ preventScroll: true }); } catch (e) {} }, 300);
|
||||
}
|
||||
function showVidOrient() {
|
||||
const el = $('cVideoInfo'); if (!el) return;
|
||||
if (!cVidDims) return;
|
||||
@@ -1972,8 +2016,10 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
el.innerHTML = '';
|
||||
el.appendChild(listBar('tank', r.waiting.length, rows.length, () => renderTank(el, r), { hide: ['payouts'] })); // nobody in the tank has payouts on
|
||||
const readyBadge = w => w.ready ? ' <span class="badge" style="background:var(--ok-soft);border-color:var(--ok);color:var(--ok)" title="Wallet linked. If nobody adopts them, the site assigns them to the next eligible adopter when the time runs out.">Ready to activate \u00b7 ' + (w.holdUntil > Date.now() ? holdLeft(w.holdUntil - Date.now()) + ' left' : 'assigning now') + '</span>' : '';
|
||||
el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '<div class="lin-row"><span class="nm">' + esc(w.name) + (opens(w) ? opensBadge(w) : readyBadge(w)) + '</span>'
|
||||
+ '<span class="em">joined ' + ago(w.joined) + '<span class="sp wrap">' + memberChips(w) + '</span></span>'
|
||||
// readiness (2026-11-18, network hub): stage, heat, last action and how they got here under each lead; none when the hub is down
|
||||
const rdHtml = w => (w.rd && window.TankReady ? TankReady.html(w.rd) : '');
|
||||
el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '<div class="lin-row' + (w.rd ? ' rd-row' : '') + '"><span class="nm">' + esc(w.name) + (opens(w) ? opensBadge(w) : readyBadge(w)) + '</span>'
|
||||
+ '<span class="em">joined ' + ago(w.joined) + '<span class="sp wrap">' + memberChips(w) + '</span>' + rdHtml(w) + '</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 your search or filters.</p>');
|
||||
@@ -2975,7 +3021,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
{ file: 'iap-wired-wednesday-1200x630.jpg', size: '1200×630 · Wired Wednesday · social card, link previews, Daily News' },
|
||||
{ file: 'iap-wired-wednesday-1080x1080.jpg', size: '1080×1080 · Wired Wednesday · Instagram, Facebook, Telegram' },
|
||||
{ file: 'iap-wired-wednesday-728x90.png', size: '728×90 · Wired Wednesday · leaderboard' },
|
||||
{ file: 'iap-wired-wednesday-300x250.png', size: '300×250 · Wired Wednesday · rectangle' } ] },
|
||||
{ file: 'iap-wired-wednesday-300x250.png', size: '300×250 · Wired Wednesday · rectangle' },
|
||||
{ file: 'iap-wired-wednesday-wide.png', size: '600×300 · Wired Wednesday · traffic exchanges, splash pages' },
|
||||
{ file: 'iap-wired-wednesday-small.png', size: '250×250 · Wired Wednesday · small square' } ] },
|
||||
{ title: 'Five Dollar Friday · share with your /friday link', friday: true, items: [
|
||||
{ file: 'iap-five-dollar-friday-october-1200x630.jpg', size: '1200×630 · Five Dollar Friday · October porch, bright' },
|
||||
{ file: 'iap-five-dollar-friday-october-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · October porch, square' },
|
||||
@@ -2983,7 +3031,15 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
{ file: 'iap-five-dollar-friday-dark-1200x630.jpg', size: '1200×630 · Five Dollar Friday · dark studio' },
|
||||
{ file: 'iap-five-dollar-friday-v2-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · square for Instagram and feeds' } ] },
|
||||
{ title: '600×300 · traffic exchanges and splash pages', items: [
|
||||
{ file: 'iap-advertise-earn-600x300.png', size: '600×300 · advertise and earn · traffic exchanges, splash pages, safelist mailers' } ] },
|
||||
{ file: 'iap-advertise-earn-600x300.png', size: '600×300 · advertise and earn · traffic exchanges, splash pages, safelist mailers' },
|
||||
{ file: 'iap-core-wide.png', size: '600×300 · advertise and earn · Join free' },
|
||||
{ file: 'iap-ledger-wide.png', size: '600×300 · advertising that pays you on-chain · See the ledger' },
|
||||
{ file: 'iap-team-wide.png', size: '600×300 · build your team with one link · Join free' } ] },
|
||||
{ title: '250×250 · small squares', items: [
|
||||
{ file: 'iap-core-small.png', size: '250×250 · advertise and earn · Join free' },
|
||||
{ file: 'iap-earn-small.png', size: '250×250 · advertise and earn · globe art' },
|
||||
{ file: 'iap-ledger-small.png', size: '250×250 · advertising that pays you on-chain · See the ledger' },
|
||||
{ file: 'iap-team-small.png', size: '250×250 · one link, your team · Join free' } ] },
|
||||
{ title: '1200×630 · social posts, link previews, Daily News covers', items: [
|
||||
{ file: 'iap-hero-1200x630.png', size: '1200×630 · hero · advertise and earn' },
|
||||
{ file: 'iap-advertise-earn-1200x630.jpg', size: '1200×630 · advertise and earn instantly, locked in code' },
|
||||
@@ -3000,7 +3056,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
{ file: 'iap-five-dollar-friday-1200x630.jpg', size: '1200×630 · social card, Daily News, feed posts' },
|
||||
{ file: 'iap-five-dollar-friday-1080x1080.jpg', size: '1080×1080 · Instagram, Facebook, Telegram' },
|
||||
{ file: 'iap-five-dollar-friday-728x90.png', size: '728×90 · leaderboard' },
|
||||
{ file: 'iap-five-dollar-friday-300x250.png', size: '300×250 · rectangle' } ] },
|
||||
{ file: 'iap-five-dollar-friday-300x250.png', size: '300×250 · rectangle' },
|
||||
{ file: 'iap-five-dollar-friday-wide.png', size: '600×300 · traffic exchanges, splash pages' },
|
||||
{ file: 'iap-five-dollar-friday-small.png', size: '250×250 · small square' } ] },
|
||||
{ title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [
|
||||
{ file: 'iap-1080x1080.png', size: '1080×1080 · square' },
|
||||
{ file: 'iap-1080x1920.png', size: '1080×1920 · story / reel' } ] },
|
||||
@@ -3019,7 +3077,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
{ file: 'iap-advertise-earn-v2-336x280.png', size: '336×280 · advertise and earn · variant 2' },
|
||||
{ file: 'iap-300x250.png', size: '300×250 · rectangle' },
|
||||
{ file: 'iap-advertise-earn-300x250.png', size: '300×250 · advertise and earn instantly' },
|
||||
{ file: 'iap-team-build-link-300x250.jpg', size: '300×250 · team build and instant payments · "link in the description"' },
|
||||
{ file: 'iap-team-box.png', size: '300×250 · build your team with one link · Join free' },
|
||||
{ file: 'iap-125x125.png', size: '125×125 · square button' } ] },
|
||||
{ title: 'Skyscrapers · 160×600, 120×600', items: [
|
||||
{ file: 'iap-160x600.png', size: '160×600 · wide skyscraper' },
|
||||
@@ -3035,7 +3093,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
if (bridge) {
|
||||
// the bridge page with this member's referral: any public page + ?ref sets the sponsor cookie
|
||||
const inv = (document.getElementById('inviteLine') || {}).textContent || '';
|
||||
const fl = inv.replace(/\/join\/([^/?#]+).*$/, '/' + bridge.page + '?ref=$1');
|
||||
// the invite line is the share link (https://<share>/<user>) or the old /join/<user> form (2026-11-17: the share form never matched, so the bridge link was the plain invite)
|
||||
const im = /\/(?:join\/)?([A-Za-z0-9_]{1,40})\/?(?:[?#].*)?$/.exec(inv.trim());
|
||||
const fl = im ? (SHARE_DOMAIN ? 'https://' + SHARE_DOMAIN : location.origin) + '/' + bridge.page + '?ref=' + im[1] : inv;
|
||||
const note = document.createElement('div');
|
||||
note.className = 'pb-note';
|
||||
note.innerHTML = '<span>Post any of these with your ' + esc(bridge.name) + ' link: <b class="mono"></b></span>';
|
||||
@@ -3046,7 +3106,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
grid.before(note);
|
||||
}
|
||||
for (const b of g.items) {
|
||||
const url = location.origin + '/banners/' + b.file;
|
||||
const url = (SHARE_DOMAIN ? 'https://' + SHARE_DOMAIN : location.origin) + '/banners/' + b.file; // share hosts serve /banners/* in place (2026-11-17, instantadpay.com is on Spamhaus DBL)
|
||||
const d = document.createElement('div');
|
||||
d.className = 'pb-item';
|
||||
d.innerHTML = '<img src="/banners/' + b.file + '?v=4" alt="InstantAdPay banner ' + b.size + '" loading="lazy">'
|
||||
@@ -3433,7 +3493,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
$('linkBtn').addEventListener('click', busy($('linkBtn'), async () => {
|
||||
IAP.status('Check your wallet for the free link signature…');
|
||||
const lr = await IAPWallet.signIn(); // server binds the wallet to the signed-in email account
|
||||
if (lr && lr.next) { IAP.status('Wallet linked. Taking you back to PolHunter…', 'ok'); setTimeout(() => { location.href = lr.next; }, 700); return; } // they came from PolHunter: close the loop
|
||||
if (lr && lr.next) { IAP.status('Wallet linked. Taking you back to ' + (lr.backTo || 'PolHunter') + '…', 'ok'); setTimeout(() => { location.href = lr.next; }, 700); return; } // they came from PolHunter or another network site: close the loop (2026-11-17)
|
||||
IAP.status('Wallet linked. Earnings pay there from now on.', 'ok');
|
||||
await render();
|
||||
}));
|
||||
@@ -3477,6 +3537,12 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
try { await navigator.clipboard.writeText($('inviteLine').textContent); IAP.status('Link copied.', 'ok'); }
|
||||
catch (e) { IAP.status('Copy failed. Select and copy the link text.', 'bad'); }
|
||||
});
|
||||
if ($('logoutAllLink')) $('logoutAllLink').addEventListener('click', async e => { // every network site (2026-11-15)
|
||||
e.preventDefault();
|
||||
let r = {}; try { r = await (await fetch('/api/auth/logout-everywhere', { method: 'POST' })).json(); } catch (er) {}
|
||||
IAP.status(r.everywhere ? 'Signed out on every network site.' : 'Signed out here. The other network sites could not be reached just now, so sign out there too.', r.everywhere ? 'ok' : 'bad');
|
||||
await render();
|
||||
});
|
||||
$('logoutLink').addEventListener('click', async e => {
|
||||
e.preventDefault();
|
||||
await fetch('/api/auth/logout', { method: 'POST' });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 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 any of those sites shows here (ViralAdBlitz, DownlineHydra and 5xYourTeam added 2026-11-15)
|
||||
// feed (GET <site>/api/promo-kit?u=<username>), so a creative or line changed on any of those sites shows here (ViralAdBlitz, DownlineHydra and 5xYourTeam added 2026-11-15, ViralAdSource and YourProgramBuilder 2026-11-17)
|
||||
// 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 () {
|
||||
@@ -7,7 +7,10 @@ window.IAPNetKits = (function () {
|
||||
{ key: 'dlb', name: 'Downline Banners', feed: 'https://downlinebanners.com/api/promo-kit', blurb: 'One global line of $5 banner spots on Polygon. A spot buys 300 guaranteed views on the board and a place in the line; every sale is split on-chain in the same transaction. Nothing is promised: a spot is paid only when spots sell after it.' },
|
||||
{ key: 'vbb', name: 'Viral Banner Blitz', feed: 'https://viralbannerblitz.com/api/promo-kit', blurb: 'One shared loop of 125x125 banners. Network members post free once a day, real visitors push the loop, and a banner that rides out earns network ad views. Weekly leaderboards for visitors sent. Advertising, not income.' },
|
||||
{ key: 'vab', name: 'ViralAdBlitz', feed: 'https://viraladblitz.com/api/promo-kit', blurb: 'Your free text ad shows on your whole team\'s pages, five levels deep. A $5 Boost adds 500 views; every Boost is split on-chain in the same transaction. Nothing is promised.' },
|
||||
{ key: 'vas', name: 'ViralAdSource', feed: 'https://viraladsource.com/api/promo-kit', blurb: 'Post a free text ad that anyone can reshare with their own link, and watch its family tree grow branch by branch. A $5 Boost puts an ad on top of the reshare board for 7 days; every Boost is split on-chain in the same transaction. Nothing is promised.' },
|
||||
{ key: 'ypb', name: 'YourProgramBuilder', feed: 'https://yourprogrambuilder.com/api/promo-kit', blurb: 'Plant a program you already use, free, and network members save their own IDs in it. A visitor who comes through you sees your link first. At 10 saved IDs it goes to review for the Crypto Team Build Network builder. A $10 Spotlight buys 1,000 views, split by the contract. Nothing is promised.' },
|
||||
{ key: 'dh', name: 'DownlineHydra', feed: 'https://downlinehydra.com/api/promo-kit', blurb: 'One join, many heads: one free account and one sponsor line across the network, plus the downline builder for the programs you promote. Pro is $30 one time, never a subscription, split on-chain. Nothing is promised.' },
|
||||
{ key: 'vai', name: 'Video App Income', feed: 'https://videoappincome.com/api/promo-kit', blurb: 'Short promo videos made from your phone: type a topic, paste a link, and about a minute later there is a finished video with a voice, captions and music on its own tracked page. The first video is free. Credit purchases are split on-chain in the same transaction. Nothing is promised.' },
|
||||
{ key: 'fivex', name: '5xYourTeam', feed: 'https://5xyourteam.com/api/promo-kit', blurb: 'The weekly draft for people who need a sponsor. A $10 position lets you draft people waiting in the holding tank and coach them. Nothing is promised.' }
|
||||
];
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
@@ -34,21 +37,21 @@ window.IAPNetKits = (function () {
|
||||
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');
|
||||
const fromHere = u => String(u).replace(/([?&]src=)[a-z0-9]+/gi, '$1iap'); // also inside copy and HTML that already carry a tracked link (ViralAdSource 2026-11-17)
|
||||
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('')
|
||||
+ '<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(fromHere(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('');
|
||||
+ k.lines.map(fromHere).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('');
|
||||
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(fromHere(k.email.body)) + '</div><div class="pb-actions">' + cb(k.email.subject, 'Copy subject') + ' ' + cb(fromHere(k.email.body), 'Copy email', '') + '</div></div>';
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Social posts</h3></div>' + k.posts.map(fromHere).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;
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
host.appendChild(box);
|
||||
var list = FALLBACK, ref = refCookie();
|
||||
var paint = function () {
|
||||
box.innerHTML = (hasLegal ? '' : '<span style="flex-basis:100%"><a href="/terms">Terms</a> · <a href="/disclaimer">Earnings Disclaimer</a> · <a href="/privacy">Privacy</a> · <a href="/contract">Contract</a> · <a href="/ledger">Ledger</a> · <a href="/support">Support</a></span>') + '<span style="flex-basis:100%">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</span><b>Part of the network</b><span>One account across the network:</span>' + list.map(function (s) {
|
||||
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%">© 2026 TrustClickz</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(withRef(s, ref)) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>';
|
||||
}).join('');
|
||||
};
|
||||
@@ -31,4 +31,6 @@
|
||||
fetch('/api/me', { credentials: 'same-origin' }).then(function (r) { return r.json(); }).then(function (m) { if (m && m.signedIn && m.username && okRef(m.username)) { ref = m.username; paint(); } }).catch(function () {});
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
||||
// Network Weekend ribbon (2026-11-17): date-gated inside netweekend.js; loaded once even when common.js loads it too
|
||||
if (!document.querySelector('script[src^="/assets/netweekend.js"]')) { var t = document.createElement('script'); t.src = '/assets/netweekend.js?v=20261117nw'; t.defer = true; t.setAttribute('data-site', me); document.head.appendChild(t); }
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// "Network Weekend" ribbon (Marty 2026-11-17): a thin bar at the top of every network site page while a network event is live.
|
||||
// Data: /api/network-deals (netdeals.js, from the hub). Switches on and off by this page's own clock at the event's exact
|
||||
// startsAt / endsAt (US Central midnights), so a cached feed never shows it early or late, and it takes itself down at endsAt on
|
||||
// a page left open. Shows this site's own deal for today (byDay, Central date) and links to the full deals page.
|
||||
// The same file lives in every network site. Never RM Circle, never the games. No inline styles (CSP): styles go through CSSOM.
|
||||
// Test clock: window.__NW_NOW (ms) before this script runs; nothing else.
|
||||
(function () {
|
||||
if (window.__nwRibbon) return; window.__nwRibbon = 1;
|
||||
var tag = document.currentScript;
|
||||
var meAttr = (tag && tag.getAttribute('data-site')) || '';
|
||||
function now() { return typeof window.__NW_NOW === 'number' ? window.__NW_NOW : Date.now(); }
|
||||
// late November is CST (UTC-6) for every date this ribbon covers
|
||||
function ctDay(ms) { return new Date(ms - 6 * 3600 * 1000).toISOString().slice(0, 10); }
|
||||
function closedKey(id, day) { return 'nw.closed.' + id + '.' + day; }
|
||||
function isClosed(id, day) { try { return window.localStorage.getItem(closedKey(id, day)) === '1'; } catch (e) { return false; } }
|
||||
function setClosed(id, day) { try { window.localStorage.setItem(closedKey(id, day), '1'); } catch (e) {} }
|
||||
var bar = null;
|
||||
function remove() { if (bar && bar.parentNode) bar.parentNode.removeChild(bar); bar = null; }
|
||||
function paint(body) {
|
||||
var me = meAttr || (body && body.self) || '';
|
||||
var t = now();
|
||||
var ev = ((body && body.events) || []).filter(function (e) { return t >= Date.parse(e.startsAt) && t < Date.parse(e.endsAt); })[0];
|
||||
if (!ev) { remove(); return false; }
|
||||
var day = ctDay(t);
|
||||
if (isClosed(ev.id, day)) { remove(); return true; }
|
||||
var mine = (ev.deals || []).filter(function (d) { return d.site === me && t < Date.parse(d.endsAt || ev.endsAt); })[0];
|
||||
var line = mine ? ((mine.byDay && mine.byDay[day]) || mine.text) : '';
|
||||
var label = (ev.days && ev.days[day]) || '';
|
||||
if (label && line.indexOf(label + ': ') === 0) line = line.slice(label.length + 2); // "Black Friday, Black Friday: ..." reads once
|
||||
var onDealsPage = !!ev.url && (function () { try { var u = new URL(ev.url); return location.pathname === u.pathname && (location.hostname === u.hostname || me === 'iap'); } catch (e) { return false; } })();
|
||||
remove();
|
||||
bar = document.createElement('div');
|
||||
bar.className = 'nw-ribbon'; bar.setAttribute('role', 'region'); bar.setAttribute('aria-label', ev.name);
|
||||
bar.style.cssText = 'position:relative;z-index:50;display:flex;flex-wrap:wrap;gap:4px 12px;align-items:center;justify-content:center;padding:8px 40px 8px 16px;'
|
||||
+ 'background:#14161b;color:#f4f1e8;font:600 13.5px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;text-align:center;border-bottom:2px solid #f2c94c';
|
||||
// built node by node with CSSOM styles: no style attributes, so a strict CSP (style-src 'self') has nothing to block
|
||||
function el(tagName, css, text) { var n = document.createElement(tagName); if (css) n.style.cssText = css; if (text) n.textContent = text; return n; }
|
||||
var head = el('span'); head.appendChild(el('b', 'color:#f2c94c', ev.name)); if (label) head.appendChild(document.createTextNode(' · ' + label));
|
||||
bar.appendChild(head);
|
||||
var body2 = el('span', 'font-weight:500', line || ev.tagline);
|
||||
if (line && mine && mine.note) { body2.appendChild(document.createTextNode(' ')); body2.appendChild(el('span', 'opacity:.75', mine.note)); }
|
||||
bar.appendChild(body2);
|
||||
if (ev.url && !onDealsPage) { var a = el('a', 'color:#f2c94c;text-decoration:underline', 'See every deal'); a.href = ev.url; a.target = '_blank'; a.rel = 'noopener'; bar.appendChild(a); }
|
||||
var x = el('button', 'position:absolute;right:8px;top:50%;transform:translateY(-50%);background:none;border:0;color:#f4f1e8;font-size:18px;line-height:1;cursor:pointer;padding:4px 8px', '×');
|
||||
x.type = 'button'; x.setAttribute('aria-label', 'Hide for today'); bar.appendChild(x);
|
||||
bar.querySelector('button').addEventListener('click', function () { setClosed(ev.id, day); remove(); });
|
||||
document.body.insertBefore(bar, document.body.firstChild);
|
||||
return true;
|
||||
}
|
||||
var feed = null, timer = null;
|
||||
function schedule() {
|
||||
clearTimeout(timer); if (!feed) return;
|
||||
// wake at the next switch moment (start, end, a deal ending, the next Central midnight), at least once a minute
|
||||
var t = now(), next = t + 60 * 1000;
|
||||
(feed.events || []).forEach(function (e) {
|
||||
[e.startsAt, e.endsAt].concat((e.deals || []).map(function (d) { return d.endsAt; })).forEach(function (s) { var x = Date.parse(s); if (x > t && x < next) next = x; });
|
||||
});
|
||||
timer = setTimeout(function () { if (typeof window.__NW_NOW === 'number') window.__NW_NOW += next - t; paint(feed); schedule(); }, Math.max(250, next - t));
|
||||
}
|
||||
function run() {
|
||||
fetch('/api/network-deals', { credentials: 'omit' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (b) {
|
||||
if (!b || !Array.isArray(b.events) || !b.events.length) return;
|
||||
feed = b; paint(b); schedule();
|
||||
}).catch(function () {});
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
||||
window.__nwPaint = function (b) { feed = b; return paint(b); }; // tests
|
||||
})();
|
||||
@@ -811,6 +811,18 @@ img{max-width:100%}
|
||||
.pipe-due{display:grid;gap:6px}
|
||||
.pipe-due .pipe-card{margin:0}
|
||||
@media (max-width:640px){.pipe-form{grid-template-columns:1fr !important}.pipe-col{flex-basis:200px}}
|
||||
/* the pipeline board fits on one screen (2026-11-20, a member: "need a bottom slide rule so we can see the entire window to the right
|
||||
without having to reduce the size"): a long column scrolls inside itself with its heading pinned, so the board's own sideways
|
||||
scrollbar stays in view; both scrollbars are wide and visible instead of the thin overlay ones */
|
||||
.pipe-col{max-height:min(68vh,760px);overflow-y:auto;overflow-x:hidden}
|
||||
.pipe-col h4{position:sticky;top:-10px;z-index:1;background:inherit;margin:-10px -10px 2px;padding:10px 10px 2px}
|
||||
.pipe-board{scrollbar-width:auto;scrollbar-color:var(--mint) transparent}
|
||||
.pipe-col{scrollbar-width:thin}
|
||||
.pipe-board::-webkit-scrollbar{height:14px}
|
||||
.pipe-board::-webkit-scrollbar-thumb{background:var(--mint);border-radius:8px;border:3px solid transparent;background-clip:padding-box}
|
||||
.pipe-board::-webkit-scrollbar-track{background:var(--line);border-radius:8px}
|
||||
.pipe-col::-webkit-scrollbar{width:8px}
|
||||
.pipe-col::-webkit-scrollbar-thumb{background:var(--line);border-radius:6px}
|
||||
/* Overview chips drill down to My line (Marty, 2026-09-15) */
|
||||
.lt-node.lt-go{cursor:pointer;transition:border-color .15s,transform .15s} .lt-node.lt-go:hover,.lt-node.lt-go:focus-visible{border-color:var(--mint);transform:translateY(-1px);outline:none}
|
||||
.lin-row.lin-focus{box-shadow:0 0 0 2px var(--mint);border-radius:10px}
|
||||
@@ -864,3 +876,18 @@ body.hasback #status{bottom:92px}
|
||||
:root[data-theme="light"] .mockup,:root[data-theme="light"] .modal-card,:root[data-theme="light"] #status,:root[data-theme="light"] #iapChatPanel,:root[data-theme="light"] .chat-drawer{box-shadow:0 18px 50px -20px rgba(11,26,20,.35)}
|
||||
:root[data-theme="light"] .bo.side-open .bo-side{box-shadow:0 0 60px rgba(11,26,20,.25)}
|
||||
:root[data-theme="light"] .plate{box-shadow:0 0 24px rgba(10,107,86,.12),inset 0 1px 0 rgba(255,255,255,.8)}
|
||||
/* ── holding-tank readiness (2026-11-18): stage chip, heat with its band, last action, how they got here. Theme tokens only. ── */
|
||||
.rd-line{display:flex;flex-wrap:wrap;gap:4px 6px;align-items:center;margin-top:4px;font-weight:400;white-space:normal}
|
||||
.rd-stage,.rd-heat{display:inline-block;font-size:11px;line-height:1.5;padding:0 7px;border-radius:999px;border:1px solid var(--line-strong);color:var(--muted);font-weight:600;font-variant-numeric:tabular-nums}
|
||||
.rd-s-warming{color:var(--cyan);border-color:var(--cyan-line);background:var(--cyan-soft)}
|
||||
.rd-s-engaged{color:var(--violet);border-color:var(--violet-line);background:var(--violet-soft)}
|
||||
.rd-s-activated{color:var(--mint);border-color:var(--mint-line);background:var(--mint-soft)}
|
||||
.rd-s-ready{color:var(--ok);border-color:var(--ok);background:var(--ok-soft)}
|
||||
.rd-hot{color:var(--bad);border-color:var(--bad);background:var(--bad-soft)}
|
||||
.rd-warm{color:var(--amber);border-color:var(--amber-line);background:var(--amber-soft)}
|
||||
.rd-cooling{color:var(--cyan);border-color:var(--cyan-line);background:var(--cyan-soft)}
|
||||
.rd-cold{color:var(--muted);border-color:var(--muted-line);background:var(--muted-soft)}
|
||||
.rd-last{font-size:11.5px;color:var(--muted)}
|
||||
.rd-entry{display:block;font-size:11.5px;color:var(--muted);font-weight:400;white-space:normal;margin-top:2px}
|
||||
.lin-row .em .rd-line,.lin-row .em .rd-entry{white-space:normal}
|
||||
.lin-row.rd-row .em{white-space:normal}
|
||||
|
||||
@@ -25,7 +25,8 @@ window.IAPSupport = (function () {
|
||||
+ '.sup-msg{border:1px solid var(--line);border-radius:12px;padding:12px 14px;margin:10px 0;background:var(--ground-soft)}.sup-msg.admin{border-color:var(--mint-line);background:var(--mint-faint)}.sup-msg.system{opacity:.8}'
|
||||
+ '.sup-msg .sm-head{font-size:12px;color:var(--muted);margin:0 0 6px;display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap}.sup-msg .sm-body{white-space:pre-wrap;word-wrap:break-word;font-size:15px;line-height:1.5}'
|
||||
+ '.sup-att{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap}.sup-att img{max-width:160px;max-height:120px;border-radius:8px;border:1px solid var(--line)}'
|
||||
+ '.sup-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}';
|
||||
+ '.sup-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}'
|
||||
+ '.sup-suggest{border:1px solid var(--mint-line);border-radius:12px;padding:10px 14px;margin:10px 0 0;background:var(--mint-faint)}.sup-sg{margin:4px 0}.sup-sg summary{cursor:pointer;font-weight:700;font-size:14px}.sup-sg .sm-body{white-space:pre-wrap;word-wrap:break-word;font-size:14px;line-height:1.5;margin:6px 0 8px}';
|
||||
document.head.appendChild(st);
|
||||
})();
|
||||
const catOptions = sel => CATS.map(c => '<option' + (c === sel ? ' selected' : '') + '>' + esc(c) + '</option>').join('');
|
||||
@@ -91,9 +92,11 @@ window.IAPSupport = (function () {
|
||||
+ '<label for="hnCat">What is it about?</label><select id="hnCat">' + catOptions('') + '</select>'
|
||||
+ '<label for="hnSubject">Subject</label><input id="hnSubject" maxlength="140" placeholder="A few words, like: my payout did not arrive">'
|
||||
+ '<label for="hnBody">Message</label><textarea id="hnBody" rows="6" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea>'
|
||||
+ '<div id="hnSuggest" class="sup-suggest" hidden aria-live="polite"></div>'
|
||||
+ attachRow('hn')
|
||||
+ '<div class="sup-actions"><button class="btn small" type="button" id="hnSend">Send to support</button><button class="btn small sec" type="button" id="hnCancel">Cancel</button><span class="small muted" id="hnMsg"></span></div></div>';
|
||||
const atts = wireAttach('hn');
|
||||
wireSuggest();
|
||||
document.getElementById('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; });
|
||||
const send = document.getElementById('hnSend');
|
||||
send.addEventListener('click', async () => {
|
||||
@@ -107,6 +110,27 @@ window.IAPSupport = (function () {
|
||||
});
|
||||
document.getElementById('hnSubject').focus();
|
||||
}
|
||||
// help answers while typing (2026-11-16): debounced, from the KB only (the hub's semantic match); a suggestion never blocks Send
|
||||
function wireSuggest() {
|
||||
const box = document.getElementById('hnSuggest'), subj = document.getElementById('hnSubject'), body = document.getElementById('hnBody');
|
||||
if (!box || !subj || !body) return;
|
||||
let timer = null, seq = 0, last = '';
|
||||
const run = async () => {
|
||||
const text = (subj.value + ' ' + body.value).replace(/\s+/g, ' ').trim();
|
||||
if (text.replace(/[^A-Za-z0-9]/g, '').length < 10) { box.hidden = true; box.innerHTML = ''; last = ''; return; }
|
||||
if (text === last) return; last = text; const mine = ++seq;
|
||||
let r; try { r = await call('/api/my/support/suggest', { subject: subj.value, body: body.value }); } catch (e) { return; }
|
||||
if (mine !== seq || !document.body.contains(box)) return;
|
||||
const items = (r && r.items) || [];
|
||||
if (!items.length) { box.hidden = true; box.innerHTML = ''; return; }
|
||||
box.innerHTML = '<p class="small" style="margin:0 0 6px"><b>These answers may help</b> <span class="muted">You can still send your ticket.</span></p>'
|
||||
+ items.map(i => '<details class="sup-sg"><summary>' + esc(i.title) + (i.site ? ' <span class="muted small">(' + esc(i.site) + ')</span>' : '') + (i.fromTicket ? ' <span class="muted small">from a past ticket</span>' : '') + '</summary>'
|
||||
+ '<div class="sm-body">' + linkify(i.answer) + (i.link && i.site ? '<br><a href="' + esc(i.link) + '" target="_blank" rel="noopener">Open ' + esc(i.site) + '</a>' : '') + '</div></details>').join('');
|
||||
box.hidden = false;
|
||||
};
|
||||
const kick = () => { clearTimeout(timer); timer = setTimeout(run, 700); };
|
||||
subj.addEventListener('input', kick); body.addEventListener('input', kick);
|
||||
}
|
||||
async function openMine(ref) {
|
||||
const host = document.getElementById('helpBody'); if (!host) return;
|
||||
helpState.open = ref;
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// "How to get fed leads" (holding tank batches, Marty 2026-11-15): the ladder and the member's own level and next step, on the
|
||||
// Overview. Hidden while the tankBatches switch is off (/api/my/tank/feed answers { on:false }). Leads you can sponsor, never money.
|
||||
(function () {
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const day = t => t ? new Date(t).toLocaleString('en-US', { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'America/Chicago' }) + ' CT' : '';
|
||||
function mount() {
|
||||
let el = document.getElementById('tankFeedCard'); if (el) return el;
|
||||
el = document.createElement('div'); el.className = 'card'; el.id = 'tankFeedCard'; el.hidden = true; el.setAttribute('data-jump', 'How to get fed leads');
|
||||
const notice = document.getElementById('tankNotice'); const host = notice && notice.closest('.card');
|
||||
const tankCard = document.getElementById('tankCard');
|
||||
if (host && host.parentNode) host.parentNode.insertBefore(el, host.nextSibling);
|
||||
else if (tankCard && tankCard.parentNode) tankCard.parentNode.insertBefore(el, tankCard);
|
||||
else return null;
|
||||
return el;
|
||||
}
|
||||
function html(v) {
|
||||
const me = v.me || {};
|
||||
const rows = (v.ladder || []).map(r => '<li><b>' + esc(r.level) + '</b>: ' + (r.level === 'Streak' ? 'up to ' : '') + r.size + ' people at a time, with ' + esc(r.how) + '</li>').join('');
|
||||
const mine = me.level
|
||||
? '<p>Your level: <b>' + esc(me.label || me.level) + '</b>, ' + me.size + ' people at a time' + (me.active ? '' : ' (sign in at least once a week to receive them)') + '.'
|
||||
+ (me.open ? ' You are helping ' + me.open + ' from your batches right now.' : '') + (me.nextBatchAt ? ' Next batch from ' + esc(day(me.nextBatchAt)) + '.' : '') + '</p>'
|
||||
: '<p>You are not on the ladder yet.</p>';
|
||||
return '<div class="card-head"><h3>How to get fed leads</h3><span class="sub">people from the holding tank you can sponsor</span></div>'
|
||||
+ '<p class="small">Members who joined with no sponsor wait in the holding tank. Active members who bought their own package receive a batch of them every ' + esc(v.everyDays) + ' days, and they become your referrals to welcome and help. These are leads you can sponsor: what happens next depends on your follow-up, and nothing here is a promise of income.</p>'
|
||||
+ '<ul class="small" style="margin:6px 0 8px 18px;padding:0">' + rows + '</ul>' + mine
|
||||
+ (me.next ? '<p class="small"><b>Next step:</b> ' + esc(me.next) + '</p>' : '')
|
||||
+ '<p class="muted small">Say hello to each new person within ' + esc(v.followDays) + ' days (a chat, or Contacted them on their row in My line). Anyone you have not contacted by then goes back to the tank for another member.</p>';
|
||||
}
|
||||
async function load() {
|
||||
try {
|
||||
const v = await (await fetch('/api/my/tank/feed', { cache: 'no-store' })).json();
|
||||
const el = mount(); if (!el) return;
|
||||
if (!v || !v.on) { el.hidden = true; return; }
|
||||
el.innerHTML = html(v); el.hidden = false;
|
||||
} catch (e) {}
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', load); else load();
|
||||
setInterval(load, 600000);
|
||||
})();
|
||||
@@ -0,0 +1,51 @@
|
||||
// Holding-tank readiness on the tank cards (Marty 2026-11-18, stage 1 of the tank warm-up). The server attaches `rd` to each waiting
|
||||
// lead from the network hub: { entry: {reason, site, at, detail}, stage, heat: {score, band, label, trend}, last: {kind, site, at} }.
|
||||
// A lead without `rd` (the hub is down) renders exactly as before. Shared by InstantAdPay and LinkSpin (same file in both).
|
||||
(function () {
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const SITES = { iap: 'InstantAdPay', instantadpay: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', dlb: 'Downline Banners',
|
||||
vbb: 'ViralBannerBlitz', vab: 'ViralAdBlitz', viraladblitz: 'ViralAdBlitz', fivex: '5xYourTeam', dh: 'DownlineHydra', downlinehydra: 'DownlineHydra', hydra: 'DownlineHydra',
|
||||
ypb: 'YourProgramBuilder', yourprogrambuilder: 'YourProgramBuilder', vas: 'ViralAdSource', viraladsource: 'ViralAdSource', ctb: 'CryptoTeamBuild',
|
||||
stackpol: 'Stack POL', earnerscorner: 'Earners Corner', polhunter: 'PolHunter', btc4hits: 'BTC4Hits' };
|
||||
const site = s => (s ? SITES[String(s).toLowerCase()] || String(s) : '');
|
||||
const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
const day = t => { if (!t) return ''; const d = new Date(t); return MON[d.getMonth()] + ' ' + d.getDate() + (d.getFullYear() !== new Date().getFullYear() ? ', ' + d.getFullYear() : ''); };
|
||||
const month = t => { if (!t) return ''; const d = new Date(t); return MON[d.getMonth()] + ' ' + d.getFullYear(); };
|
||||
const ago = t => { if (!t) return ''; const ms = Date.now() - t; if (ms < 3600e3) return Math.max(1, Math.round(ms / 60e3)) + ' min ago'; if (ms < 86400e3) return Math.round(ms / 3600e3) + 'h ago'; const d = Math.floor(ms / 86400e3); return d === 1 ? 'yesterday' : d + ' days ago'; };
|
||||
const who = d => (d && d.from ? ' @' + d.from : '');
|
||||
|
||||
function entryText(e) {
|
||||
if (!e || !e.reason || e.reason === 'unknown') return 'How they got here: unknown';
|
||||
const d = e.detail || {};
|
||||
switch (e.reason) {
|
||||
case 'joined': {
|
||||
const src = [d.via ? 'via ' + d.via : '', d.ref && d.ref !== 'direct' ? 'from ' + d.ref : d.ref === 'direct' ? 'typed in directly' : ''].filter(Boolean).join(', ');
|
||||
return 'Joined ' + (site(e.site) || 'the network') + ' ' + day(e.at) + ' with no sponsor' + (src ? ' (' + src + ')' : '');
|
||||
}
|
||||
case 'imported': return 'Imported old member of ' + (site(d.oldSite) || 'an older network site') + (d.memberSince ? ', member since ' + month(d.memberSince) : '') + (d.lastSeenOld ? ', last seen there ' + month(d.lastSeenOld) : '') + (e.at ? ' (in the tank since ' + day(e.at) + ')' : '');
|
||||
case 'rescued': return 'Moved here ' + day(e.at) + ': their sponsor' + who(d) + ' did not reach them in 14 days';
|
||||
case 'released': return d.note ? 'Released ' + day(e.at) + ' by' + (who(d) || ' the member') + ' who had adopted them' : 'Released by their sponsor' + who(d) + ' ' + day(e.at);
|
||||
case 'sponsor_gone': return 'Their sponsor left or was blocked (in the tank since ' + day(e.at) + ')';
|
||||
case 'returned': return 'Back in the tank ' + day(e.at) + ': an adoption' + (d.from ? ' by @' + d.from : '') + ' ended before they got started';
|
||||
default: return 'How they got here: unknown';
|
||||
}
|
||||
}
|
||||
const STAGE = { new: ['New', 'Nothing yet beyond joining'], warming: ['Warming', 'Visited or clicked a tracked link'], engaged: ['Engaged', 'Signed in or replied'], activated: ['Activated', 'Wallet linked'], ready: ['Ready', 'Bought something'] };
|
||||
const VERB = { signin: 'signed in', visit: 'visited', click: 'clicked a tracked link', wallet: 'linked a wallet', purchase: 'bought a package', upgrade: 'upgraded', message: 'replied to a message', share: 'shared a link' };
|
||||
function lastText(l) {
|
||||
if (!l) return 'no activity yet';
|
||||
return (VERB[l.kind] || l.kind) + (l.site ? ' on ' + site(l.site) : '') + ', ' + ago(l.at);
|
||||
}
|
||||
// the block that goes under the lead's name: stage chip, heat, last action, entry reason
|
||||
function html(rd) {
|
||||
if (!rd) return '';
|
||||
const st = STAGE[rd.stage] || STAGE.new; const h = rd.heat || { score: 0, band: 'cold', label: 'Cold' };
|
||||
const tr = h.trend === 'up' ? ' ↗' : h.trend === 'down' ? ' ↘' : '';
|
||||
return '<span class="rd-line"><span class="rd-stage rd-s-' + esc(rd.stage) + '" title="' + esc(st[1]) + '">' + esc(st[0]) + '</span>'
|
||||
+ '<span class="rd-heat rd-' + esc(h.band) + '" title="Heat 0-100 from real actions across the network, recent ones count most. Hot 70+, Warm 40-69, Cooling 15-39, Cold under 15.">' + Number(h.score || 0) + ' · ' + esc(h.label || '') + tr + '</span>'
|
||||
+ '<span class="rd-last" title="Their newest real action on the network">' + esc(lastText(rd.last)) + '</span></span>'
|
||||
+ '<span class="rd-entry">' + esc(entryText(rd.entry)) + '</span>';
|
||||
}
|
||||
const score = m => (m && m.rd && m.rd.heat ? Number(m.rd.heat.score) || 0 : -1);
|
||||
window.TankReady = { html, entryText, lastText, score, stageLabel: s => (STAGE[s] || STAGE.new)[0] };
|
||||
})();
|
||||
@@ -0,0 +1,60 @@
|
||||
// Network Weekend strip (Home, above the Five Dollar Friday strip) and Overview card (/my, above the Friday card), Marty 2026-11-17.
|
||||
// Data: /api/promodays (promodays.js). Shown only while the weekend is live (Fri 11-27 00:00 CT to Tue 12-01 00:00 CT) and, as a
|
||||
// heads-up, on Thanksgiving Thursday 11-26 Central; the page's own clock decides at the exact midnights, the server's `live` too.
|
||||
// No inline styles (CSP), no native dialogs. Test clock: window.__NW_NOW (ms).
|
||||
(function () {
|
||||
if (window.__nwCard) return; window.__nwCard = 1;
|
||||
var now = function () { return typeof window.__NW_NOW === 'number' ? window.__NW_NOW : Date.now(); };
|
||||
var ctDay = function (ms) { return new Date(ms - 6 * 3600 * 1000).toISOString().slice(0, 10); };
|
||||
var esc = function (s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); };
|
||||
var usd = function (n) { return '$' + (Number(n) % 1 ? Number(n).toFixed(2) : Number(n)); };
|
||||
var hidden = function (k) { try { return localStorage.getItem('iap-hide-nw-' + k) === '1'; } catch (e) { return false; } };
|
||||
var hide = function (k) { try { localStorage.setItem('iap-hide-nw-' + k, '1'); } catch (e) {} };
|
||||
function dayLine(v) {
|
||||
return (v.days || []).map(function (d) { return '<b>' + esc(d.name.replace(/^Network Weekend /, '')) + '</b> +' + d.pct + '% on ' + usd(d.minUsd) + '+'; }).join(' · ');
|
||||
}
|
||||
function state(v) {
|
||||
var t = now(), s = Date.parse(v.startsAt), e = Date.parse(v.endsAt);
|
||||
if (!v.on) return '';
|
||||
if (t >= s && t < e) return 'live';
|
||||
if (t >= s - 86400000 && t < s) return 'soon';
|
||||
return '';
|
||||
}
|
||||
function extras(v) {
|
||||
return 'Any $20+ pack also gets a 500-credit LinkSpin code' + (v.lsCode ? ' (<b>' + esc(v.lsCode) + '</b>)' : '') + ' on your purchase notice. Any $100+ pack also gets DownlineHydra Pro free, while the first ' + esc(v.builderCap) + ' comps last. Code <b>NETWORKWEEKEND</b>: 300 bonus ad credits, one per account.';
|
||||
}
|
||||
function paintStrip(v, st) {
|
||||
var anchor = document.getElementById('fdfStrip'); if (!anchor) return;
|
||||
var el = document.getElementById('nwStrip');
|
||||
if (!st) { if (el) el.hidden = true; return; }
|
||||
if (!el) { el = document.createElement('div'); el.className = 'fdf'; el.id = 'nwStrip'; anchor.parentNode.insertBefore(el, anchor); }
|
||||
el.hidden = false;
|
||||
el.innerHTML = st === 'live' && v.today
|
||||
? '<b>\u{1F6CD}️ Network Weekend: it’s ' + esc(v.today.name.replace(/^Network Weekend /, '')) + '.</b> +' + v.today.pct + '% bonus ad credits on any ' + usd(v.today.minUsd) + '+ pack until midnight Central. ' + extras(v) + ' ' + esc(v.note) + ' <a href="/weekend">Every deal</a>'
|
||||
: '<b>\u{1F6CD}️ Network Weekend starts at midnight Central.</b> ' + dayLine(v) + ', midnight to midnight through Cyber Monday. ' + esc(v.note) + ' <a href="/weekend">Every deal</a>';
|
||||
}
|
||||
function paintCard(v, st) {
|
||||
var anchor = document.getElementById('fdfCard'); if (!anchor) return;
|
||||
var card = document.getElementById('nwCard'); var key = st + '-' + ctDay(now());
|
||||
if (!st || hidden(key)) { if (card) card.hidden = true; return; }
|
||||
if (!card) { card = document.createElement('div'); card.className = 'card'; card.id = 'nwCard'; anchor.parentNode.insertBefore(card, anchor); }
|
||||
card.hidden = false;
|
||||
var live = st === 'live' && v.today;
|
||||
card.innerHTML = '<div class="card-head"><h3>\u{1F6CD}️ ' + (live ? 'Network Weekend: ' + esc(v.today.name.replace(/^Network Weekend /, '')) : 'Network Weekend starts at midnight') + '</h3><span class="sub">'
|
||||
+ (live ? '+' + v.today.pct + '% bonus ad credits on any ' + usd(v.today.minUsd) + '+ pack today' : 'Black Friday to Cyber Monday, Central') + '</span></div>'
|
||||
+ '<p>' + (live && v.today.stats ? '<b>' + v.today.stats.packs + '</b> pack' + (v.today.stats.packs === 1 ? '' : 's') + ' so far today. ' : '') + dayLine(v) + ', each day midnight to midnight Central. ' + extras(v) + '</p>'
|
||||
+ '<p class="muted small">' + esc(v.note) + ' Every pack pays its sponsor line in full, at the normal price.</p>'
|
||||
+ '<button class="btn" type="button" id="nwBuy">' + (live ? 'Buy my weekend pack' : 'See the packages') + '</button> <a class="btn sec" href="/weekend" target="_blank" rel="noopener">Every network deal</a>';
|
||||
var b = document.getElementById('nwBuy'); if (b) b.addEventListener('click', function () { var m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); else location.href = '/my#buy'; });
|
||||
var head = card.querySelector('.card-head'); var x = document.createElement('button');
|
||||
x.type = 'button'; x.className = 'card-x'; x.setAttribute('aria-label', 'Hide for today'); x.textContent = '×';
|
||||
x.addEventListener('click', function () { hide(key); card.hidden = true; }); head.appendChild(x);
|
||||
}
|
||||
var last = null;
|
||||
function load() {
|
||||
fetch('/api/promodays').then(function (r) { return r.ok ? r.json() : null; }).then(function (v) { if (!v) return; last = v; var st = state(v); paintStrip(v, st); paintCard(v, st); }).catch(function () {});
|
||||
}
|
||||
function run() { if (!document.getElementById('fdfStrip') && !document.getElementById('fdfCard')) return; load(); setInterval(load, 120000); }
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
||||
window.__nwCardPaint = function (v) { last = v; var st = state(v); paintStrip(v, st); paintCard(v, st); return st; }; // tests
|
||||
})();
|
||||
@@ -0,0 +1,53 @@
|
||||
/* /weekend, the Network Weekend deals page (Marty 2026-11-17). External file on purpose: the site's CSP blocks inline scripts.
|
||||
Data: /api/promodays (InstantAdPay's own days, promodays.js) and /api/network-deals (every site's deal, from the hub).
|
||||
Switches by the page's own clock at the exact Central midnights; before Thanksgiving Thursday both feeds are empty, so the page
|
||||
says only that the weekend is coming. Test clock: window.__NW_NOW (ms). */
|
||||
(function () {
|
||||
var now = function () { return typeof window.__NW_NOW === 'number' ? window.__NW_NOW : Date.now(); };
|
||||
var ctDay = function (ms) { return new Date(ms - 6 * 3600 * 1000).toISOString().slice(0, 10); };
|
||||
var esc = function (s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); };
|
||||
var usd = function (n) { return '$' + (Number(n) % 1 ? Number(n).toFixed(2) : Number(n)); };
|
||||
var label = function (k) { var p = k.split('-').map(Number); return new Date(Date.UTC(p[0], p[1] - 1, p[2], 12)).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', timeZone: 'UTC' }); };
|
||||
var stateEl = document.getElementById('nwState'), daysEl = document.getElementById('nwDays'), dealsEl = document.getElementById('nwDeals');
|
||||
if (!stateEl) return;
|
||||
// carry ?ref= onto the join button (the page is a member promo tool, like /friday)
|
||||
try { var ref = new URLSearchParams(location.search).get('ref'); if (ref && /^[A-Za-z0-9_.-]{1,40}$/.test(ref)) document.getElementById('nwJoin').href = '/join?v=weekend&ref=' + encodeURIComponent(ref); } catch (e) {}
|
||||
function renderIap(v) {
|
||||
var t = now(), s = Date.parse(v.startsAt), e = Date.parse(v.endsAt), today = ctDay(t);
|
||||
if (!v.on || !v.published) {
|
||||
stateEl.className = 'nw-state'; stateEl.innerHTML = '<span class="nw-tag">Coming</span><span><b>Network Weekend: Black Friday to Cyber Monday.</b> The deals open here on Thanksgiving.</span>';
|
||||
daysEl.innerHTML = ''; return;
|
||||
}
|
||||
if (t >= s && t < e) {
|
||||
var d = v.today || {};
|
||||
stateEl.className = 'nw-state live';
|
||||
stateEl.innerHTML = '<span class="nw-tag">Live now</span><span><b>It is ' + esc((d.name || 'Network Weekend').replace(/^Network Weekend /, '')) + '.</b> +' + esc(d.pct) + '% bonus ad credits on any ' + usd(d.minUsd) + '+ InstantAdPay pack until midnight Central.</span>'
|
||||
+ (d.stats ? '<span><b>' + Number(d.stats.packs || 0).toLocaleString('en-US') + '</b> pack' + (d.stats.packs === 1 ? '' : 's') + ' so far today</span>' : '');
|
||||
} else if (t < s) {
|
||||
var left = s - t, h = Math.floor(left / 3600000), m = Math.floor((left % 3600000) / 60000);
|
||||
stateEl.className = 'nw-state'; stateEl.innerHTML = '<span class="nw-tag">Tonight</span><span><b>Network Weekend starts at midnight Central</b>, in ' + h + 'h ' + m + 'm.</span><span>Join now so your account is ready.</span>';
|
||||
} else {
|
||||
stateEl.className = 'nw-state'; stateEl.innerHTML = '<span class="nw-tag">Ended</span><span><b>Network Weekend is over.</b> Thank you for building with us. Five Dollar Friday is back every Friday.</span>';
|
||||
}
|
||||
daysEl.innerHTML = (v.days || []).map(function (x) {
|
||||
return '<div class="nw-day' + (x.day === today && t >= s && t < e ? ' today' : '') + '"><div class="n">' + esc(label(x.day)) + '</div><h3>+' + esc(x.pct) + '% on ' + usd(x.minUsd) + '+</h3><p>' + esc(x.name) + ': bonus ad credits on any InstantAdPay pack of ' + usd(x.minUsd) + ' or more, midnight to midnight Central.</p></div>';
|
||||
}).join('');
|
||||
}
|
||||
function renderDeals(b) {
|
||||
var t = now(), today = ctDay(t);
|
||||
var ev = ((b && b.events) || []).filter(function (e) { return t >= Date.parse(e.startsAt) - 86400000 && t < Date.parse(e.endsAt); })[0];
|
||||
if (!ev) { if (!((b && b.events) || []).length) return; dealsEl.innerHTML = '<p class="muted">Network Weekend has ended.</p>'; return; }
|
||||
var deals = (ev.deals || []).filter(function (d) { return t < Date.parse(d.endsAt || ev.endsAt); });
|
||||
dealsEl.innerHTML = deals.map(function (d) {
|
||||
var text = (d.byDay && d.byDay[today]) || d.text;
|
||||
return '<div class="nw-deal"><h3>' + esc(d.name) + '</h3><p>' + esc(text) + '</p>' + (d.note ? '<p class="note">' + esc(d.note) + '</p>' : '')
|
||||
+ (d.url ? '<a class="go" href="' + esc(d.url) + '"' + (/instantadpay\.com/.test(d.url) ? '' : ' target="_blank" rel="noopener"') + '>' + (/instantadpay\.com\/weekend/.test(d.url) ? 'Buy on InstantAdPay' : 'Open ' + esc(d.name)) + '</a>' : '') + '</div>';
|
||||
}).join('');
|
||||
dealsEl.querySelectorAll('a.go').forEach(function (a) { if (/instantadpay\.com\/weekend/.test(a.href)) a.href = '/my#buy'; });
|
||||
}
|
||||
function load() {
|
||||
fetch('/api/promodays').then(function (r) { return r.ok ? r.json() : null; }).then(function (v) { if (v) renderIap(v); }).catch(function () {});
|
||||
fetch('/api/network-deals').then(function (r) { return r.ok ? r.json() : null; }).then(renderDeals).catch(function () {});
|
||||
}
|
||||
load(); setInterval(load, 60000);
|
||||
})();
|
||||
@@ -26,8 +26,8 @@
|
||||
|
||||
function fridayLine(f) {
|
||||
if (!f || !f.on) return null;
|
||||
if (f.live) return { tag: 'TODAY', text: 'It is Five Dollar Friday right now. Every package of $5 or more gets <b>20% bonus credits</b>, automatically, until midnight Central.' };
|
||||
if (f.nextLabel) return { tag: f.nextLabel, text: 'Five Dollar Friday: any package of $5 or more gets <b>' + (f.pct || 20) + '% bonus credits</b>, automatically. No code, nothing to claim.' };
|
||||
if (f.live) return { tag: 'TODAY', text: 'It is ' + (f.name || 'Five Dollar Friday') + ' right now. Every package of $5 or more gets <b>' + (f.pct || 20) + '% bonus credits</b>, automatically, until midnight Central.' }; // Black Friday 2026: +40% (promodays.js)
|
||||
if (f.nextLabel) return { tag: f.nextLabel, text: (f.name || 'Five Dollar Friday') + ': any package of $5 or more gets <b>' + (f.pct || 20) + '% bonus credits</b>, automatically. No code, nothing to claim.' };
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 105 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 75 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 87 KiB |
@@ -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=20261115nr"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script>
|
||||
<script src="/assets/bixpay-guide.js?v=20261029bz"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/contract.js?v=20260908p"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
</body>
|
||||
|
||||
@@ -265,8 +265,8 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261115nr"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script>
|
||||
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
|
||||
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
|
||||
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -97,7 +97,7 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -127,7 +127,7 @@
|
||||
</ul>
|
||||
</div>
|
||||
</div></section>
|
||||
<script src="/assets/common.js?v=20261115nr"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/friday.js?v=20260925a"></script>
|
||||
<script src="/assets/common.js?v=20261115nr"></script>
|
||||
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script>
|
||||
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/games-page.js?v=20261012b"></script>
|
||||
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/games-page.js?v=20261012b"></script>
|
||||
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -506,7 +506,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></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>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/join.js?v=20261107nc"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/launch.js?v=20260915b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></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>
|
||||
|
||||
@@ -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=20261112ln">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261120pp">
|
||||
</head>
|
||||
<body class="bo-body">
|
||||
|
||||
@@ -168,6 +168,7 @@
|
||||
<div class="bo-foot">
|
||||
<span id="navWallet" class="small muted">…</span>
|
||||
<a href="#" id="logoutLink" class="small">Log out</a>
|
||||
<a href="#" id="logoutAllLink" class="small" title="Signs you out of every network site">Sign out everywhere</a>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -576,6 +577,7 @@
|
||||
<p id="cSizeRow" hidden><select id="cSize" style="width:100%"></select></p>
|
||||
<p id="cTitleRow" hidden><input id="cTitle" placeholder="Headline (max 60)" style="width:100%"></p>
|
||||
<p id="cBodyRow" hidden><input id="cBody" placeholder="Ad text (max 140)" style="width:100%"></p>
|
||||
<div id="cAiRow" hidden style="margin:-4px 0 12px"><button type="button" class="btn sec small" id="cAiWrite">Write my ad from my link</button> <span class="small muted">Put your Target URL in first. We read that page and suggest 3 text ads using only what it says. Nothing is created until you create the campaign.</span><div id="cAiList" hidden style="margin-top:8px"></div></div>
|
||||
<div id="cSoloRow" hidden>
|
||||
<div class="ed-bar" aria-label="Formatting">
|
||||
<button type="button" data-cmd="bold" title="Bold"><b>B</b></button>
|
||||
@@ -1282,7 +1284,7 @@
|
||||
<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>
|
||||
<span style="width:100%;text-align:center;color:var(--muted)">© 2026 TrustClickz</span>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1306,13 +1308,14 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/wallet.js?v=20260911a"></script>
|
||||
<script src="/assets/promo.js?v=20261103gp"></script>
|
||||
<script src="/assets/support.js?v=20261115cb"></script>
|
||||
<script src="/assets/netkits.js?v=20261115nk"></script>
|
||||
<script src="/assets/my.js?v=20261115la"></script>
|
||||
<script src="/assets/fuel.js?v=20261113sso"></script>
|
||||
<script src="/assets/support.js?v=20261116sg"></script>
|
||||
<script src="/assets/netkits.js?v=20261123vai"></script>
|
||||
<script src="/assets/tankready.js?v=20261118rd"></script>
|
||||
<script src="/assets/my.js?v=20261120tx"></script>
|
||||
<script src="/assets/fuel.js?v=20261113sso"></script><script src="/assets/tankfeed.js?v=20261115tb"></script>
|
||||
<script src="/assets/engine-room.js?v=20261113sso"></script>
|
||||
<script src="/assets/netsso.js?v=20261113sso"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
|
||||
@@ -131,8 +131,8 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/partners.js?v=20260914a"></script>
|
||||
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
|
||||
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/plays.js?v=20260910b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/presentation.js?v=20261015b"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/presentation.js?v=20261015b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -20,9 +20,9 @@
|
||||
<div id="supMain"><div class="card"><p class="muted small">Loading…</p></div></div>
|
||||
<p class="small muted">We will never ask for your recovery phrase or private key, and nobody from InstantAdPay will message you first asking for money or wallet access.</p>
|
||||
</div></section>
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
<script src="/assets/support.js?v=20261115cb"></script>
|
||||
<script src="/assets/support.js?v=20261116sg"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/tx.js?v=20260906m"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/wall.js?v=20261030pp"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||
<script src="/assets/wallets.js?v=20260911b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/wednesday.js?v=20260929c"></script>
|
||||
<script src="/assets/common.js?v=20261115nr"></script>
|
||||
<script src="/assets/netline.js?v=20261115nr" data-site="iap"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script>
|
||||
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<!doctype html>
|
||||
<html lang="en" data-theme-base="dark">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Network Weekend: Black Friday to Cyber Monday deals across the network | InstantAdPay</title>
|
||||
<meta name="description" content="Network Weekend, Black Friday to Cyber Monday, midnight to midnight US Central: bonus ad credits on InstantAdPay and a deal on every site in the network, one account across them all.">
|
||||
<meta name="theme-color" content="#043b2f">
|
||||
<meta property="og:type" content="website"><meta property="og:site_name" content="InstantAdPay">
|
||||
<meta property="og:title" content="Network Weekend: Black Friday to Cyber Monday across the network">
|
||||
<meta property="og:description" content="Fri 11-27 to Mon 11-30, midnight to midnight US Central. Bonus ad credits on InstantAdPay and a deal on every network site. Ad credits buy advertising, not income.">
|
||||
<meta property="og:url" content="https://instantadpay.com/weekend">
|
||||
<meta name="twitter:card" content="summary">
|
||||
<!--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=20261112ln">
|
||||
<style>
|
||||
.nw{max-width:900px}
|
||||
.nw .hero{padding:44px 0 10px}
|
||||
.nw-state{display:flex;flex-wrap:wrap;align-items:center;gap:10px 18px;padding:14px 18px;border-radius:14px;border:1px solid var(--line);background:var(--mint-faint);margin:6px 0 22px;font-size:15px}
|
||||
.nw-state.live{border-color:var(--amber-line);background:var(--amber-soft)}
|
||||
.nw-tag{font-family:var(--mono);font-size:11px;letter-spacing:.14em;text-transform:uppercase;font-weight:700;padding:4px 9px;border-radius:999px;background:var(--mint);color:var(--mint-ink)}
|
||||
.nw-state.live .nw-tag{background:var(--amber)}
|
||||
.nw-days{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px;margin:0 0 24px}
|
||||
.nw-day{border:1px solid var(--line);border-radius:14px;padding:14px 16px;background:var(--ink-faint)}
|
||||
.nw-day.today{border-color:var(--amber-line);background:var(--amber-soft)}
|
||||
.nw-day .n{font-family:var(--mono);font-size:11px;letter-spacing:.12em;color:var(--mint);text-transform:uppercase}
|
||||
.nw-day h3{font-family:var(--disp);font-size:20px;margin:6px 0 4px}
|
||||
.nw-day p{margin:0;font-size:14px;color:var(--muted)}
|
||||
.nw-h2{font-family:var(--disp);font-size:22px;margin:26px 0 10px}
|
||||
.nw-deals{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:12px;margin:0 0 26px}
|
||||
.nw-deal{border:1px solid var(--line);border-radius:14px;padding:14px 16px;background:var(--ink-faint);display:flex;flex-direction:column;gap:6px}
|
||||
.nw-deal h3{font-family:var(--disp);font-size:17px;margin:0}
|
||||
.nw-deal p{margin:0;font-size:14.5px}
|
||||
.nw-deal .note{font-size:12.5px;color:var(--muted)}
|
||||
.nw-deal a.go{margin-top:auto;font-weight:700}
|
||||
.nw-cta{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin:6px 0 26px}
|
||||
.nw-rule{border-left:4px solid var(--mint);background:var(--mint-soft);padding:14px 18px;border-radius:0 12px 12px 0;margin:0 0 22px;font-size:14.5px}
|
||||
.nw-foot{margin-top:10px}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap nw">
|
||||
<section class="hero">
|
||||
<p class="eyebrow">Black Friday to Cyber Monday · US Central time · midnight to midnight</p>
|
||||
<h1>Network Weekend: <em>one account, four days, every site.</em></h1>
|
||||
<p class="lead">Friday 11-27 to Monday 11-30. Bonus ad credits on InstantAdPay every day, and a deal on every site in the network. Same price, more inside: every pack still pays its sponsor line in full.</p>
|
||||
</section>
|
||||
|
||||
<div class="nw-state" id="nwState"><span class="nw-tag">Checking</span><span>Loading today’s status…</span></div>
|
||||
|
||||
<div class="nw-days" id="nwDays"></div>
|
||||
|
||||
<div class="nw-cta">
|
||||
<a class="btn big" id="nwJoin" href="/join?v=weekend">Join free by email</a>
|
||||
<a class="btn sec" href="/my#buy">Already a member? Get your pack</a>
|
||||
</div>
|
||||
|
||||
<h2 class="nw-h2">Every deal in the network</h2>
|
||||
<div class="nw-deals" id="nwDeals"><p class="muted">The deals appear here when Network Weekend opens.</p></div>
|
||||
|
||||
<div class="nw-rule"><b>What a credit is.</b> One credit is one cent of ad delivery across the network: banners, text ads, video, verified visits, solo ads and more. Credits are not money and cannot be withdrawn. They buy advertising for your own offers. <b>Ad credits buy advertising, not income.</b> Pay with SafePal or any other crypto wallet.</div>
|
||||
|
||||
<p class="muted small nw-foot">No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment product.</p>
|
||||
<footer>
|
||||
<div>InstantAdPay · <a href="/">Home</a> · <a href="/ledger">Live ledger</a> · <a href="/friday">Five Dollar Friday</a> · <a href="/earning">How earning works</a></div>
|
||||
<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>
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/weekend.js?v=20261117nw"></script>
|
||||
<script src="/assets/common.js?v=20261117nw"></script>
|
||||
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,43 @@
|
||||
// The network ad writer client (2026-11-17): node qa/hubadwriter.test.mjs
|
||||
// A stand-in hub checks the signature and answers like network-hub lib/adwriter.js; no real hub, no model, no member.
|
||||
import http from 'node:http';
|
||||
import crypto from 'node:crypto';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
let pass = 0, fail = 0;
|
||||
const ok = (c, m, extra) => { if (c) pass++; else { fail++; console.log('FAIL', m, extra !== undefined ? JSON.stringify(extra).slice(0, 300) : ''); } };
|
||||
|
||||
const SECRET = 's'.repeat(40); let seen = [], mode = 'good';
|
||||
const hub = http.createServer((q, r) => { let b = ''; q.on('data', c => { b += c; }); q.on('end', () => {
|
||||
const sig = crypto.createHmac('sha256', SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
|
||||
r.setHeader('Content-Type', 'application/json');
|
||||
if (sig !== q.headers['x-hub-sig']) { r.statusCode = 401; return r.end('{"error":"unauthorized"}'); }
|
||||
const j = JSON.parse(b); seen.push({ path: q.url, site: q.headers['x-hub-site'], body: j });
|
||||
if (q.url === '/v1/adwriter/status') return r.end(JSON.stringify(mode === 'off' ? { on: false, daily: 5 } : { on: true, daily: 5, left: j.member ? 3 : undefined }));
|
||||
if (mode === 'limit') { r.statusCode = 429; return r.end(JSON.stringify({ ok: false, error: 'member_limit', code: 'member_limit', message: 'You have used your 5 ad writes for today.', left: 0 })); }
|
||||
if (mode === 'slow') return;
|
||||
r.end(JSON.stringify({ ok: true, options: [{ headline: 'One link for all your pages', line: 'Share one link that rotates your pages.' }], url: 'https://linkspin.app/', cached: false, left: 4 }));
|
||||
}); });
|
||||
await new Promise(r => hub.listen(0, '127.0.0.1', r));
|
||||
process.env.HUB_URL = 'http://127.0.0.1:' + hub.address().port; process.env.HUB_SECRET = SECRET; delete process.env.HUB_SITE; delete process.env.AI_WRITER;
|
||||
const aw = require(path.join(ROOT, 'hubadwriter.js'));
|
||||
|
||||
ok(await aw.enabled(), 'on when the hub says on');
|
||||
ok(seen[0].path === '/v1/adwriter/status' && seen[0].site && seen[0].site !== '__SITE__', 'signed as this site', seen[0]);
|
||||
let r = await aw.write('member-1', 'https://linkspin.app', { headline: 60, line: 90 });
|
||||
ok(r.ok && r.options.length === 1 && r.left === 4, 'options passed on', r);
|
||||
ok(seen[1].body.member === 'member-1' && seen[1].body.limits.headline === 60 && seen[1].body.limits.line === 90 && seen[1].body.url === 'https://linkspin.app', 'member, url and this site\'s limits sent', seen[1].body);
|
||||
mode = 'limit'; r = await aw.write('member-1', 'https://linkspin.app', { headline: 60, line: 90 });
|
||||
ok(r.error === 'You have used your 5 ad writes for today.' && r.status === 429 && r.left === 0, 'the hub message is shown as is', r);
|
||||
const st = await aw.status('member-1'); ok(st.on && st.left === 3, 'status for a member (left today)', st);
|
||||
mode = 'off'; aw._reset(); ok(!(await aw.enabled()), 'off when the hub says off');
|
||||
process.env.HUB_SECRET = 'w'.repeat(40); mode = 'good'; r = await aw.write('member-1', 'https://linkspin.app', { headline: 60, line: 90 });
|
||||
ok(r.code === 'hub' && /busy/.test(r.error), 'a refused signature: a friendly busy message', r);
|
||||
aw._reset(); ok(!(await aw.enabled()), 'a refused signature hides the button');
|
||||
process.env.HUB_SECRET = SECRET; process.env.AI_WRITER = '0'; aw._reset(); const n0 = seen.length; ok(!(await aw.enabled()) && seen.length === n0, 'AI_WRITER=0 hides it without asking the hub', seen.length);
|
||||
delete process.env.AI_WRITER; process.env.HUB_URL = 'http://127.0.0.1:1'; aw._reset(); ok(!(await aw.enabled()), 'an unreachable hub hides the button');
|
||||
hub.close();
|
||||
console.log('hubadwriter: ' + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,115 @@
|
||||
// Semantic matching, site side (netkb.js route/suggest/match, 2026-11-16) + parity of the shared files: node qa/netkb-semantic.test.mjs
|
||||
// A stand-in hub answers /v1/kb/match with scripted hits, so no model and no network. Checks: a sure match answers with this site's
|
||||
// entry, a pattern hit is kept when the match agrees or has no idea and overruled when the match points elsewhere, other sites'
|
||||
// entries rank behind this site's unless named or clearly closer, a named site that asks about "here" stays home, a slow or down hub
|
||||
// answers null inside the timeout and is skipped for a while (fail soft), and the support suggestions never offer the contact-support entry.
|
||||
// Parity: netkb.js is the same file in all eight network sites, chatcore.js + kb.js in the six that share them (checked against the
|
||||
// sibling checkouts beside this one; a missing sibling is skipped, a different one fails).
|
||||
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline Banners, Stack POL).
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import crypto from 'node:crypto';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
let pass = 0, fail = 0, skip = 0;
|
||||
const ok = (c, m) => { if (c) pass++; else { fail++; console.log('FAIL', m); } };
|
||||
|
||||
// ---- parity with the sibling checkouts
|
||||
const sha = f => crypto.createHash('sha1').update(fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n')).digest('hex');
|
||||
const SIBLINGS = ['onchain-ad-membership/site', 'linkspin/site', 'vbb/app', 'banner-line/app', 'viraladblitz/app', 'downlinehydra/app', '5xyourteam/app', 'stackpol'];
|
||||
const KIT = new Set(['vbb/app', 'banner-line/app', 'viraladblitz/app', 'downlinehydra/app', '5xyourteam/app', 'stackpol']);
|
||||
let base = ROOT; for (let i = 0; i < 4 && !SIBLINGS.some(s => path.resolve(base, s) === ROOT); i++) base = path.dirname(base);
|
||||
const mine = SIBLINGS.find(s => path.resolve(base, s) === ROOT);
|
||||
for (const s of SIBLINGS) {
|
||||
if (s === mine) continue;
|
||||
const dir = path.resolve(base, s);
|
||||
const files = ['netkb.js'].concat(mine && KIT.has(mine) && KIT.has(s) ? ['chatcore.js', 'kb.js'] : []);
|
||||
for (const f of files) {
|
||||
if (!fs.existsSync(path.join(dir, f))) { skip++; continue; }
|
||||
ok(sha(path.join(dir, f)) === sha(path.join(ROOT, f)), 'parity: ' + f + ' differs from ' + s + '/' + f);
|
||||
}
|
||||
}
|
||||
ok(/The SAME file ships in every network site/.test(fs.readFileSync(path.join(ROOT, 'netkb.js'), 'utf8')), 'netkb.js carries the shared-file header');
|
||||
|
||||
// ---- a stand-in hub
|
||||
let script = () => ({ hits: [], margin: 0 }), delay = 0, status = 200, last = null;
|
||||
const hub = http.createServer((req, res) => { let b = ''; req.on('data', c => { b += c; }); req.on('end', () => {
|
||||
last = { path: req.url, body: JSON.parse(b || '{}'), site: req.headers['x-hub-site'] };
|
||||
setTimeout(() => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(status === 200 ? Object.assign({ ok: true }, script(last.body)) : { error: 'embeddings_down' })); }, delay);
|
||||
}); });
|
||||
await new Promise(r => hub.listen(0, '127.0.0.1', r));
|
||||
process.env.HUB_URL = 'http://127.0.0.1:' + hub.address().port; process.env.HUB_SECRET = 'q'.repeat(40); process.env.HUB_SITE = 'home'; process.env.NETKB_MATCH_MS = '400';
|
||||
delete process.env.NETKB; delete process.env.NETKB_MATCH;
|
||||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'nksem-'));
|
||||
const netkb = require(path.join(ROOT, 'netkb.js'));
|
||||
netkb._set({ version: 'v', sites: { home: { name: 'Home', url: 'https://home.example' }, other: { name: 'Other', url: 'https://other.example' } },
|
||||
entries: [{ site: 'other', id: 'c-split', title: 'Other split', questions: [], answer: 'Other split answer.', tags: [] }] });
|
||||
const own = [{ id: 'c-split', title: 'Split', answer: 'Home split.' }, { id: 'c-packages', title: 'Packages', answer: 'Home prices.' }, { id: 'c-support', title: 'Support', answer: 'Ask support.', handoff: true }, { id: 'kb-t1', title: 'From a ticket', answer: 'Ticket answer.', source: 'ticket' }];
|
||||
const H = (site, id, score) => ({ site, id, title: id, answer: '', score, boosted: score + (site === 'home' ? 0.08 : 0), home: site === 'home' });
|
||||
const set = (hits, margin) => { script = () => ({ hits, margin: margin == null ? 0.1 : margin, confidence: hits.length ? hits[0].score : 0 }); };
|
||||
|
||||
// a sure match answers with this site's entry, even over a pattern hit that points elsewhere
|
||||
set([H('home', 'c-split', 0.93), H('home', 'c-packages', 0.7)]);
|
||||
let r = await netkb.route('how much do I earn', { fast: own[1], own });
|
||||
ok(r && r.via === 'answer' && r.hit.id === 'c-split', 'sure match answers (' + JSON.stringify(r && [r.via, r.hit && r.hit.id]) + ')');
|
||||
ok(last && last.path === '/v1/kb/match' && last.site === 'home' && last.body.k === 8, 'signed match call as this site');
|
||||
// the pattern hit kept when the match agrees
|
||||
set([H('home', 'c-split', 0.78), H('home', 'c-packages', 0.72)], 0.01);
|
||||
r = await netkb.route('what does it cost', { fast: own[1], own });
|
||||
ok(r && r.via === 'agree' && r.hit.id === 'c-packages', 'pattern kept when the match agrees (' + (r && r.via) + ')');
|
||||
// the pattern hit kept when the match has no idea
|
||||
set([H('home', 'c-split', 0.55)]);
|
||||
r = await netkb.route('zzq', { fast: own[1], own });
|
||||
ok(r && r.via === 'regex' && r.hit.id === 'c-packages', 'pattern kept when the match has no idea');
|
||||
// overruled when the match points elsewhere with some confidence
|
||||
set([H('home', 'c-split', 0.8), H('home', 'kb-t1', 0.75)], 0.05);
|
||||
r = await netkb.route('what is my cut when my friends buy', { fast: own[1], own });
|
||||
ok(r && r.via === 'veto' && r.hit === null && r.hits[0].entry.id === 'c-split', 'pattern overruled, the match feeds the prompt (' + (r && r.via) + ')');
|
||||
// home first: another site's entry stays behind unless clearly closer
|
||||
set([H('other', 'c-split', 0.82), H('home', 'c-split', 0.79)], 0.02);
|
||||
r = await netkb.route('my cut', { own });
|
||||
ok(r && r.via === 'context' && r.hits[0].entry.id === 'c-split' && !r.hits[0].entry.site, 'home entry first when no site is named');
|
||||
set([H('other', 'c-split', 0.95), H('home', 'c-packages', 0.70)], 0.2);
|
||||
r = await netkb.route('other thing', { own });
|
||||
ok(r && !r.hits[0].entry.site && r.hits.some(h => h.entry.site === 'other'), 'another site rides behind this site entry when clearly closer');
|
||||
set([H('other', 'c-split', 0.95), H('home', 'c-packages', 0.55)], 0.2);
|
||||
r = await netkb.route('other thing', { own });
|
||||
ok(r && r.hits[0].entry.site === 'other', 'another site leads when this site has nothing close');
|
||||
// a named site asked about "here" stays home (no prefer sent)
|
||||
set([H('home', 'c-split', 0.9)]);
|
||||
await netkb.route('I am on Other, will my team carry over here?', { own, prefer: ['other'] });
|
||||
ok(!last.body.prefer, 'named site + "here": no prefer');
|
||||
await netkb.route('How much is the split on Other?', { own, prefer: ['other'] });
|
||||
ok(Array.isArray(last.body.prefer) && last.body.prefer[0] === 'other', 'named site: prefer sent');
|
||||
// remote never answers outright
|
||||
set([H('other', 'c-split', 0.99)], 0.3);
|
||||
r = await netkb.route('How much is the split on Other?', { own, prefer: ['other'] });
|
||||
ok(r && r.hit === null && r.hits[0].entry.site === 'other', 'another site\'s entry rides as context, never the instant answer');
|
||||
|
||||
// suggestions: KB entries only, no contact-support entry, ticket-derived entries labelled
|
||||
set([H('home', 'kb-t1', 0.82), H('home', 'c-support', 0.8), H('home', 'c-split', 0.79), H('home', 'c-packages', 0.5)]);
|
||||
let s = await netkb.suggest('my payout never arrived after a purchase', { own });
|
||||
ok(s.via === 'semantic' && s.items.map(i => i.id).join() === 'kb-t1,c-split', 'suggest: closest answers, no support entry, no weak ones (' + s.items.map(i => i.id) + ')');
|
||||
ok(s.items[0].fromTicket === true && s.items[1].fromTicket === false, 'suggest: past-ticket entries labelled');
|
||||
s = await netkb.suggest('hi', { own }); ok(s.items.length === 0 && s.via === 'short', 'suggest: too short asks nothing');
|
||||
|
||||
// fail soft: slow hub -> null inside the timeout, then skipped for a while; down hub -> null; suggest falls back to BM25
|
||||
netkb._matchReset(); delay = 2000;
|
||||
let t0 = Date.now(); r = await netkb.route('anything', { own }); const took = Date.now() - t0;
|
||||
ok(r === null && took < 1500, 'slow hub: null within the timeout (' + took + ' ms)');
|
||||
delay = 0; t0 = Date.now(); r = await netkb.route('anything', { own });
|
||||
ok(r === null && Date.now() - t0 < 50, 'after a failure the hub is skipped for a while (no wait)');
|
||||
s = await netkb.suggest('my payout never arrived after a purchase', { own, fallback: async () => [{ entry: own[0] }, { entry: own[2] }] });
|
||||
ok(s.via === 'bm25' && s.items.map(i => i.id).join() === 'c-split', 'suggest falls back to BM25 when the hub is skipped');
|
||||
netkb._matchReset(); status = 503;
|
||||
r = await netkb.route('anything', { own }); ok(r === null, 'hub 503: null');
|
||||
netkb._matchReset(); status = 200;
|
||||
process.env.NETKB_MATCH = '0'; r = await netkb.route('anything', { own }); ok(r === null, 'NETKB_MATCH=0: off'); delete process.env.NETKB_MATCH;
|
||||
const v = netkb.view(); ok(v.matchErrors >= 2 && v.semAnswer >= 1 && typeof v.sem.answer === 'number', 'view carries the semantic counters');
|
||||
|
||||
hub.close();
|
||||
console.log((fail ? 'FAILED ' : 'ok ') + pass + ' passed, ' + fail + ' failed' + (skip ? ', ' + skip + ' sibling files not here (skipped)' : ''));
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,180 @@
|
||||
// The network hub as the sign-in provider (Marty 2026-11-15), end to end. Same file in InstantAdPay and LinkSpin.
|
||||
// node qa/networksso-hub.e2e.mjs (needs ../../network-hub and the other site beside this one; skips otherwise)
|
||||
// Boots the real hub (JSON store), InstantAdPay, LinkSpin and a stand-in wallet partner (the 5xYourTeam shape) with HUB_SSO=on,
|
||||
// each on its own cookie host (hub 127.0.0.3, IAP 127.0.0.1, LinkSpin localhost, partner 127.0.0.2), and drives a real browser:
|
||||
// 1. a code sign-in on IAP, then any IAP page: the page load goes once through the hub (/sso/set) and the hub sign-in is set
|
||||
// 2. same browser, a LinkSpin screen: the silent check asks the HUB (not IAP) and signs in with no code
|
||||
// 3. same browser, the partner's "Sign in with InstantAdPay": the hub answers with a token carrying the wallet
|
||||
// 4. Sign out everywhere on LinkSpin: the hub sign-in ends, a fresh partner check gets "nobody" from the hub
|
||||
// 5. a blocked member: the hub refuses; a replayed hub token is refused; no email-code request by any network sign-in
|
||||
// The partner takes the hub's hook with the real wallet-site hubevents.js (from ../../5xyourteam/app, 2026-11-16): its session
|
||||
// open on the partner ends after Sign out everywhere (step 4) and after a hub block (step 5).
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import http from 'node:http';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
|
||||
const PEER = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||
const HUB_DIR = [process.env.HUB_DIR, path.resolve(HERE, '../../network-hub')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'lib', 'sso.js')));
|
||||
if (!PEER || !HUB_DIR) { console.log('SKIP hub sign-in e2e: needs the other site and network-hub (with lib/sso.js) beside this repo.'); process.exit(0); }
|
||||
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
|
||||
const require = createRequire(import.meta.url);
|
||||
const WALLET_DIR = [process.env.WALLET_SITE_DIR, path.resolve(HERE, '../../5xyourteam/app')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'hubevents.js')));
|
||||
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||
const { ethers } = require(path.join(IAP_DIR, 'node_modules', 'ethers'));
|
||||
const SSO = crypto.randomBytes(24).toString('hex');
|
||||
const K = { iap: crypto.randomBytes(24).toString('hex'), linkspin: crypto.randomBytes(24).toString('hex'), fivex: crypto.randomBytes(24).toString('hex') };
|
||||
const ADMIN = crypto.randomBytes(24).toString('hex');
|
||||
const IP = Number(process.env.NSSO_IAP_PORT || 8841), LP = IP + 1, PP = IP + 2, HP = IP + 3;
|
||||
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP, P = 'http://127.0.0.2:' + PP, HUB = 'http://127.0.0.3:' + HP;
|
||||
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 fetch0 = globalThis.fetch;
|
||||
const fetch = async (...a) => { for (let i = 0; ; i++) { try { return await fetch0(...a); } catch (e) { if (i >= 3 || !/ECONNRESET|UND_ERR_SOCKET/.test(String((e.cause && (e.cause.code || e.cause.message)) || ''))) throw e; await sleep(300); } } };
|
||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-hub-'));
|
||||
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: '', hub: '' };
|
||||
function boot(name, dir, port, script, 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: SSO, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', DOCSTORE_URL: '', LS_SYNC_SECRET: '', HUB_ENABLED: '', FIVEX_URL: P, HUB_URL: HUB, HUB_SSO: 'on', HUB_ACTIVITY: '0',
|
||||
NODE_OPTIONS: '--require ' + JSON.stringify(SPY).slice(1, -1) }, extra);
|
||||
const p = spawn(process.execPath, [script], { 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 srvH = boot('hub', HUB_DIR, HP, 'server.js', { HUB_URL: '', HUB_SSO: '', HUB_ADMIN_SECRET: ADMIN, HUB_HOOK_EVERY_MS: '1000',
|
||||
HUB_SITES: JSON.stringify({ iap: { secret: K.iap }, linkspin: { secret: K.linkspin }, fivex: Object.assign({ secret: K.fivex }, WALLET_DIR ? { hook: P + '/api/hub/events' } : {}) }),
|
||||
HUB_SSO_SITES: JSON.stringify({ iap: IAP, linkspin: LS, fivex: P }) });
|
||||
const srvI = boot('iap', IAP_DIR, IP, 'server.js', { LS_URL: LS, HUB_SECRET: K.iap, HUB_SITE: 'iap' });
|
||||
const srvL = boot('ls', LS_DIR, LP, 'server.js', { IAP_URL: IAP, HUB_SECRET: K.linkspin, HUB_SITE: 'linkspin' });
|
||||
|
||||
// the stand-in wallet partner (self fivex), hub mode on, in this process
|
||||
Object.assign(process.env, { NETWORK_SSO_SECRET: SSO, HUB_URL: HUB, HUB_SECRET: K.fivex, HUB_SITE: 'fivex', HUB_SSO: 'on', HUB_ACTIVITY: '0' });
|
||||
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||
const PS = new Map(); const sidOf = req => (/(?:^|;\s*)fx\.sid=([a-f0-9]{32})/.exec(req.headers.cookie || '') || [])[1];
|
||||
const partnerLog = []; const origLog = console.log; console.log = (...a) => { if (a[0] === 'network-sso') partnerLog.push(a.join(' ')); else origLog(...a); };
|
||||
N.init({ self: 'fivex', peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: TMP, defaultPath: '/team',
|
||||
member: async req => { const s = PS.get(sidOf(req)); return s ? { address: s.address } : null; },
|
||||
accept: async (e, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
||||
signIn: async (e, req, v) => { const id = crypto.randomBytes(16).toString('hex'); PS.set(id, { address: v.wallet, via: v.iss, at: Date.now() }); return 'fx.sid=' + id + '; Path=/; HttpOnly; SameSite=Lax'; },
|
||||
landing: to => to, signinPath: to => '/signin?to=' + encodeURIComponent(to) });
|
||||
// the hub's hook into the partner: the real wallet-site module, ending partner sessions made before the event
|
||||
const HE = WALLET_DIR ? require(path.join(WALLET_DIR, 'hubevents.js')) : null;
|
||||
if (HE) HE.init({ dataDir: TMP, site: 'fivex', end: who => { let n = 0; for (const [k, x] of PS) if (x.at <= who.before && who.match(x)) { PS.delete(k); n++; } return n; } });
|
||||
const partner = http.createServer(async (req, res) => {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
if (HE && u.pathname === '/api/hub/events' && req.method === 'POST') { let raw = ''; for await (const c of req) raw += c; const r = await HE.receive(req.headers, raw); res.writeHead(r.status, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(r.body)); }
|
||||
if (req.method === 'GET' && await N.page(req, res, u)) return;
|
||||
if (await N.handle(req, res, u)) return;
|
||||
if (u.pathname === '/api/whoami') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(PS.get(sidOf(req)) || {})); }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>partner</title><p>' + u.pathname + '</p>');
|
||||
});
|
||||
await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); });
|
||||
|
||||
const signHub = (secret, ts, raw) => crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
||||
async function hubCall(route, site, secret, body) { const raw = JSON.stringify(body); const ts = String(Date.now()); const r = await fetch(HUB + route, { method: 'POST', body: raw, headers: { 'Content-Type': 'application/json', 'X-Hub-Site': site, 'X-Hub-Ts': ts, 'X-Hub-Sig': signHub(secret, ts, raw) } }); return { status: r.status, json: await r.json().catch(() => ({})) }; }
|
||||
let ipN = 50;
|
||||
const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.7.0.' + (ipN++), 'User-Agent': UA });
|
||||
const sidFrom = r => ((r.headers.getSetCookie ? r.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid=')) || '').slice('iap.sid='.length);
|
||||
async function codeSignIn(base, email) {
|
||||
const h = H();
|
||||
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
|
||||
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
|
||||
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
|
||||
const sid = sidFrom(v); if (!sid) throw new Error('code sign-in failed on ' + base);
|
||||
const un = 'h' + email.split('@')[0].replace(/[^a-z0-9]/g, '').slice(0, 12) + crypto.randomBytes(2).toString('hex');
|
||||
await fetch(base + '/api/my/profile', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: JSON.stringify({ username: un }) });
|
||||
return sid;
|
||||
}
|
||||
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 {}; } };
|
||||
const codeReqs = () => (logs.iap + logs.ls).split('\n').filter(l => /^REQ POST \/api\/auth\/email\/(start|verify)$/.test(l)).length;
|
||||
let browser = null;
|
||||
try {
|
||||
for (let i = 0; i < 240; i++) { let a = false, b = false, c = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} try { c = (await fetch(HUB + '/health')).ok; } catch (e) {} if (a && b && c) break; if (i === 239) throw new Error('servers not up: iap ' + a + ', linkspin ' + b + ', hub ' + c); await sleep(500); }
|
||||
await sleep(1500); // each site's first hub /health answer
|
||||
N._hubSeen();
|
||||
browser = await chromium.launch();
|
||||
const A = 'hub-a@example.com', wA = ethers.Wallet.createRandom().address.toLowerCase();
|
||||
const aI = await codeSignIn(IAP, A); await codeSignIn(LS, A);
|
||||
// the hub knows A (in production the sites' hubsync sends joins; here the test joins A as InstantAdPay) with a wallet
|
||||
ok((await hubCall('/v1/join', 'iap', K.iap, { email: A, username: 'huba' })).status === 200 && (await hubCall('/v1/wallet', 'iap', K.iap, { email: A, wallet: wA })).status === 200, 'setup: A on the hub with a wallet');
|
||||
const codes0 = codeReqs();
|
||||
|
||||
// 1. an IAP page load tells the hub
|
||||
const ctx = await browser.newContext({ userAgent: UA }); await ctx.addCookies([{ name: 'iap.sid', value: aI, domain: '127.0.0.1', path: '/' }]);
|
||||
const page = await ctx.newPage(); const navs = []; page.on('request', r => { if (r.isNavigationRequest() && r.frame() === page.mainFrame()) navs.push(r.url()); }); // every hop, 302s included
|
||||
await page.goto(IAP + '/my#overview'); await page.waitForLoadState('domcontentloaded'); await page.waitForTimeout(1000);
|
||||
ok(navs.some(u => u.startsWith(HUB + '/sso/set?site=iap')) && page.url().startsWith(IAP + '/my'), '1. IAP page load went once through the hub and came back', navs.map(u => u.slice(0, 45)).join(' , '));
|
||||
ok((await ctx.cookies(HUB)).some(c => c.name === 'hub.sso' && c.httpOnly && c.sameSite === 'Lax'), '1. the hub sign-in cookie is set (HttpOnly, SameSite=Lax) on the hub host');
|
||||
const before = navs.length; await page.goto(IAP + '/my'); await page.waitForTimeout(800);
|
||||
ok(!navs.slice(before).some(u => u.startsWith(HUB)), '1. the next page load does not go through the hub again');
|
||||
|
||||
// 2. LinkSpin signs in through the hub, no code
|
||||
await page.goto(LS + '/links'); await page.waitForURL(u => String(u).startsWith(LS + '/links'), { timeout: 20000 }); await page.waitForTimeout(2500);
|
||||
ok((await meOf(ctx, LS)).email === A, '2. LinkSpin screen opened directly: signed in through the hub', page.url());
|
||||
ok(navs.some(u => u.startsWith(HUB + '/sso/check?site=linkspin')) && /signed in from the network hub/.test(logs.ls), '2. it asked the hub, not InstantAdPay');
|
||||
|
||||
// 3. the partner: Sign in with InstantAdPay -> the hub answers, with the wallet
|
||||
await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?x=1')); await page.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 });
|
||||
const who = await (await ctx.request.get(P + '/api/whoami')).json();
|
||||
ok(page.url() === P + '/team?x=1' && who.address === wA && who.via === 'hub', '3. partner signed in by the hub with the member\'s wallet', page.url() + ' ' + JSON.stringify(who));
|
||||
|
||||
// 4. Sign out everywhere on LinkSpin
|
||||
const out = await (await ctx.request.post(LS + '/api/auth/logout-everywhere')).json();
|
||||
ok(out.ok && out.everywhere === true && !(await meOf(ctx, LS)).signedIn, '4. Sign out everywhere: signed out on LinkSpin, the hub confirmed', JSON.stringify(out));
|
||||
const hubNow = await ctx.request.get(HUB + '/sso/check?site=fivex&st=' + crypto.randomBytes(16).toString('hex') + '&to=%2F', { maxRedirects: 0 });
|
||||
ok(/none=1&hub=1/.test(hubNow.headers()['location'] || ''), '4. the hub sign-in is gone', hubNow.headers()['location']);
|
||||
if (HE) {
|
||||
let gone = false; for (let i = 0; i < 40 && !gone; i++) { await sleep(250); gone = !(await (await ctx.request.get(P + '/api/whoami')).json()).address; }
|
||||
ok(gone && HE.view().stats.ended >= 1, '4. the wallet partner session ended too (hub hook member.signedout, matched by the member wallet)', JSON.stringify(HE.view().stats));
|
||||
} else console.log('SKIP 4. wallet-site hook: no ../../5xyourteam/app/hubevents.js');
|
||||
|
||||
// 5. blocked on the hub: no hub sign-in at all
|
||||
const ctx2 = await browser.newContext({ userAgent: UA }); await ctx2.addCookies([{ name: 'iap.sid', value: await codeSignIn(IAP, A), domain: '127.0.0.1', path: '/' }]);
|
||||
const p2 = await ctx2.newPage(); await p2.goto(IAP + '/my'); await p2.waitForTimeout(1500);
|
||||
ok((await ctx2.cookies(HUB)).some(c => c.name === 'hub.sso'), '5. (a fresh browser signs in on the hub again)');
|
||||
// a partner session open in this browser before the block
|
||||
await p2.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team')); await p2.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 }).catch(() => {});
|
||||
const open2 = (await (await ctx2.request.get(P + '/api/whoami')).json()).address === wA;
|
||||
await hubCall('/v1/admin/block', 'admin', ADMIN, { email: A, reason: 'e2e' });
|
||||
if (HE) {
|
||||
let gone = false; for (let i = 0; i < 40 && !gone; i++) { await sleep(250); gone = !(await (await ctx2.request.get(P + '/api/whoami')).json()).address; }
|
||||
ok(open2 && gone, '5. blocked on the hub: the session open on the wallet partner ends (hub hook member.blocked)', JSON.stringify(HE.view().log.slice(-3)));
|
||||
}
|
||||
const blocked = await ctx2.request.get(HUB + '/sso/check?site=linkspin&st=' + crypto.randomBytes(16).toString('hex') + '&to=%2F', { maxRedirects: 0 });
|
||||
ok(/none=1/.test(blocked.headers()['location'] || '') && /sign-in ended \(blocked/.test(logs.hub + '') || /none=1/.test(blocked.headers()['location'] || ''), '5. blocked on the hub: the hub answers nobody', blocked.headers()['location']);
|
||||
// a hub token replayed: mint one by hand for LinkSpin, spend it, try again
|
||||
await hubCall('/v1/admin/block', 'admin', ADMIN, { email: A, blocked: false });
|
||||
const ctx3 = await browser.newContext({ userAgent: UA }); const st = crypto.randomBytes(16).toString('hex');
|
||||
await ctx3.addCookies([{ name: 'nsso.st', value: st, domain: 'localhost', path: '/' }]);
|
||||
const hubSso = require(path.join(HUB_DIR, 'lib', 'sso.js'));
|
||||
const tok = hubSso.mint(K.linkspin, { iss: 'hub', aud: 'linkspin', email: A, st, to: '/ads' });
|
||||
await ctx3.request.get(LS + '/sso/in?h=' + tok, { maxRedirects: 0 }); const first = (await meOf(ctx3, LS)).email === A;
|
||||
await ctx3.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||
await ctx3.addCookies([{ name: 'nsso.st', value: st, domain: 'localhost', path: '/' }]);
|
||||
await ctx3.request.get(LS + '/sso/in?h=' + tok, { maxRedirects: 0 });
|
||||
ok(first && !(await meOf(ctx3, LS)).signedIn && /token already used/.test(logs.ls), '5. a hub token signs in once; the replay is refused');
|
||||
const forged = hubSso.mint(K.iap, { iss: 'hub', aud: 'linkspin', email: A, st, to: '/ads' });
|
||||
await ctx3.addCookies([{ name: 'nsso.st', value: st, domain: 'localhost', path: '/' }]); await ctx3.request.get(LS + '/sso/in?h=' + forged, { maxRedirects: 0 });
|
||||
ok(!(await meOf(ctx3, LS)).signedIn && /refused: signature/.test(logs.ls), '5. a hub token signed with another site\'s key is refused');
|
||||
ok(codeReqs() === codes0 + 2, '5. no email-code request by any network sign-in (only the one setup sign-in in step 5)', (codeReqs() - codes0) + ' requests');
|
||||
ok(!logs.iap.includes(K.iap) && !logs.ls.includes(K.linkspin) && !logs.hub.includes(K.iap), 'no secret in any log');
|
||||
await ctx.close(); await ctx2.close(); await ctx3.close();
|
||||
} catch (e) { origLog('FAIL exception', e && e.stack || e, e && e.cause ? 'cause: ' + (e.cause.stack || e.cause) : ''); fails++; }
|
||||
finally {
|
||||
try { if (browser) await browser.close(); } catch (e) {}
|
||||
for (const s of [srvI, srvL, srvH]) { try { s.kill(); } catch (e) {} } try { partner.close(); } catch (e) {}
|
||||
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
|
||||
}
|
||||
console.log = origLog;
|
||||
if (fails) { for (const k of ['hub', 'iap', 'ls']) console.log('--- ' + k + ' log (tail)\n' + logs[k].split('\n').filter(l => !/rpc eth_call|^REQ /.test(l)).slice(-20).join('\n')); console.log('--- partner\n' + partnerLog.slice(-10).join('\n')); }
|
||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||
@@ -108,6 +108,12 @@ try {
|
||||
const hc = await fetch(IAP + '/api/admin/campaigns', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer localtest' }, body: JSON.stringify({ type: 'login', name: 'QA login sponsor', targetUrl: 'https://example.com/' }) });
|
||||
const hj = await hc.json().catch(() => ({}));
|
||||
ok(hc.ok && !hj.error, 'setup: a house login ad on InstantAdPay', JSON.stringify(hj).slice(0, 160));
|
||||
// signed out (bots, probes, link previews): no login ad drawn and no view counted, on either site
|
||||
const so = await (await fetch(IAP + '/api/ads/slot?type=login')).json();
|
||||
const imps = async () => ((await (await fetch(IAP + '/api/admin/campaigns', { headers: { Authorization: 'Bearer localtest' } })).json()).campaigns || []).filter(c => c.type === 'login').reduce((t, c) => t + (Number(c.imps) || 0), 0);
|
||||
ok(so.signedOut === true && !so.ad && (await imps()) === 0, 'signed out: /api/ads/slot?type=login draws nothing and counts no view on IAP', JSON.stringify(so));
|
||||
const sl = await (await fetch(LS + '/api/ads/slot?type=login')).json();
|
||||
ok(sl.signedOut === true && !sl.ad, 'signed out: nothing on LinkSpin either', JSON.stringify(sl));
|
||||
|
||||
// A. signed in on IAP with a wallet: straight back to the partner page with a session, never an IAP page, no login ad
|
||||
const A = 'partner-a@example.com';
|
||||
@@ -174,6 +180,18 @@ try {
|
||||
who = await whoami(ctx);
|
||||
ok(page.url() === P + '/team' && who.address === wd.address && who.via === 'linkspin', 'D. signed in on LinkSpin: back on the partner page signed in', page.url() + ' ' + JSON.stringify(who));
|
||||
ok(/token issued p\*\*\*@example\.com for 5xYourTeam/.test(logs.ls), 'D. LinkSpin logged a token for 5xYourTeam');
|
||||
// E. LinkSpin's login-ad clock: a house login ad, then the member's clock (served, too soon refused, finished, not due)
|
||||
const lh = await fetch(LS + '/api/admin/campaigns', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer localtest' }, body: JSON.stringify({ type: 'login', name: 'QA LS login sponsor', targetUrl: 'https://example.com/' }) });
|
||||
const lhj = await lh.json().catch(() => ({}));
|
||||
if (!lh.ok || lhj.error) ok(false, 'E. setup: a house login ad on LinkSpin', lh.status + ' ' + JSON.stringify(lhj).slice(0, 160));
|
||||
else {
|
||||
const lsGet = async () => (await ctx.request.get(LS + '/api/ads/slot?type=login')).json();
|
||||
const lsSeen = async () => (await ctx.request.post(LS + '/api/ads/login/seen')).json();
|
||||
let x = await lsGet(); ok(!!(x.ad && x.ad.targetUrl), 'E. LinkSpin: due -> a login ad', JSON.stringify(x).slice(0, 100));
|
||||
x = await lsSeen(); ok(x.ok === false && x.reason === 'too soon', 'E. LinkSpin: "seen" before the countdown is refused', JSON.stringify(x));
|
||||
await sleep(9000); x = await lsSeen(); ok(x.ok === true, 'E. LinkSpin: after the countdown the clock restarts', JSON.stringify(x));
|
||||
x = await lsGet(); ok(x.notDue === true && !x.ad, 'E. LinkSpin: inside the setting, no login ad', JSON.stringify(x));
|
||||
}
|
||||
await ctx.close();
|
||||
} catch (e) { console.log('FAIL exception', e && e.stack || e, e && e.cause ? 'cause: ' + (e.cause.stack || e.cause) : ''); fails++; }
|
||||
finally {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
// The way back to a network site after signing in on InstantAdPay (Marty 2026-11-17: "I just logged in to Instant Ad Pay from
|
||||
// Viral Ad Source, and it never had a return path back"). Same file in InstantAdPay and LinkSpin.
|
||||
// node qa/networksso-return.e2e.mjs (needs ../../network-hub and the other site beside this one; skips otherwise)
|
||||
// The partner here is a site InstantAdPay has NO hand-written line for (the ViralAdSource case): only the hub's HUB_SSO_SITES lists
|
||||
// it, and IAP learns it from the hub's public GET /v1/sso-sites. Real hub (JSON store), IAP, LinkSpin, a stand-in wallet partner
|
||||
// (the ViralAdSource shape: email-less, signs in by wallet), each on its own cookie host, driven by a real browser:
|
||||
// 1. signed in nowhere, the partner's silent check: back on the partner's own sign-in page, never dropped on the IAP dashboard
|
||||
// 2. a deliberate tap, signed out on IAP: IAP's sign-in, the code, then back on the exact partner page, signed in by wallet
|
||||
// 3. a deliberate tap, signed in on IAP with no wallet yet: the IAP Wallet tab (no bounce loop), the wallet link, then back
|
||||
// 4. a ?return=<site>&to=/path link on IAP: remembered, the URL cleaned, the code sign-in, then back on that partner page
|
||||
// 5. the same link while signed in: straight back; /go/<site> works for a hub-only site
|
||||
// 6. never an open redirect: an unknown ?return= is ignored, an off-site to= becomes /
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import http from 'node:http';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
|
||||
const PEER = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||
const HUB_DIR = [process.env.HUB_DIR, path.resolve(HERE, '../../network-hub')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'lib', 'sso.js')));
|
||||
if (!PEER || !HUB_DIR) { console.log('SKIP return e2e: needs the other site and network-hub beside this repo.'); process.exit(0); }
|
||||
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
|
||||
const require = createRequire(import.meta.url);
|
||||
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||
const { ethers } = require(path.join(IAP_DIR, 'node_modules', 'ethers'));
|
||||
const SITE = 'newsite'; // in no provider's hand-written list
|
||||
const SSO = crypto.randomBytes(24).toString('hex');
|
||||
const K = { iap: crypto.randomBytes(24).toString('hex'), linkspin: crypto.randomBytes(24).toString('hex'), [SITE]: crypto.randomBytes(24).toString('hex') };
|
||||
const IP = Number(process.env.NSSO_IAP_PORT || 8861), LP = IP + 1, PP = IP + 2, HP = IP + 3;
|
||||
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP, P = 'http://127.0.0.2:' + PP, HUB = 'http://127.0.0.3:' + HP;
|
||||
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-ret-'));
|
||||
const logs = { iap: '', ls: '', hub: '' };
|
||||
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: SSO, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', DOCSTORE_URL: '', LS_SYNC_SECRET: '', HUB_ENABLED: '', HUB_URL: HUB, HUB_SSO: 'on', HUB_ACTIVITY: '0' }, 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 srvH = boot('hub', HUB_DIR, HP, { HUB_URL: '', HUB_SSO: '', HUB_ADMIN_SECRET: crypto.randomBytes(24).toString('hex'),
|
||||
HUB_SITES: JSON.stringify({ iap: { secret: K.iap }, linkspin: { secret: K.linkspin }, [SITE]: { secret: K[SITE] } }),
|
||||
HUB_SSO_SITES: JSON.stringify({ iap: IAP, linkspin: LS, [SITE]: P }) });
|
||||
// the hub has to answer /v1/sso-sites before IAP and LinkSpin start (they read it at start, and again when an unknown site asks)
|
||||
for (let i = 0; i < 120; i++) { try { if ((await fetch(HUB + '/health')).ok) break; } catch (e) {} await sleep(250); }
|
||||
const srvI = boot('iap', IAP_DIR, IP, { LS_URL: LS, HUB_SECRET: K.iap, HUB_SITE: 'iap' });
|
||||
const srvL = boot('ls', LS_DIR, LP, { IAP_URL: IAP, HUB_SECRET: K.linkspin, HUB_SITE: 'linkspin' });
|
||||
|
||||
// the stand-in partner (the ViralAdSource shape), hub mode on, in this process
|
||||
Object.assign(process.env, { NETWORK_SSO_SECRET: SSO, HUB_URL: HUB, HUB_SECRET: K[SITE], HUB_SITE: SITE, HUB_SSO: 'on', HUB_ACTIVITY: '0' });
|
||||
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||
const PS = new Map(); const sidOf = req => (/(?:^|;\s*)ns\.sid=([a-f0-9]{32})/.exec(req.headers.cookie || '') || [])[1];
|
||||
const origLog = console.log; const partnerLog = []; console.log = (...a) => { if (a[0] === 'network-sso') partnerLog.push(a.join(' ')); else origLog(...a); };
|
||||
N.init({ self: SITE, peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: TMP, defaultPath: '/my',
|
||||
member: async req => { const s = PS.get(sidOf(req)); return s ? { address: s.address } : null; },
|
||||
accept: async (e, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
||||
signIn: async (e, req, v) => { const id = crypto.randomBytes(16).toString('hex'); PS.set(id, { address: v.wallet, via: v.iss }); return 'ns.sid=' + id + '; Path=/; HttpOnly; SameSite=Lax'; },
|
||||
landing: to => to, signinPath: to => '/signin?to=' + encodeURIComponent(to) });
|
||||
const partner = http.createServer(async (req, res) => {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
if (await N.handle(req, res, u)) return;
|
||||
if (u.pathname === '/api/whoami') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(PS.get(sidOf(req)) || {})); }
|
||||
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>partner</title><p id="pg">' + u.pathname + '</p>');
|
||||
});
|
||||
await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); });
|
||||
|
||||
let ipN = 70;
|
||||
const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.9.0.' + (ipN++), 'User-Agent': UA });
|
||||
const sidFrom = r => ((r.headers.getSetCookie ? r.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid=')) || '').slice('iap.sid='.length);
|
||||
async function codeSignIn(base, email) {
|
||||
const h = H();
|
||||
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
|
||||
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
|
||||
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
|
||||
const sid = sidFrom(v); if (!sid) throw new Error('code sign-in failed on ' + base + ': ' + JSON.stringify(sj) + ' ' + v.status);
|
||||
const un = 'r' + email.split('@')[0].replace(/[^a-z0-9]/g, '').slice(0, 14) + crypto.randomBytes(2).toString('hex');
|
||||
const pr = await fetch(base + '/api/my/profile', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: JSON.stringify({ username: un }) });
|
||||
if (!pr.ok && !(await (await fetch(base + '/api/me', { headers: { Cookie: 'iap.sid=' + sid } })).json()).username) throw new Error('username on ' + base + ': ' + pr.status); // a second sign-in: the name is set already
|
||||
return sid;
|
||||
}
|
||||
async function linkWallet(base, sid) {
|
||||
const w = ethers.Wallet.createRandom(); const h = Object.assign(H(), { Cookie: 'iap.sid=' + sid });
|
||||
const ch = await (await fetch(base + '/api/auth/challenge', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address }) })).json();
|
||||
const v = await fetch(base + '/api/auth/verify', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address, signature: await w.signMessage(ch.message) }) });
|
||||
const j = await v.json(); if (j.error) throw new Error('wallet link: ' + j.error);
|
||||
return { address: w.address.toLowerCase(), sid: sidFrom(v) || sid };
|
||||
}
|
||||
const logout = sid => fetch(IAP + '/api/auth/logout', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: '{}' });
|
||||
// the IAP dashboard's email-code sign-in, in the browser (the form's 4-second human timer included)
|
||||
async function uiSignIn(page, email) {
|
||||
await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||
await page.fill('#mcEmail', email); await page.waitForTimeout(4600); await page.click('#mcSendBtn');
|
||||
await page.waitForFunction(() => document.getElementById('mcCode') && document.getElementById('mcCode').value.length === 6, null, { timeout: 15000 });
|
||||
await page.click('#mcVerifyBtn');
|
||||
}
|
||||
const whoami = async ctx => (await (await ctx.request.get(P + '/api/whoami')).json());
|
||||
const mainNavs = page => { const n = []; page.on('framenavigated', f => { if (f === page.mainFrame()) n.push(f.url()); }); return n; };
|
||||
let browser = null;
|
||||
const newCtx = async sid => { const c = await browser.newContext({ userAgent: UA }); if (sid) await c.addCookies([{ name: 'iap.sid', value: sid, domain: '127.0.0.1', path: '/' }]); return c; };
|
||||
|
||||
try {
|
||||
for (let i = 0; i < 240; i++) { let a = false, b = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} if (a && b) break; if (i === 239) throw new Error('servers not up'); await sleep(500); }
|
||||
await sleep(1500); N._hubSeen();
|
||||
browser = await chromium.launch();
|
||||
const sites = await (await fetch(HUB + '/v1/sso-sites')).json();
|
||||
ok(sites.sites && sites.sites[SITE] === P, 'setup: the hub lists the partner at GET /v1/sso-sites', JSON.stringify(sites));
|
||||
|
||||
// 1. the 2026-11-17 bug: signed in nowhere, the partner's silent check dropped the visitor on the IAP dashboard
|
||||
let ctx = await newCtx(); let page = await ctx.newPage(); let navs = mainNavs(page);
|
||||
await page.goto(P + '/sso/start?mode=check&to=' + encodeURIComponent('/my')); await page.waitForLoadState('domcontentloaded'); await page.waitForTimeout(800);
|
||||
ok(page.url() === P + '/signin?to=%2Fmy', '1. signed in nowhere: back on the partner\'s own sign-in page', page.url());
|
||||
ok(!navs.some(u => u.startsWith(IAP + '/my')), '1. never dropped on the InstantAdPay dashboard', navs.map(u => u.slice(0, 60)).join(' , '));
|
||||
ok(!/unknown site asking/.test(logs.iap), '1. IAP knows the hub-only site (no "unknown site asking")');
|
||||
await ctx.close();
|
||||
|
||||
// 2. a deliberate tap while signed out on IAP: sign in there, then back on the exact partner page
|
||||
const B = 'ret-b@example.com'; const wb = await linkWallet(IAP, await codeSignIn(IAP, B)); await logout(wb.sid);
|
||||
ctx = await newCtx(); page = await ctx.newPage();
|
||||
await page.goto(P + '/sso/start?mode=go&to=' + encodeURIComponent('/my?tab=post#new')); await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||
ok(page.url().startsWith(IAP + '/my') && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), '2. signed out on IAP: IAP asks for its sign-in and remembers the trip', page.url());
|
||||
await uiSignIn(page, B);
|
||||
await page.waitForURL(u => String(u).startsWith(P + '/my'), { timeout: 20000 });
|
||||
let who = await whoami(ctx);
|
||||
ok(page.url() === P + '/my?tab=post#new' && who.address === wb.address, '2. after the code: back on the exact partner page, signed in by wallet', page.url() + ' ' + JSON.stringify(who));
|
||||
await ctx.close();
|
||||
|
||||
// 3. signed in on IAP with no wallet yet: the Wallet tab first, no bounce, then the wallet link sends it back
|
||||
const C = 'ret-c@example.com'; const sc = await codeSignIn(IAP, C);
|
||||
ctx = await newCtx(sc); page = await ctx.newPage(); navs = mainNavs(page);
|
||||
await page.goto(P + '/sso/start?mode=go&to=' + encodeURIComponent('/my?c=3')); await page.waitForURL(u => String(u).startsWith(IAP + '/my'), { timeout: 15000 }); await page.waitForTimeout(3500);
|
||||
ok(page.url() === IAP + '/my#wallet' && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.wait'), '3. no wallet yet: the IAP Wallet tab, waiting', page.url());
|
||||
const resumes = navs.filter(u => u.includes('/sso/resume')).length;
|
||||
ok(resumes === 0, '3. the dashboard does not bounce back and forth while it waits', resumes + ' resume hops');
|
||||
await page.waitForFunction(() => /signs you in with your wallet/.test((document.getElementById('status') || {}).textContent || ''), null, { timeout: 8000 }).catch(() => {});
|
||||
const st3 = await page.evaluate(() => (document.getElementById('status') || {}).textContent || '');
|
||||
ok(/newsite signs you in with your wallet/.test(st3) && !/\u2014/.test(st3), '3. one plain line says why and what to do', st3);
|
||||
const w3 = ethers.Wallet.createRandom();
|
||||
const ch = await (await ctx.request.post(IAP + '/api/auth/challenge', { headers: H(), data: { address: w3.address } })).json();
|
||||
const lk = await (await ctx.request.post(IAP + '/api/auth/verify', { headers: H(), data: { address: w3.address, signature: await w3.signMessage(ch.message) } })).json();
|
||||
ok(lk.linked && lk.next === '/sso/resume' && lk.backTo === SITE, '3. the wallet link answers with the way back', JSON.stringify({ next: lk.next, backTo: lk.backTo }));
|
||||
await page.goto(IAP + lk.next); await page.waitForURL(u => String(u).startsWith(P + '/my'), { timeout: 15000 });
|
||||
who = await whoami(ctx);
|
||||
ok(page.url() === P + '/my?c=3' && who.address === w3.address.toLowerCase(), '3. back on the partner page, signed in with the new wallet', page.url() + ' ' + JSON.stringify(who));
|
||||
await ctx.close();
|
||||
|
||||
// 4. a ?return= link on IAP (a site's "Join free" / "Sign in on InstantAdPay" link), signed out
|
||||
const D = 'ret-d@example.com'; const wd = await linkWallet(IAP, await codeSignIn(IAP, D)); await logout(wd.sid);
|
||||
ctx = await newCtx(); page = await ctx.newPage();
|
||||
await page.goto(IAP + '/my?x=1&return=' + SITE + '&to=' + encodeURIComponent('/post?y=2')); await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||
const ret = (await ctx.cookies(IAP)).find(c => c.name === 'nsso.ret');
|
||||
ok(!/return=|to=/.test(page.url()) && ret && decodeURIComponent(ret.value) === SITE + '|/post?y=2' && ret.httpOnly, '4. remembered (HttpOnly), the URL cleaned', page.url());
|
||||
await uiSignIn(page, D);
|
||||
await page.waitForURL(u => String(u).startsWith(P + '/post'), { timeout: 20000 });
|
||||
who = await whoami(ctx);
|
||||
ok(page.url() === P + '/post?y=2' && who.address === wd.address, '4. after the code: back on that partner page, signed in', page.url() + ' ' + JSON.stringify(who));
|
||||
ok(!(await ctx.cookies(IAP)).some(c => c.name === 'nsso.ret'), '4. the way back is used once');
|
||||
|
||||
// 5. the same link while signed in on IAP: straight back; /go/<site> for a hub-only site
|
||||
const sd = await codeSignIn(IAP, D); const ctx5 = await newCtx(sd); const p5 = await ctx5.newPage();
|
||||
await p5.goto(IAP + '/?return=' + SITE + '&to=' + encodeURIComponent('/team')); await p5.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 });
|
||||
ok(p5.url() === P + '/team' && (await whoami(ctx5)).address === wd.address, '5. signed in already: straight back, signed in', p5.url());
|
||||
const ctx5b = await newCtx(sd); const p5b = await ctx5b.newPage();
|
||||
await p5b.goto(IAP + '/go/' + SITE + '?to=' + encodeURIComponent('/stats')); await p5b.waitForURL(u => String(u).startsWith(P + '/stats'), { timeout: 15000 });
|
||||
ok(p5b.url() === P + '/stats' && (await whoami(ctx5b)).address === wd.address, '5. /go/<site> signs in on a site only the hub lists', p5b.url());
|
||||
await ctx5.close(); await ctx5b.close(); await ctx.close();
|
||||
|
||||
// 6. never an open redirect
|
||||
ctx = await newCtx(); page = await ctx.newPage();
|
||||
await page.goto(IAP + '/my?return=evil&to=' + encodeURIComponent('/x')); await page.waitForLoadState('domcontentloaded');
|
||||
ok(new URL(page.url()).search === '' && !(await ctx.cookies(IAP)).some(c => c.name === 'nsso.ret'), '6. an unknown ?return= is ignored and the URL cleaned', page.url());
|
||||
await page.goto(IAP + '/my?return=' + SITE + '&to=' + encodeURIComponent('//evil.example/x')); await page.waitForLoadState('domcontentloaded');
|
||||
const r6 = (await ctx.cookies(IAP)).find(c => c.name === 'nsso.ret');
|
||||
ok(r6 && decodeURIComponent(r6.value) === SITE + '|/', '6. an off-site to= becomes /', r6 && decodeURIComponent(r6.value));
|
||||
const r6b = await ctx.request.get(IAP + '/my?return=' + SITE + '&to=%2Fa', { maxRedirects: 0, headers: { 'User-Agent': 'curl/8' } });
|
||||
ok(r6b.status() === 302 && !(r6b.headers()['set-cookie'] || '').includes('nsso.ret'), '6. a bot remembers nothing');
|
||||
await ctx.close();
|
||||
ok(!logs.iap.includes(K.iap) && !logs.hub.includes(K[SITE]), 'no secret in any log');
|
||||
} catch (e) { origLog('FAIL exception', e && e.stack || e); fails++; }
|
||||
finally {
|
||||
try { if (browser) await browser.close(); } catch (e) {}
|
||||
for (const s of [srvI, srvL, srvH]) { try { s.kill(); } catch (e) {} } try { partner.close(); } catch (e) {}
|
||||
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
|
||||
}
|
||||
console.log = origLog;
|
||||
if (fails) { for (const k of ['hub', 'iap']) console.log('--- ' + k + ' log (tail)\n' + logs[k].split('\n').filter(l => /sso/.test(l)).slice(-25).join('\n')); console.log('--- partner\n' + partnerLog.slice(-15).join('\n')); }
|
||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||
@@ -31,6 +31,9 @@ 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));
|
||||
// an idle keep-alive socket the server closed (5 s default) while the browser launched: the request never reached it, send again
|
||||
const fetch0 = globalThis.fetch;
|
||||
const fetch = async (...a) => { for (let i = 0; ; i++) { try { return await fetch0(...a); } catch (e) { if (i >= 3 || !/ECONNRESET|UND_ERR_SOCKET/.test(String((e.cause && (e.cause.code || e.cause.message)) || ''))) throw e; await sleep(300); } } };
|
||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-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');
|
||||
@@ -187,7 +190,7 @@ try {
|
||||
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');
|
||||
const forged = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads' }).replace(/^(.*)(.)(.{10})$/, (m, h, c, t) => h + (c === 'A' ? 'Q' : 'A') + t); // a middle character: the last one carries 4 bits, so A<->B could decode the same (a 6% flake)
|
||||
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
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// PolHunter tour-stop credits (2026-11-17): POST /api/partner/credits against a LOCAL copy. node qa/partnercredits.test.mjs
|
||||
// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, DATABASE_URL blank, devCode sign-in, minimal env).
|
||||
// Checks: bad signature 401, unknown member 404, over the ceiling 400, other games refused, a good call grants earned-grade
|
||||
// credits once with a credit-activity line, the same ref again answers repeat and grants nothing. Exit code 1 on any failure.
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const SITE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const PORT = Number(process.env.PC_PORT || 8835), B = 'http://127.0.0.1:' + PORT;
|
||||
const SECRET = 'qa-pc-' + crypto.randomBytes(24).toString('hex');
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-pc-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (!cond && extra ? ' ' + extra : '')); if (!cond) fails++; };
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const ENV = {};
|
||||
for (const k of ['PATH', 'Path', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'COMSPEC', 'windir']) if (process.env[k]) ENV[k] = process.env[k];
|
||||
Object.assign(ENV, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DATABASE_URL: '', HUNT_SSO_SECRET: SECRET });
|
||||
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, env: ENV, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
|
||||
const post = async (body, secret) => { const raw = JSON.stringify(Object.assign({ game: 'polhunter' }, body)), ts = String(Date.now());
|
||||
const r = await fetch(B + '/api/partner/credits', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game-Ts': ts, 'X-Game-Sig': crypto.createHmac('sha256', secret || SECRET).update(ts + '\n' + raw).digest('hex') }, body: raw });
|
||||
let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
|
||||
try {
|
||||
let up = false; for (let i = 0; i < 90 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(1000); } }
|
||||
if (!up) throw new Error('local server did not come up:\n' + log.slice(-2000));
|
||||
const email = 'hunter-pc@example.com';
|
||||
const s = await (await fetch(B + '/api/auth/email/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) })).json();
|
||||
const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.devCode }) });
|
||||
const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
|
||||
ok((await post({ email, credits: 10, ref: 'tour:a1' }, 'wrong-' + SECRET)).status === 401, 'a bad signature is refused');
|
||||
ok((await post({ email: 'nobody@example.com', credits: 10, ref: 'tour:a1' })).status === 404, 'an unknown member is 404');
|
||||
ok((await post({ email, credits: 26, ref: 'tour:a1' })).status === 400, 'over the 25 ceiling is refused');
|
||||
ok((await post({ email, credits: 10, ref: 'bad ref!' })).status === 400, 'a malformed ref is refused');
|
||||
const g1 = await post({ email, credits: 10, ref: 'tour:a1', note: 'PolHunter tour stop: Site A' });
|
||||
ok(g1.status === 200 && g1.j.ok && g1.j.credits === 10 && !g1.j.repeat, 'a good call grants 10 credits', JSON.stringify(g1));
|
||||
const g2 = await post({ email, credits: 10, ref: 'tour:a1' });
|
||||
ok(g2.status === 200 && g2.j.ok && g2.j.repeat === true, 'the same ref again answers repeat', JSON.stringify(g2));
|
||||
const logFile = path.join(DATA, 'credit-log.json'); const lines = fs.existsSync(logFile) ? JSON.parse(fs.readFileSync(logFile, 'utf8')).items.filter(i => i.email === email && /tour stop/i.test(i.note)) : [];
|
||||
ok(lines.length === 1 && lines[0].delta === 10 && lines[0].kind === 'earn', 'exactly one credit-activity line of +10 (earned grade)', JSON.stringify(lines));
|
||||
const ej = path.join(DATA, 'earned.json'); const ec = fs.existsSync(ej) ? JSON.parse(fs.readFileSync(ej, 'utf8')) : {};
|
||||
ok(ec[email] && ec[email].balance >= 10 && !ec[email].grade, 'earned balance holds the 10, none of it purchased grade', JSON.stringify(ec[email]));
|
||||
ok((await post({ game: 'gemkingdom', email, credits: 10, ref: 'tour:b1' })).status !== 200, 'another game cannot use it');
|
||||
} catch (e) { console.log('FAIL crash', e.message); fails++; }
|
||||
srv.kill(); await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
||||
console.log(fails ? '\nFAILURES: ' + fails : '\nALL PARTNER CREDIT CHECKS PASS'); process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,197 @@
|
||||
// Network Weekend 2026 (promodays.js + its friday.js, promos.js, gamepass.js and chatbot hooks). Every date gate is driven by the
|
||||
// event time or the IAP_TEST_NOW test clock, never the machine clock. Fakes only: no chain, no DB, no mail, no network.
|
||||
// node --test qa/promodays.test.cjs
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const fs = require('fs'); const os = require('os'); const path = require('path');
|
||||
process.env.NODE_ENV = 'test';
|
||||
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-'));
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const T = s => Date.parse(s);
|
||||
|
||||
function fresh(mod) { delete require.cache[require.resolve(path.join(ROOT, mod))]; return require(path.join(ROOT, mod)); }
|
||||
function rig(events, site) {
|
||||
const granted = [], notices = [], mails = [], posts = [], claimed = new Set();
|
||||
const deps = {
|
||||
dataDir: fs.mkdtempSync(path.join(DIR, 'd-')), siteConfig: () => Object.assign({}, site || {}),
|
||||
chain: { recentEvents: () => events.slice(), member: async id => ({ account: '0x' + String(id).padStart(40, 'a') }) },
|
||||
ads: { addEarned: async (email, n, o) => granted.push({ email, n, note: o.log.note, purchased: o.purchased }) },
|
||||
accounts: { byMemberId: async id => ({ email: 'm' + id + '@x.test', memberId: id }), listAll: async () => [{ email: 'a@x.test', memberId: 7, lastSeen: T('2026-11-20T00:00:00Z') }] },
|
||||
marks: { claim: async k => { if (claimed.has(k)) return false; claimed.add(k); return true; } },
|
||||
notify: async (id, subject, text) => notices.push({ id, subject, text }),
|
||||
telegram: async t => { posts.push(t); return true; },
|
||||
mailer: { hasKey: () => true, send: async (to, subject, text) => mails.push({ to, subject, text }) }, drip: { isUnsubscribed: async () => false }
|
||||
};
|
||||
const pd = fresh('promodays.js'); pd.init(deps);
|
||||
const fr = fresh('friday.js'); fr.init(Object.assign({}, deps, { promodays: pd }));
|
||||
return { pd, fr, granted, notices, mails, posts, deps };
|
||||
}
|
||||
let n = 0;
|
||||
const buy = (iso, cents, credits, id) => ({ type: 'Purchase', tx: '0xtx' + (++n), li: 0, ts: T(iso), buyerId: id || 11, priceCents: cents, creditAmount: credits });
|
||||
|
||||
test('the map: each day is midnight to midnight Central (CST, UTC-6)', () => {
|
||||
const { pd } = rig([]);
|
||||
assert.strictEqual(pd.dayAt(T('2026-11-27T05:59:59Z')), null); // Thu 23:59:59 CT
|
||||
assert.strictEqual(pd.dayAt(T('2026-11-27T06:00:00Z')).pct, 40); // Fri 00:00 CT
|
||||
assert.strictEqual(pd.dayAt(T('2026-11-28T05:59:59Z')).name, 'Black Friday');
|
||||
assert.strictEqual(pd.dayAt(T('2026-11-28T06:00:00Z')).pct, 20);
|
||||
assert.strictEqual(pd.dayAt(T('2026-11-29T12:00:00Z')).pct, 20);
|
||||
const m = pd.dayAt(T('2026-11-30T06:00:00Z')); assert.strictEqual(m.pct, 30); assert.strictEqual(m.minCents, 2000);
|
||||
assert.strictEqual(pd.dayAt(T('2026-12-01T05:59:59Z')).name, 'Cyber Monday');
|
||||
assert.strictEqual(pd.dayAt(T('2026-12-01T06:00:00Z')), null); // Tue 00:00 CT: off
|
||||
assert.strictEqual(pd.inWeekend(T('2026-11-27T06:00:00Z')), true);
|
||||
assert.strictEqual(pd.inWeekend(T('2026-12-01T06:00:00Z')), false);
|
||||
});
|
||||
|
||||
test('Black Friday: ONE bonus per tx at 40% through friday.js, not 20 + 40, and nobody flips fridayBonusPct', async () => {
|
||||
const ev = buy('2026-11-27T15:00:00Z', 500, 500);
|
||||
const r = rig([ev], { fridayBonusPct: '20' });
|
||||
assert.strictEqual(await r.fr.onEvent(ev), 200); // 40% of 500
|
||||
assert.strictEqual(await r.fr.onEvent(ev), null); // same tx again: nothing
|
||||
const p = await r.pd.onEvent(ev); assert.strictEqual(p.bonus, 0); // promodays never pays a Friday
|
||||
assert.deepStrictEqual(r.granted.map(g => g.n), [200]);
|
||||
assert.match(r.granted[0].note, /^Black Friday: \+40% on your \$5 package/);
|
||||
assert.ok(r.notices.some(x => /^Black Friday: \+200 bonus credits/.test(x.subject) && /Ad credits buy advertising, not income\./.test(x.text)));
|
||||
});
|
||||
|
||||
test('a normal Friday after the weekend is Five Dollar Friday +20% again (12-04)', async () => {
|
||||
const ev = buy('2026-12-04T15:00:00Z', 500, 500);
|
||||
const r = rig([ev], { fridayBonusPct: '20' });
|
||||
assert.strictEqual(await r.fr.onEvent(ev), 100);
|
||||
assert.match(r.granted[0].note, /^Five Dollar Friday: \+20%/);
|
||||
assert.strictEqual((await r.pd.onEvent(ev)).bonus, 0);
|
||||
});
|
||||
|
||||
test('Saturday and Sunday +20% on $5+, Cyber Monday +30% on $20+ only, Tuesday nothing; once per tx', async () => {
|
||||
const sat = buy('2026-11-28T06:00:00Z', 500, 500), sun = buy('2026-11-30T05:59:00Z', 1000, 1000);
|
||||
const mon10 = buy('2026-11-30T18:00:00Z', 1000, 1000), mon20 = buy('2026-11-30T18:00:00Z', 2000, 2000), tue = buy('2026-12-01T06:00:00Z', 2000, 2000);
|
||||
const r = rig([sat, sun, mon10, mon20, tue]);
|
||||
assert.strictEqual((await r.pd.onEvent(sat)).bonus, 100);
|
||||
assert.strictEqual((await r.pd.onEvent(sat)).bonus, 0);
|
||||
assert.strictEqual((await r.pd.onEvent(sun)).bonus, 200);
|
||||
assert.strictEqual((await r.pd.onEvent(mon10)).bonus, 0);
|
||||
assert.strictEqual((await r.pd.onEvent(mon20)).bonus, 600);
|
||||
assert.strictEqual((await r.pd.onEvent(tue)).bonus, 0);
|
||||
assert.deepStrictEqual(r.granted.map(g => g.note.split(':')[0]), ['Network Weekend Saturday', 'Network Weekend Sunday', 'Cyber Monday']);
|
||||
assert.ok(r.granted.every(g => g.purchased));
|
||||
assert.strictEqual(await r.fr.onEvent(sat), null); // friday.js never pays a Saturday
|
||||
});
|
||||
|
||||
test('bundles: $20+ in the window shows the LinkSpin code; $100+ also says DownlineHydra Pro; outside the window nothing', async () => {
|
||||
const s20 = buy('2026-11-29T15:00:00Z', 2000, 2000), b100 = buy('2026-11-27T06:00:01Z', 10000, 12000, 21), b5 = buy('2026-11-28T15:00:00Z', 500, 500);
|
||||
const late = buy('2026-12-01T06:00:00Z', 10000, 12000), early = buy('2026-11-27T05:59:59Z', 10000, 12000);
|
||||
const r = rig([s20, b100, b5, late, early], { weekendLinkspinCode: 'weekend500' });
|
||||
const a = await r.pd.onEvent(s20); assert.ok(a.starter && !a.builder);
|
||||
const b = await r.pd.onEvent(b100); assert.ok(b.starter && b.builder);
|
||||
assert.ok(!(await r.pd.onEvent(b5)).starter);
|
||||
assert.ok(!(await r.pd.onEvent(late)).starter && !(await r.pd.onEvent(early)).starter);
|
||||
assert.ok(!(await r.pd.onEvent(s20)).starter, 'once per tx');
|
||||
const bn = r.notices.filter(x => x.subject === 'Network Weekend: your bundle extras');
|
||||
assert.strictEqual(bn.length, 2);
|
||||
assert.ok(bn.every(x => /WEEKEND500/.test(x.text) && /linkspin\.app/.test(x.text) && /Ad credits buy advertising, not income\./.test(x.text)));
|
||||
assert.ok(/DownlineHydra Pro/.test(bn[1].text) && /first 24 comps/.test(bn[1].text) && !/DownlineHydra/.test(bn[0].text));
|
||||
});
|
||||
|
||||
test('builders list for DownlineHydra: $100+ packs from Fri 00:00 CT to Tue 00:00 CT, lowercase wallets', async () => {
|
||||
const evs = [buy('2026-11-27T05:59:59Z', 10000, 12000, 1), buy('2026-11-27T06:00:00Z', 10000, 12000, 2), buy('2026-11-30T20:00:00Z', 25000, 32500, 3),
|
||||
buy('2026-11-30T20:00:00Z', 5000, 5500, 4), buy('2026-12-01T06:00:00Z', 50000, 70000, 5), { type: 'MemberActivated', id: 2, account: '0xABCDEF0000000000000000000000000000000002', tx: 'x', ts: 1 }];
|
||||
const r = rig(evs);
|
||||
const out = await r.pd.builders();
|
||||
assert.deepStrictEqual(out.builders.map(b => b.usdCents), [10000, 25000]);
|
||||
assert.strictEqual(out.builders[0].wallet, '0xabcdef0000000000000000000000000000000002');
|
||||
assert.match(out.builders[1].wallet, /^0x[a]+3$/);
|
||||
assert.strictEqual(out.cap, 24);
|
||||
});
|
||||
|
||||
test('Thanksgiving Thu 11-26 18:00 CT: the Friday notice and email carry the Black Friday copy, once; a normal Thursday stays normal', async () => {
|
||||
try {
|
||||
process.env.IAP_TEST_NOW = '2026-11-26T23:59:00Z'; // Thu 17:59 CT: not yet
|
||||
let r = rig([]); await r.fr.tick(); assert.strictEqual(r.mails.length, 0);
|
||||
process.env.IAP_TEST_NOW = '2026-11-27T00:05:00Z'; // Thu 18:05 CT
|
||||
await r.fr.tick(); await r.fr.tick();
|
||||
assert.strictEqual(r.mails.length, 1, 'one email, not two');
|
||||
assert.strictEqual(r.mails[0].subject, 'Black Friday starts at midnight: Network Weekend');
|
||||
assert.match(r.mails[0].text, /midnight to midnight/); assert.match(r.mails[0].text, /\+40% bonus ad credits on any \$5\+ pack/);
|
||||
assert.match(r.mails[0].text, /Ad credits buy advertising, not income\./); assert.ok(!/—/.test(r.mails[0].text));
|
||||
assert.strictEqual(r.notices.filter(x => /Black Friday starts/.test(x.subject)).length, 1);
|
||||
process.env.IAP_TEST_NOW = '2026-12-04T00:05:00Z'; // Thu 12-03 18:05 CT: normal Five Dollar Friday copy
|
||||
r = rig([]); await r.fr.tick(); assert.strictEqual(r.mails[0].subject, 'Tomorrow is Five Dollar Friday');
|
||||
process.env.IAP_TEST_NOW = '2026-11-27T11:05:00Z'; // Fri 05:05 CT kickoff: Black Friday copy
|
||||
r = rig([]); await r.fr.tick(); assert.ok(r.posts.length === 1 && /Black Friday\. Network Weekend is live/.test(r.posts[0]) && /\+40%/.test(r.posts[0]));
|
||||
process.env.IAP_TEST_NOW = '2026-11-25T23:30:00Z'; // the Friday page/strip on Wed 11-25 already says the coming Friday is +40%
|
||||
r = rig([]); const v = r.fr.view(); assert.strictEqual(v.pct, 40); assert.strictEqual(v.name, 'Black Friday');
|
||||
} finally { delete process.env.IAP_TEST_NOW; }
|
||||
});
|
||||
|
||||
test('promoDaysOn 0 switches everything off; a promoDays setting replaces the map for a future holiday', async () => {
|
||||
const ev = buy('2026-11-28T15:00:00Z', 500, 500);
|
||||
let r = rig([ev], { promoDaysOn: '0' }); assert.strictEqual((await r.pd.onEvent(ev)).bonus, 0); assert.strictEqual(r.pd.passBonusDays('legend', ev.ts), 0);
|
||||
r = rig([], { promoDays: JSON.stringify({ '2027-07-04': { pct: 15, minCents: 500, name: 'Fourth of July' } }) });
|
||||
assert.strictEqual(r.pd.dayAt(T('2027-07-04T17:00:00Z')).pct, 15); assert.strictEqual(r.pd.dayAt(T('2026-11-28T15:00:00Z')), null);
|
||||
});
|
||||
|
||||
test('Game Pass bonus days: Explorer/Champion +15, Legend +60, packages fulfilled Fri 11-27 00:00 CT to Fri 12-04 00:00 CT', () => {
|
||||
const { pd } = rig([]);
|
||||
assert.strictEqual(pd.passBonusDays('explorer', T('2026-11-27T05:59:59Z')), 0);
|
||||
assert.strictEqual(pd.passBonusDays('explorer', T('2026-11-27T06:00:00Z')), 15);
|
||||
assert.strictEqual(pd.passBonusDays('champion', T('2026-12-04T05:59:59Z')), 15); // Thu 12-03 23:59:59 CT
|
||||
assert.strictEqual(pd.passBonusDays('legend', T('2026-12-01T12:00:00Z')), 60);
|
||||
assert.strictEqual(pd.passBonusDays('legend', T('2026-12-04T06:00:00Z')), 0);
|
||||
assert.strictEqual(pd.passBonusDays('weekly', T('2026-11-28T12:00:00Z')), 0);
|
||||
assert.strictEqual(pd.passBonusDays('sovereign', T('2026-11-28T12:00:00Z')), 0);
|
||||
});
|
||||
|
||||
test('chatbot: fact and answer only around the window; the Friday question on Black Friday gets 40%', () => {
|
||||
const { pd } = rig([]);
|
||||
assert.strictEqual(pd.chatFact(T('2026-11-25T12:00:00Z')), '');
|
||||
assert.match(pd.chatFact(T('2026-11-26T12:00:00Z')), /starts Fri 2026-11-27 00:00 Central/);
|
||||
assert.match(pd.chatFact(T('2026-11-28T12:00:00Z')), /LIVE now/);
|
||||
assert.strictEqual(pd.chatFact(T('2026-12-02T12:00:00Z')), '', 'sovTiers off (live 11-17): no tier pass days to talk about after Mon');
|
||||
assert.ok(!/Game Pass bonus days/.test(pd.chatFact(T('2026-11-28T12:00:00Z'))), 'sovTiers off: the live fact leaves the tier days out');
|
||||
{ const r2 = rig([], { sovTiers: '1' }); assert.match(r2.pd.chatFact(T('2026-12-02T12:00:00Z')), /is over.*Game Pass bonus days/); assert.match(r2.pd.chatFact(T('2026-11-28T12:00:00Z')), /Game Pass bonus days/); }
|
||||
assert.strictEqual(pd.chatFact(T('2026-12-04T06:00:00Z')), '');
|
||||
assert.strictEqual(pd.chatAnswer('what is five dollar friday', T('2026-11-20T12:00:00Z')), null);
|
||||
assert.match(pd.chatAnswer('any black friday deal?', T('2026-11-27T15:00:00Z')), /Today is Black Friday: \+40% bonus ad credits on any \$5\+ pack/);
|
||||
assert.match(pd.chatAnswer('cyber monday?', T('2026-11-30T15:00:00Z')), /Today is Cyber Monday: \+30% .* \$20\+/);
|
||||
assert.strictEqual(pd.chatAnswer('black friday', T('2026-12-01T06:00:00Z')), null);
|
||||
for (const t of ['2026-11-26T12:00:00Z', '2026-11-28T12:00:00Z']) assert.ok(!/—|up to/i.test(pd.chatFact(T(t)) + pd.chatAnswer('network weekend', T(t))));
|
||||
});
|
||||
|
||||
test('promo code start gate (NETWORKWEEKEND): dormant until Fri 00:00 CT, expired at Tue 00:00 CT', async () => {
|
||||
process.env.DATABASE_URL = ''; delete process.env.DOCSTORE_URL;
|
||||
const promos = fresh('promos.js'); promos.init({ dataDir: fs.mkdtempSync(path.join(DIR, 'p-')) });
|
||||
const r = await promos.create({ code: 'NETWORKWEEKEND', credits: 300, maxUses: 300, starts: '2026-11-27T00:00:00-06:00', expires: '2026-12-01T00:00:00-06:00', note: 'Network Weekend 2026' });
|
||||
assert.ok(r.ok); assert.strictEqual(r.code.starts, T('2026-11-27T06:00:00Z'));
|
||||
try {
|
||||
process.env.IAP_TEST_NOW = '2026-11-27T05:59:59Z'; assert.match((await promos.check('networkweekend', 'a@x.test')).error, /opens Friday, Nov 27, 12:00 AM Central/);
|
||||
process.env.IAP_TEST_NOW = '2026-11-27T06:00:00Z'; assert.strictEqual(await promos.check('NETWORKWEEKEND', 'a@x.test'), null);
|
||||
const g = await promos.redeem('NETWORKWEEKEND', 'a@x.test', 'dashboard'); assert.strictEqual(g.credits, 300); assert.strictEqual(g.step, 60);
|
||||
assert.match((await promos.redeem('NETWORKWEEKEND', 'a@x.test', 'dashboard')).error, /already used/);
|
||||
process.env.IAP_TEST_NOW = '2026-12-01T05:59:59Z'; assert.strictEqual(await promos.check('NETWORKWEEKEND', 'b@x.test'), null);
|
||||
process.env.IAP_TEST_NOW = '2026-12-01T06:00:01Z'; assert.match((await promos.check('NETWORKWEEKEND', 'b@x.test')).error, /expired/);
|
||||
// an update without starts keeps it (the admin form never drops the gate)
|
||||
const u = await promos.create({ code: 'NETWORKWEEKEND', credits: 300, maxUses: 300, expires: '2026-12-01T00:00:00-06:00' }); assert.strictEqual(u.code.starts, T('2026-11-27T06:00:00Z'));
|
||||
} finally { delete process.env.IAP_TEST_NOW; }
|
||||
});
|
||||
|
||||
test.after(() => fs.rmSync(DIR, { recursive: true, force: true }));
|
||||
|
||||
test('gamepass: a tier pass paid by a package in the window gets the bonus days; the weekly pass and comps never do', async () => {
|
||||
const maps = {}; const pm = k => (maps[k] = maps[k] || new Map());
|
||||
const { pd } = rig([]);
|
||||
const gp = fresh('gamepass.js');
|
||||
gp.init({ dataDir: fs.mkdtempSync(path.join(DIR, 'g-')), siteConfig: () => ({ gamePassEnabled: '1', sovTiers: '1' }), accounts: { byMemberId: async () => ({ email: 'p@x.test' }) },
|
||||
marks: { claim: async () => true }, isProd: false, persistedMap: pm, polUsd: async () => 0.2, blockTime: async () => 0, notify: async () => {}, telegram: async () => {},
|
||||
bonusDays: (tier, ts) => pd.passBonusDays(tier, ts) });
|
||||
const D = 86400000;
|
||||
const pay = async (tier, cents, iso, tx) => {
|
||||
pm('gporders').set('o-' + tx, { status: 'waiting', email: 'p@x.test', ts: T(iso) - 60000, tier });
|
||||
return gp.onEvent({ type: 'Purchase', tx, ts: T(iso), buyerId: 9, priceCents: cents, devEmail: 'p@x.test', devMinedAt: T(iso) });
|
||||
};
|
||||
let r = await pay('explorer', 2000, '2026-11-28T12:00:00Z', '0xe1'); assert.strictEqual(Math.round((r.until - T('2026-11-28T12:00:00Z')) / D), 45);
|
||||
r = await pay('legend', 25000, '2026-12-03T23:00:00Z', '0xl1'); assert.strictEqual(Math.round((r.until - T('2026-12-03T23:00:00Z')) / D), 425);
|
||||
r = await pay('champion', 5000, '2026-12-04T06:00:00Z', '0xc1'); assert.strictEqual(Math.round((r.until - T('2026-12-04T06:00:00Z')) / D), 30); // Fri 12-04 00:00 CT: over
|
||||
r = await pay('weekly', 500, '2026-11-28T12:00:00Z', '0xw1'); assert.strictEqual(Math.round((r.until - T('2026-11-28T12:00:00Z')) / D), 7);
|
||||
const c = gp.comp('q@x.test', 'test', 'explorer', T('2026-11-28T12:00:00Z')); assert.strictEqual(c.days, 30);
|
||||
});
|
||||
@@ -24,6 +24,7 @@
|
||||
# bash qa/run.sh fuel # Fuel Your Offers: refill notices, refuel streak, Refuel Kit, Engine Room (unit + two-copy tests, throwaway data)
|
||||
# bash qa/run.sh policy # profile policy + link-farm scan: prohibited list, bio links, quarantine, 06:30 claim, walls of free/paying members, 404 walls (unit + local copy; also runs in member)
|
||||
# bash qa/run.sh bixpay # BixPay card: partner-link validator, sponsor-follows resolver (own / level 3 / company), gate, click store (unit, no server; also runs in member)
|
||||
# bash qa/run.sh weekend # Network Weekend 2026 (promodays.js): unit tests + local e2e at Black Friday / Cyber Monday / before / after test clocks
|
||||
# bash qa/run.sh theme # light/dark themes: WCAG contrast of the main text/background pairs on the member area, admin and public pages, both themes (local copy)
|
||||
# QA_THEME=dark bash qa/run.sh member # walk every pane in one theme; screenshots land as *-dark.png / *-light.png
|
||||
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
|
||||
@@ -67,20 +68,31 @@ elif [ "$MODE" = "sso" ]; then
|
||||
node qa/networksso.test.cjs || status=1
|
||||
node qa/networksso.e2e.mjs || status=1
|
||||
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
|
||||
node qa/networksso-hub.e2e.mjs || status=1 # the network hub as the sign-in provider: push, hub sign-in on another site, wallet partner, sign out everywhere, blocked, replay (skips without ../../network-hub)
|
||||
elif [ "$MODE" = "member" ]; then
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; LOCAL=http://127.0.0.1:8796 node qa/member-extra.mjs || status=1; }; stop_local 8796
|
||||
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; LOCAL=http://127.0.0.1:8796 node qa/support-suggest.mjs || status=1; }; stop_local 8796
|
||||
node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard
|
||||
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
|
||||
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
|
||||
node qa/networksso-hub.e2e.mjs || status=1 # the network hub as the sign-in provider: push, hub sign-in on another site, wallet partner, sign out everywhere, blocked, replay (skips without ../../network-hub)
|
||||
node qa/tank-hold.mjs || status=1
|
||||
node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap
|
||||
node qa/tank-readiness.test.mjs || status=1 # holding tank readiness (2026-11-18): entry reasons, stage, heat against a LOCAL network hub; hub down = card as before
|
||||
node qa/draft-partner.test.mjs || status=1 # 5xYourTeam draft partner routes (DRAFT_E2E_PORT, default 8825)
|
||||
node qa/site-invite.test.mjs || status=1 # sponsor invite emails for other network sites: directs only, once ever, caps, never-mail list
|
||||
node qa/walletnudge.test.cjs || status=1
|
||||
node qa/bixpay.test.cjs || status=1
|
||||
node qa/profile-policy.test.cjs || status=1
|
||||
node qa/sov-heroes-store.cjs || status=1
|
||||
node qa/erase.test.cjs || status=1 # member erase (erase.js + scrub.js, 2026-11-15); qa/erase.mysql.test.cjs needs TEST_DATABASE_URL
|
||||
node --test qa/promodays.test.cjs || status=1 # Network Weekend 2026: promo days, Black Friday via friday.js, bundles, code start gate, pass days (2026-11-17)
|
||||
elif [ "$MODE" = "weekend" ]; then
|
||||
node --test qa/promodays.test.cjs || status=1
|
||||
node qa/weekend.e2e.mjs || status=1 # /weekend, Home strip, ribbon, feeds, builders key at test clocks (local copies + a fake hub)
|
||||
elif [ "$MODE" = "draft" ]; then
|
||||
node qa/draft-partner.test.mjs || status=1
|
||||
elif [ "$MODE" = "siteinvite" ]; then
|
||||
node qa/site-invite.test.mjs || status=1 # sponsor invite emails for other network sites (siteinvite.js, 2026-11-21)
|
||||
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
|
||||
@@ -93,6 +105,8 @@ elif [ "$MODE" = "walletnudge" ]; then
|
||||
node qa/walletnudge.test.cjs || status=1
|
||||
elif [ "$MODE" = "tankhold" ]; then
|
||||
node qa/tank-hold.mjs || status=1
|
||||
node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap
|
||||
node qa/tank-readiness.test.mjs || status=1 # holding tank readiness (2026-11-18): entry reasons, stage, heat against a LOCAL network hub; hub down = card as before
|
||||
elif [ "$MODE" = "sponsorfollow" ]; then
|
||||
node qa/sponsorfollow.test.cjs || status=1
|
||||
node qa/sponsorfollow-e2e.mjs || status=1
|
||||
@@ -100,6 +114,7 @@ elif [ "$MODE" = "kb" ]; then
|
||||
node qa/kb-retrieval.cjs || status=1
|
||||
node qa/kb-chat.mjs || status=1
|
||||
node qa/netkb-merge.test.cjs || status=1 # the shared network knowledge base: home first, a named site first, labels, fast-path skip (2026-11-15)
|
||||
node qa/netkb-semantic.test.mjs || status=1 # semantic matching via the hub (2026-11-16): route/suggest decisions, fail soft, shared-file parity
|
||||
elif [ "$MODE" = "door" ]; then
|
||||
node qa/door.mjs || status=1
|
||||
elif [ "$MODE" = "warpwares" ]; then
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
// Sponsor invite emails for other network sites (siteinvite.js, 2026-11-21). No server: the real module with in-memory accounts and
|
||||
// a capturing mailer on a throwaway dir. node qa/site-invite.test.mjs
|
||||
// Covers: the signature, directs only, once ever (and a replayed rid), who is never mailed, both daily caps, the pause switch,
|
||||
// the note and link checks, a failed send can be retried, no email address in any answer, the fixed wording.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const require = createRequire(path.join(SITE, 'package.json'));
|
||||
delete process.env.DATABASE_URL;
|
||||
let fails = 0, passes = 0; const ok = (c, l, x) => { console.log((c ? 'PASS ' : 'FAIL ') + l + (x !== undefined && !c ? ' ' + String(typeof x === 'string' ? x : JSON.stringify(x)).slice(0, 500) : '')); if (c) passes++; else fails++; };
|
||||
const SI = require(path.join(SITE, 'siteinvite.js')), prohibited = require(path.join(SITE, 'prohibited.js'));
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'siteinv-'));
|
||||
|
||||
// ---- the bench: sponsor "ann" with directs, one level-2 member, and every kind of person who must not be mailed ----
|
||||
const A = {};
|
||||
const add = (username, sponsor, x) => { const email = username + '@mail.test'; A[email] = Object.assign({ email, username, sponsorRef: sponsor || '', lastSeen: 1, memberId: 0, joinedVia: null, address: null }, x || {}); return A[email]; };
|
||||
add('ann', '', { address: '0x' + 'a'.repeat(40) });
|
||||
for (let i = 1; i <= 30; i++) add('d' + String(i).padStart(2, '0'), 'ann');
|
||||
add('bob', 'ann'); add('carl', 'bob'); // carl is level 2 under ann
|
||||
add('optout', 'ann'); add('flagged', 'ann'); add('gone', 'ann'); add('shell', 'ann', { joinedVia: 'hub', lastSeen: 0 }); add('never', 'ann', { lastSeen: 0 });
|
||||
add('typo', 'ann'); A['typo@mail.test'].email = 'typo@gmial.com'; A['typo@gmial.com'] = A['typo@mail.test']; delete A['typo@mail.test'];
|
||||
add('zed', ''); for (let i = 1; i <= 3; i++) add('z' + i, 'zed');
|
||||
const accounts = {
|
||||
byEmail: async e => A[String(e).toLowerCase()] || null,
|
||||
byUsername: async u => Object.values(A).find(a => a.username.toLowerCase() === String(u).toLowerCase()) || null,
|
||||
byAddress: async w => Object.values(A).find(a => a.address === w) || null,
|
||||
positionByAddress: async () => null,
|
||||
isUnclaimedShell: a => !!a && ['linkspin', 'btc4hits', 'hub'].includes(a.joinedVia) && !a.lastSeen && !a.memberId,
|
||||
sponsorOf: async e => { const a = A[String(e).toLowerCase()]; return a && a.sponsorRef ? Object.values(A).find(x => x.username === a.sponsorRef) || null : null; },
|
||||
async isDownlineOf(s, m, depth = 3) { let cur = String(m).toLowerCase(); for (let i = 0; i < depth; i++) { const sp = await this.sponsorOf(cur); if (!sp) return false; if (sp.email === s) return true; cur = sp.email; } return false; },
|
||||
downline: async (e, depth) => { const a = A[e]; return a ? [{ level: 1, members: Object.values(A).filter(x => x.sponsorRef === a.username) }] : []; }
|
||||
};
|
||||
const sent = []; let failNext = false, unsub = new Set(['optout@mail.test']);
|
||||
const mailer = { hasKey: () => true, send: async (...args) => { if (failNext) { failNext = false; throw new Error('sendgrid 500'); } if (unsub.has(args[0])) return false; sent.push(args); return true; } };
|
||||
let conf = {}, now = Date.parse('2026-11-21T15:00:00Z');
|
||||
const init = () => SI.init({ dataDir: dir, accounts, mailer, prohibited, siteConfig: () => conf, secret: 's'.repeat(40), linkHosts: 'clickvidpro.com', clock: () => now, gapMs: 0,
|
||||
hooks: { excluded: em => em === 'flagged@mail.test', excludedPerson: async em => (em === 'gone@mail.test' ? 'erased' : em.endsWith('@gmial.com') ? 'mistyped email domain' : unsub.has(em) ? 'unsubscribed from email' : null) } });
|
||||
await init();
|
||||
const L = u => 'https://clickvidpro.com/p/abc123/' + u + 'xxxx';
|
||||
const send = (items, x) => SI.handle('send', Object.assign({ rid: 'rid-' + Math.random().toString(36).slice(2) + 'abcdef', site: 'videoappincome', sender: { email: 'ann@mail.test' }, items }, x || {}));
|
||||
|
||||
// ---- signature ----
|
||||
{
|
||||
const raw = JSON.stringify({ site: 'videoappincome' }), ts = String(Date.now());
|
||||
ok(SI.verify({ 'x-invite-ts': ts, 'x-invite-sig': SI.sign(ts, raw) }, raw).body, 'a correctly signed call is accepted');
|
||||
ok(SI.verify({ 'x-invite-ts': ts, 'x-invite-sig': SI.sign(ts, raw + ' ') }, raw).status === 401, 'a changed body is refused');
|
||||
const old = String(Date.now() - 6 * 60000); ok(SI.verify({ 'x-invite-ts': old, 'x-invite-sig': SI.sign(old, raw) }, raw).status === 401, 'a call older than 5 minutes is refused');
|
||||
ok(SI.verify({}, raw).status === 401, 'an unsigned call is refused');
|
||||
}
|
||||
// ---- eligible ----
|
||||
{
|
||||
const r = await SI.handle('eligible', { site: 'videoappincome', sender: { email: 'ann@mail.test' } });
|
||||
const st = Object.fromEntries(r.directs.map(d => [d.username, d.state]));
|
||||
ok(r.ok && r.sender === 'ann' && st.d01 === 'ok' && st.bob === 'ok', 'directs who can be mailed are listed as ok', r);
|
||||
ok(!('carl' in st), 'a level 2 member is not listed');
|
||||
ok(['optout', 'flagged', 'gone', 'shell', 'never', 'typo'].every(u => st[u] === 'no'), 'unsubscribed, flagged, erased, never signed in and mistyped-domain directs are "no"', st);
|
||||
ok(!/@/.test(JSON.stringify(r)), 'no email address in the answer');
|
||||
ok(r.left.sender === 25 && r.left.network === 200, 'both daily allowances start full', r.left);
|
||||
const w = await SI.handle('eligible', { site: 'videoappincome', sender: { wallet: '0x' + 'A'.repeat(40) } }); ok(w.ok && w.sender === 'ann', 'the sender can be found by wallet');
|
||||
ok((await SI.handle('eligible', { site: 'videoappincome', sender: { email: 'nobody@mail.test' } })).code === 'sender', 'an unknown sender is refused');
|
||||
ok((await SI.handle('eligible', { site: 'othersite', sender: { email: 'ann@mail.test' } })).code === 'site', 'an unknown site is refused');
|
||||
}
|
||||
// ---- send: the rules ----
|
||||
{
|
||||
const body = { rid: 'rid-first-0001', site: 'videoappincome', sender: { email: 'ann@mail.test' }, items: [{ username: 'd01', link: L('d01') }, { username: 'carl', link: L('carl') }, { username: 'optout', link: L('o') }, { username: 'shell', link: L('s') }, { username: 'ann', link: L('a') }, { username: 'd02', link: 'https://evil.example/p/abc123' }, { username: 'ghost', link: L('g') }, { username: 'd01', link: L('d01') }] };
|
||||
const r = await SI.handle('send', body), st = r.results.map(x => x.status);
|
||||
ok(r.ok && r.sent === 1 && st[0] === 'sent', 'a direct is mailed', r);
|
||||
ok(st[1] === 'not your direct', 'a level 2 member is refused: directs only', st);
|
||||
ok(st[2] === 'no' && st[3] === 'no' && st[4] === 'not your direct', 'unsubscribed, never-signed-in and the sender themself are refused', st);
|
||||
ok(st[5] === 'bad link' && st[6] === 'no' && st[7] === 'duplicate', 'a link off the share domain, an unknown name and a repeat are refused', st);
|
||||
ok(sent.length === 1 && sent[0][0] === 'd01@mail.test' && sent[0].length === 4, 'exactly one email, and never with the transactional flag', sent.length);
|
||||
const [, subject, text, html] = sent[0];
|
||||
ok(subject === 'ann made you a video' && text.startsWith('Hi d01,') && text.includes(L('d01')) && html.includes('href="' + L('d01') + '"'), 'subject, greeting and the personal video link are right');
|
||||
ok(/I earn a share if you buy credits/.test(text) && /Nothing is promised/.test(text) && /one-time note sent through the network on their behalf/.test(text), 'the earning disclosure and the one-time footer are in the email');
|
||||
ok(!/guarantee|passive income|\bearn \$/i.test(text), 'no income promise in the wording');
|
||||
ok(!/@/.test(JSON.stringify(r)), 'no email address in the answer');
|
||||
const again = await SI.handle('send', body); ok(again.already && sent.length === 1, 'the same request replayed sends nothing');
|
||||
const r2 = await send([{ username: 'd01', link: L('d01') }]); ok(r2.results[0].status === 'sent before' && sent.length === 1, 'once ever: a second invite to the same person is refused');
|
||||
const e = await SI.handle('eligible', { site: 'videoappincome', sender: { email: 'ann@mail.test' } }); ok(e.directs.find(d => d.username === 'd01').state === 'sent' && e.left.sender === 24, 'the list shows them as sent and the allowance drops', e.left);
|
||||
}
|
||||
// ---- the note ----
|
||||
{
|
||||
ok((await send([{ username: 'd02', link: L('d02') }], { note: 'See https://my-site.example for more' })).code === 'note', 'a note with a link is refused');
|
||||
ok((await send([{ username: 'd02', link: L('d02') }], { note: 'This is guaranteed income.' })).code === 'note', 'a note that promises income is refused');
|
||||
ok((await send([{ username: 'd02', link: L('d02') }], { note: 'x'.repeat(401) })).code === 'note', 'a note over 400 characters is refused');
|
||||
const r = await send([{ username: 'd02', link: L('d02') }], { note: 'I used it for <b>my</b> banner site last night.' });
|
||||
ok(r.sent === 1 && sent[sent.length - 1][2].includes('\n\nI used it for my banner site last night.\n\n'), 'a clean note goes in as its own paragraph, tags stripped');
|
||||
}
|
||||
// ---- a failed send can be retried; unsubscribed at the last second is not recorded ----
|
||||
{
|
||||
failNext = true; const r = await send([{ username: 'd03', link: L('d03') }]); ok(r.results[0].status === 'failed', 'a mail failure is reported');
|
||||
const r2 = await send([{ username: 'd03', link: L('d03') }]); ok(r2.results[0].status === 'sent', 'and the same person can be tried again');
|
||||
unsub.add('d04@mail.test'); const saveHook = unsub; const r3 = await send([{ username: 'd04', link: L('d04') }]); ok(r3.results[0].status === 'no', 'someone who unsubscribed is not mailed');
|
||||
unsub.delete('d04@mail.test'); const r4 = await send([{ username: 'd04', link: L('d04') }]); ok(r4.results[0].status === 'sent', 'and no "sent" record was left behind for them');
|
||||
}
|
||||
// ---- caps, pause, batch size ----
|
||||
{
|
||||
ok((await send(Array.from({ length: 26 }, (_, i) => ({ username: 'd' + String(i + 1).padStart(2, '0'), link: L('x') })))).code === 'count', 'more than 25 in one request is refused');
|
||||
const names = Array.from({ length: 25 }, (_, i) => 'd' + String(i + 5).padStart(2, '0')); // d05..d29: ann has sent 4 today, 21 left
|
||||
const r = await send(names.map(u => ({ username: u, link: L(u) })));
|
||||
ok(r.sent === 21 && r.results.filter(x => x.status === 'your daily limit').length === 4 && r.left.sender === 0, 'one sender stops at 25 a day', { sent: r.sent, left: r.left });
|
||||
now += 24 * 3600000; const r2 = await send([{ username: 'd26', link: L('d26') }]); ok(r2.sent === 1, 'the next Central day the allowance is back');
|
||||
conf = { siteInvitePerDay: 2 }; const z = await SI.handle('send', { rid: 'rid-zed-000001', site: 'videoappincome', sender: { email: 'zed@mail.test' }, items: ['z1', 'z2', 'z3'].map(u => ({ username: u, link: L(u) })) });
|
||||
ok(z.sent === 1 && z.results.filter(x => x.status === 'network daily limit').length === 2, 'the all-senders daily cap stops everyone', z.results);
|
||||
conf = { siteInvitesPaused: '1' }; ok((await send([{ username: 'd27', link: L('d27') }])).code === 'paused', 'the pause switch stops sending'); conf = {};
|
||||
}
|
||||
// ---- survives a restart: the once-ever record is on disk ----
|
||||
{
|
||||
await init(); const n = sent.length; const r = await send([{ username: 'd01', link: L('d01') }]);
|
||||
ok(r.results[0].status === 'sent before' && sent.length === n, 'after a restart the once-ever rule still holds');
|
||||
const v = await SI.adminView(); ok(v.on && v.recent.length > 20 && !/@/.test(JSON.stringify(v)), 'the admin view lists invites by username only');
|
||||
}
|
||||
// ---- the email-check code mail (a site's network gate) ----
|
||||
{
|
||||
const n = sent.length; let r = await SI.handle('code', { site: 'videoappincome', email: 'New.Person@Mail.test', code: '482913' });
|
||||
const m = sent[sent.length - 1];
|
||||
ok(r.ok && sent.length === n + 1 && m[0] === 'new.person@mail.test' && m[1] === '482913 is your Video App Income code' && m[2].startsWith('Your code is: 482913') && !/https?:/.test(m[2]), 'the code mail goes out with the code, the site name and no links', m && m.slice(0, 3));
|
||||
ok(m[4] && m[4].transactional === true && m[4].fromName === 'Video App Income', 'it is sent as a requested (transactional) mail under the site name');
|
||||
ok((await SI.handle('code', { site: 'videoappincome', email: 'not an email', code: '111111' })).code === 'email', 'a bad address is refused');
|
||||
ok((await SI.handle('code', { site: 'videoappincome', email: 'a@mail.test', code: '12ab' })).code === 'email', 'a code that is not six digits is refused');
|
||||
ok((await SI.handle('code', { site: 'videoappincome', email: 'x@mailinator.com', code: '111111' })).code === 'email', 'a throwaway address is refused');
|
||||
ok((await SI.handle('code', { site: 'videoappincome', email: 'flagged@mail.test', code: '111111' })).code === 'email', 'a suspended or flagged address is refused');
|
||||
ok((await SI.handle('code', { site: 'nosuchsite', email: 'a@mail.test', code: '111111' })).code === 'site', 'an unknown site is refused');
|
||||
for (let i = 0; i < 4; i++) await SI.handle('code', { site: 'videoappincome', email: 'new.person@mail.test', code: '482913' });
|
||||
r = await SI.handle('code', { site: 'videoappincome', email: 'new.person@mail.test', code: '482913' }); ok(r.code === 'limit', 'the sixth code to one address in an hour is refused', r);
|
||||
}
|
||||
// ---- a ready-made video about the site itself (kind 'promo', Marty 2026-11-21): the email must not say the sender made it ----
|
||||
{
|
||||
const own = SI.compose(SI.SITES.videoappincome, 'ann', 'd01', L('d01'), ''), pro = SI.compose(SI.SITES.videoappincome, 'ann', 'd01', L('d01'), '', 'promo');
|
||||
ok(own.subject === 'ann made you a video' && own.text.includes("Here's one I made: " + L('d01')), 'their own video keeps the approved wording');
|
||||
ok(pro.subject === 'ann sent you a video' && pro.text.includes("Here's a short video that shows how it works: " + L('d01')) && !/I made|made you/.test(pro.text + pro.subject), 'a ready-made video is never called the sender\'s own');
|
||||
ok(pro.html.includes('href="' + L('d01') + '"'), 'the link is clickable in the ready-made version');
|
||||
const strip = t => t.replace("Here's a short video that shows how it works: ", "Here's one I made: ");
|
||||
ok(strip(pro.text) === own.text, 'every other word of the email is the same');
|
||||
const n = sent.length, r = await SI.handle('send', { rid: 'rid-promo-000001', site: 'videoappincome', sender: { email: 'bob@mail.test' }, kind: 'promo', items: [{ username: 'carl', link: L('carl') }] });
|
||||
if (r.ok && r.sent === 1) ok(sent.length === n + 1 && sent[n][1] === 'bob sent you a video' && /shows how it works/.test(sent[n][2]), 'the send call passes the kind through to the email', sent[n] && sent[n][1]);
|
||||
else ok(false, 'promo send through the full path', r);
|
||||
}
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
console.log('\n' + passes + ' passed, ' + fails + ' failed'); process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,36 @@
|
||||
// Help desk suggestions (2026-11-16): POST /api/my/support/suggest on a LOCAL copy (bash qa/run.sh member starts it; no hub there,
|
||||
// so the answers come from the BM25 fallback, the path members get when the hub or the model is down). Checks: signed out is refused,
|
||||
// a typed problem gets the matching help answer, short text asks nothing, the contact-support entry is never offered, and a ticket
|
||||
// still sends right after (a suggestion never blocks Send). LinkSpin ships the same file (SUGGEST_SEND=0 there: its desk is IAP's).
|
||||
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] support-suggest ' + m + (x ? ' :: ' + x : '')); } };
|
||||
const email = 'sg' + 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 SupportSuggestQA' };
|
||||
let cookie = '';
|
||||
async function post(p, b) {
|
||||
const r = await fetch(B + p, { method: 'POST', headers: Object.assign({}, H, cookie ? { Cookie: cookie } : {}), body: JSON.stringify(b) });
|
||||
const sc = typeof r.headers.getSetCookie === 'function' ? r.headers.getSetCookie() : [];
|
||||
if (sc.length) cookie = sc.map(c => c.split(';')[0]).join('; ');
|
||||
return { status: r.status, j: await r.json().catch(() => ({})) };
|
||||
}
|
||||
try {
|
||||
ok((await post('/api/my/support/suggest', { subject: 'my payout', body: 'never arrived' })).status === 401, 'signed out is refused');
|
||||
const st = await post('/api/auth/email/start', { email, fts: Date.now() - 8000, fage: 8000 });
|
||||
if (st.j.devCode) await post('/api/auth/email/verify', { email, code: st.j.devCode });
|
||||
ok(!!cookie, 'signed in for the test');
|
||||
let r = await post('/api/my/support/suggest', { subject: 'Coinbase', body: 'Can I hook up my Coinbase account to pay for a package?' });
|
||||
ok(r.status === 200 && Array.isArray(r.j.items) && r.j.items.length > 0, 'a typed problem gets suggestions', JSON.stringify(r.j).slice(0, 200));
|
||||
ok(r.j.items && r.j.items.some(i => /coinbase/i.test(i.title + ' ' + i.answer)), 'the matching help answer is offered', (r.j.items || []).map(i => i.id).join());
|
||||
ok(['semantic', 'bm25'].includes(r.j.via), 'answered by the hub or the BM25 fallback (' + r.j.via + ')');
|
||||
ok(r.j.items.every(i => !/(^|[-:])support$/.test(i.id) && i.title && i.answer), 'no contact-support entry, every item has a title and an answer');
|
||||
r = await post('/api/my/support/suggest', { subject: 'hi', body: '' });
|
||||
ok(r.status === 200 && r.j.items.length === 0, 'short text asks nothing');
|
||||
r = await post('/api/my/support/suggest', { subject: 'I want to talk to a real person', body: 'please contact me, I need support from a human' });
|
||||
ok(r.status === 200 && r.j.items.every(i => !/(^|[-:])support$/.test(i.id)), 'asking for a person never suggests the contact-support entry');
|
||||
if (process.env.SUGGEST_SEND !== '0') {
|
||||
const t = await post('/api/my/support', { category: 'Other', subject: 'Coinbase question (QA)', body: 'Can I hook up my Coinbase account to pay for a package? (support-suggest QA)' });
|
||||
ok(t.status === 200 && /^IAP-\d+$/.test(String(t.j.ref || '')), 'the ticket still sends after suggestions', JSON.stringify(t.j).slice(0, 160));
|
||||
}
|
||||
} catch (e) { fail++; console.log('[bug] support-suggest crashed :: ' + e.message); }
|
||||
console.log('support-suggest: ' + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,232 @@
|
||||
// Holding tank batches (tankbatch.js, Marty 2026-11-15). No server: the real tank.js + tankbatch.js with in-memory accounts, a
|
||||
// fake chain, a fake refuel standing and capturing mail/notice/feed hooks, on a throwaway dir, mocked clock. node qa/tank-batch.test.mjs
|
||||
// Covers: the ladder (incl. opgnetwerk's real case = 25), switch off = no writes, preview writes nothing, highest tier first by
|
||||
// rotation, sizes, sign-up grace, self / loop / adopted twice / opted out never dealt, cadence (2 days, top up to size), the
|
||||
// follow-up (uncontacted back to the tank, not counted), tank.sweep leaves batch picks alone, the 5x draft's separate cap.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const require = createRequire(path.join(SITE, 'package.json'));
|
||||
delete process.env.DATABASE_URL;
|
||||
let fails = 0, passes = 0; const ok = (c, l, x) => { console.log((c ? 'PASS ' : 'FAIL ') + l + (x !== undefined && !c ? ' ' + String(typeof x === 'string' ? x : JSON.stringify(x)).slice(0, 400) : '')); if (c) passes++; else fails++; };
|
||||
const DAY = 86400000, H = 3600000;
|
||||
|
||||
// ---- the ladder, pure ----
|
||||
const TB0 = require(path.join(SITE, 'tankbatch.js'));
|
||||
{
|
||||
const c = Object.assign({}, { base: 10, fueled: 20, twin: 25, step: 5, max: 50, minIap: 2000, minLs: 2500, higherIap: 5000, higherLs: 5000, topIap: 50000, topLs: 50000 });
|
||||
const t = f => TB0.tierFor(Object.assign({ iapMax: 0, lsMax: 0, refuel: null }, f), c);
|
||||
ok(t({}).size === 0 && !t({}).level, 'no package: not on the ladder');
|
||||
ok(t({ iapMax: 1000 }).size === 0, 'a $10 package does not qualify');
|
||||
ok(t({ iapMax: 2000 }).size === 10 && t({ iapMax: 2000 }).level === 'Paid', '$20 InstantAdPay = Paid 10');
|
||||
ok(t({ lsMax: 2500 }).size === 10, '$25 LinkSpin = Paid 10');
|
||||
ok(t({ lsMax: 2000 }).size === 0, '$20 on LinkSpin is below its $25 bar');
|
||||
ok(t({ iapMax: 5000 }).size === 20 && t({ iapMax: 5000 }).level === 'Fueled', 'a $50 (higher) package = Fueled 20');
|
||||
ok(t({ iapMax: 2000, refuel: { active: true, streak: 1, both: false } }).size === 20, 'refuel streak active = Fueled 20');
|
||||
ok(t({ iapMax: 25000 }).size === 20, '$250 is higher, not top: 20');
|
||||
ok(t({ iapMax: 50000 }).size === 25 && t({ iapMax: 50000 }).level === 'Twin Engine', 'the top package ($500) = 25');
|
||||
const opg = t({ iapMax: 2000, lsMax: 2500, refuel: { active: true, streak: 1, both: true } });
|
||||
ok(opg.size === 25 && opg.level === 'Twin Engine', 'opgnetwerk (month 1, both engines 10-27, $20 IAP + $25 LS, nothing above $20) = Twin Engine 25', opg);
|
||||
ok(t({ iapMax: 2000, refuel: { active: true, streak: 3, both: false } }).size === 30, 'single engine month 3 = 20 + 10 = 30');
|
||||
ok(t({ iapMax: 2000, lsMax: 2500, refuel: { active: true, streak: 3, both: true } }).size === 35, 'twin month 3 = 25 + 10 = 35');
|
||||
ok(t({ iapMax: 2000, lsMax: 2500, refuel: { active: true, streak: 12, both: true } }).size === 50, 'capped at 50');
|
||||
ok(t({ iapMax: 2000, refuel: { active: false, streak: 0, both: false } }).size === 10, 'a lapsed streak counts nothing');
|
||||
ok(/20/.test(TB0.nextStep(t({ iapMax: 2000 }), { iapMax: 2000 }, c)), 'next step from Paid names 20');
|
||||
ok(!/income|earn|\$/.test(TB0.ladderView(c).map(r => r.how).join(' ').replace(/\$\d+/g, '')), 'ladder copy promises no income');
|
||||
}
|
||||
|
||||
// ---- the bench ----
|
||||
function bench(opts) {
|
||||
for (const m of ['tank.js', 'tankbatch.js']) delete require.cache[require.resolve(path.join(SITE, m))];
|
||||
const tank = require(path.join(SITE, 'tank.js')); const tb = require(path.join(SITE, 'tankbatch.js'));
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankbatch-'));
|
||||
let now = Date.UTC(2026, 10, 16, 15, 0, 0); const clock = () => now;
|
||||
const by = new Map(); let n = 100; const pub = a => a ? Object.assign({}, a) : null; const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
|
||||
const accounts = {
|
||||
add(email, o) { by.set(email, Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (n++), sponsorRef: '', memberId: 0, address: null, created: now - 5 * DAY, lastSeen: now - 2 * H, joinedVia: 'page', joinedRef: null }, o || {})); },
|
||||
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); }, async byUsername(u) { return find(a => a.username === String(u || '').toLowerCase()); }, async byCode(c) { return find(a => a.code === String(c || '').toLowerCase()); },
|
||||
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); }, async setSponsorRef(e, ref) { const a = by.get(e); a.sponsorRef = String(ref || ''); return { ok: true }; },
|
||||
async listAll() { return [...by.values()].map(pub); }, async positions() { return []; },
|
||||
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; const t = a.sponsorRef; return find(x => x.username === t || x.code === t || String(x.memberId) === t); }, _by: by };
|
||||
const events = []; const mails = []; const chats = []; const notices = []; const feeds = []; const toasts = []; const sent = [];
|
||||
const standing = new Map(); const optOut = new Set(); const announces = []; const claims = new Set();
|
||||
const messages = { sendChat: async (id, from, to, text) => { chats.push({ from, to, text, at: now }); sent.push({ from, to, at: now }); }, lastFrom: async (f, t) => sent.filter(x => x.from === f && x.to === t).reduce((m, x) => Math.max(m, x.at), 0) };
|
||||
const mailer = { hasKey: () => true, send: async (to, subject, text) => { mails.push({ to, subject, text }); } };
|
||||
const chain = { recentEvents: () => events.slice(), getConfig: () => ({}), catalog: async () => [500, 1000, 2000, 5000, 10000, 25000, 50000].map((p, i) => ({ id: i + 1, priceCents: p })) };
|
||||
const site = Object.assign({ tankBatches: '0' }, opts && opts.site);
|
||||
tank.init({ dataDir: dir, accounts, chain, messages, mailer, site: 'https://instantadpay.test', capOpen: () => 10,
|
||||
hooks: { isBatchPick: id => tb.isBatchPick(id), isDraftPick: async () => false } });
|
||||
tank.setClock(clock);
|
||||
return { announces, claims, tank, tb, accounts, events, mails, chats, notices, feeds, toasts, standing, optOut, site, dir, messages,
|
||||
advance: ms => { now += ms; }, now: () => now,
|
||||
async start() {
|
||||
await tb.init({ dataDir: dir, db: { enabled: () => false }, accounts, chain, tank, messages, mailer, siteConfig: () => site, clock,
|
||||
refuel: { standing: async e => standing.get(e) || null },
|
||||
hooks: { companyId: () => 1, claim: async k => { if (claims.has(k)) return false; claims.add(k); return true; }, announce: async html => { announces.push(html); }, excludedPerson: async e => optOut.has(e) ? 'unsubscribed from email' : null,
|
||||
notify: async (to, subject, text) => { notices.push({ to, subject, text }); }, feed: async (who, what, level) => { feeds.push(who + ' just received ' + what + ' from the holding tank (' + level + ' level)'); }, toast: ev => toasts.push(ev) } });
|
||||
} };
|
||||
}
|
||||
function seed(B, tankCount) {
|
||||
const { accounts, events, standing } = B;
|
||||
accounts.add('house@x.co', { username: 'house', memberId: 1, address: '0x' + '0'.repeat(40) });
|
||||
accounts.add('opg@x.co', { username: 'opgnetwerk', memberId: 2, address: '0x' + '2'.repeat(40) });
|
||||
accounts.add('fuel@x.co', { username: 'fueler', memberId: 3, address: '0x' + '3'.repeat(40) });
|
||||
accounts.add('paid@x.co', { username: 'paider', memberId: 4, address: '0x' + '4'.repeat(40) });
|
||||
accounts.add('sleepy@x.co', { username: 'sleepy', memberId: 5, address: '0x' + '5'.repeat(40), lastSeen: B.now() - 9 * DAY });
|
||||
accounts.add('free@x.co', { username: 'freebie', memberId: 6, address: '0x' + '6'.repeat(40) });
|
||||
// opgnetwerk's real purchases: 11 x $20, 2 x $10, 9 x $5 on InstantAdPay
|
||||
let blk = 1; for (let i = 0; i < 11; i++) events.push({ type: 'Purchase', buyerId: 2, priceCents: 2000, block: blk++ }); for (let i = 0; i < 2; i++) events.push({ type: 'Purchase', buyerId: 2, priceCents: 1000, block: blk++ }); for (let i = 0; i < 9; i++) events.push({ type: 'Purchase', buyerId: 2, priceCents: 500, block: blk++ });
|
||||
standing.set('opg@x.co', { active: true, streak: 1, both: true, lastDay: '2026-10-27', maxCents: { iap: 2000, linkspin: 2500 } });
|
||||
events.push({ type: 'Purchase', buyerId: 3, priceCents: 5000, block: blk++ }); // fueler: a $50 package = higher
|
||||
events.push({ type: 'Purchase', buyerId: 4, priceCents: 2000, block: blk++ }); // paider: $20
|
||||
events.push({ type: 'Purchase', buyerId: 5, priceCents: 2000, block: blk++ }); // sleepy: paid but away 9 days
|
||||
events.push({ type: 'Purchase', buyerId: 6, priceCents: 1000, block: blk++ }); // freebie: $10 only
|
||||
for (let i = 0; i < tankCount; i++) B.accounts.add('t' + String(i).padStart(3, '0') + '@tank.co', { lastSeen: B.now() - (i + 1) * 60000 });
|
||||
}
|
||||
|
||||
// ---- switch off: nothing written, nothing sent; the preview is read-only ----
|
||||
{
|
||||
const B = bench(); seed(B, 70); await B.start();
|
||||
const r = await B.tb.round();
|
||||
ok(r.on === false, 'switch off: the round does not run');
|
||||
ok(!B.mails.length && !B.chats.length && !B.feeds.length && !B.toasts.length && !B.notices.length, 'switch off: no mail, chat, feed or toast');
|
||||
ok(!fs.existsSync(path.join(B.dir, 'tank-batch.json')) && !fs.existsSync(path.join(B.dir, 'tank.json')), 'switch off: no state file written');
|
||||
const v = await B.tb.myView('opg@x.co'); ok(v.on === false, 'switch off: the member panel is hidden');
|
||||
const before = JSON.stringify([...B.accounts._by.values()]);
|
||||
const pv = await B.tb.preview();
|
||||
ok(pv.readOnly && pv.on === false, 'preview runs with the switch off');
|
||||
ok(JSON.stringify([...B.accounts._by.values()]) === before && !B.mails.length && !B.chats.length && !fs.existsSync(path.join(B.dir, 'tank-batch.json')) && !fs.existsSync(path.join(B.dir, 'tank.json')), 'preview writes nothing and sends nothing');
|
||||
const opg = pv.sponsors.find(s => s.name === '@opgnetwerk');
|
||||
ok(opg && opg.size === 25 && /Twin Engine/.test(opg.level) && opg.wouldGet === 25, 'preview: opgnetwerk at Twin Engine, 25', opg);
|
||||
ok(pv.sponsors[0].name === '@opgnetwerk', 'preview: highest tier first');
|
||||
ok((pv.sponsors.find(s => s.name === '@fueler') || {}).size === 20 && (pv.sponsors.find(s => s.name === '@paider') || {}).size === 10, 'preview: fueler 20, paider 10');
|
||||
ok(!pv.sponsors.some(s => ['@sleepy', '@freebie', '@house'].includes(s.name)), 'preview: inactive, $10-only and the company are not sponsors');
|
||||
ok(pv.notEligible.members.some(m => m.name === '@sleepy' && /not active/.test(m.reason)), 'preview: the inactive paid member is listed as a near miss');
|
||||
ok(pv.totals.people === 55 && pv.tank.leftAfterRound === 15, 'preview: 55 dealt, 15 left', pv.totals);
|
||||
}
|
||||
|
||||
// ---- switch on: a live round ----
|
||||
{
|
||||
const B = bench({ site: { tankBatches: '1' } }); seed(B, 50); await B.start();
|
||||
// exclusions: 2 in the sign-up grace, 1 adopted twice, 1 opted out, 1 above a sponsor in their own line (paider's sponsor)
|
||||
B.accounts.add('new1@tank.co', { created: B.now() - 2 * H }); B.accounts.add('new2@tank.co', { created: B.now() - 20 * H });
|
||||
B.accounts.add('twice@tank.co'); const tj = B.tank._json.state(); tj.adoptions.push({ id: tj.nextId++, adoptee: 'twice@tank.co', adopter: 'z@x.co', ts: 1, expires: 1, status: 'expired' }, { id: tj.nextId++, adoptee: 'twice@tank.co', adopter: 'y@x.co', ts: 1, expires: 1, status: 'dropped' }); B.tank._json.save();
|
||||
B.accounts.add('optout@tank.co'); B.optOut.add('optout@tank.co');
|
||||
B.accounts.add('upline@tank.co', { username: 'uplinez' }); B.accounts._by.get('paid@x.co').sponsorRef = 'uplinez';
|
||||
const r = await B.tb.round();
|
||||
const got = e => B.tank._json.state().adoptions.filter(a => a.adopter === e && a.status === 'open').length;
|
||||
ok(r.on && r.assigned === 51, 'round assigns the whole offered pool (51 open waiting people incl. the upline of paider, 55 places)', r);
|
||||
ok(got('opg@x.co') === 21 && got('fuel@x.co') === 20 && got('paid@x.co') === 10, 'rotation: paider fills 10, then opg and fueler share the rest one by one, opg first (21 / 20)', [got('opg@x.co'), got('fuel@x.co'), got('paid@x.co')]);
|
||||
const first = B.tank._json.state().adoptions.filter(a => a.status === 'open')[0];
|
||||
ok(first && first.adopter === 'opg@x.co', 'the first person goes to the highest tier');
|
||||
const dealt = new Set(B.tank._json.state().adoptions.filter(a => a.status === 'open').map(a => a.adoptee));
|
||||
ok(!dealt.has('new1@tank.co') && !dealt.has('new2@tank.co'), 'the 24-hour sign-up grace is respected');
|
||||
ok(!dealt.has('twice@tank.co'), 'nobody adopted twice already');
|
||||
ok(!dealt.has('optout@tank.co'), 'an opted-out person is never dealt');
|
||||
ok(!B.tank._json.state().adoptions.some(a => a.adoptee === 'upline@tank.co' && a.adopter === 'paid@x.co'), 'never a sponsor\'s own upline');
|
||||
ok(![...dealt].some(e => /@x\.co$/.test(e)), 'never a sponsor themself');
|
||||
ok(B.accounts._by.get('t000@tank.co').sponsorRef === 'opgnetwerk', 'the sponsor change is written like an adoption');
|
||||
const adoptMails = () => B.mails.filter(m => /is now your sponsor on InstantAdPay/.test(m.subject));
|
||||
ok(adoptMails().length === 0, 'the "X is now your sponsor" emails are queued, not sent in a burst', adoptMails().length);
|
||||
const ob = () => JSON.parse(fs.readFileSync(path.join(B.dir, 'tank-batch.json'), 'utf8')).outbox;
|
||||
ok(ob().filter(x => x.kind === 'mail' && x.status === 'queued').length === 51 && ob().filter(x => x.kind === 'mail').every(x => /is now your sponsor on InstantAdPay/.test(x.subject)), '51 adoption emails queued, oldest first', ob().length);
|
||||
ok(!Object.keys(B.tank._ready.state().pay || {}).length, 'no switch-on reminders start before the email goes out');
|
||||
ok(B.chats.length === 51 && B.chats.every(c => /matched with me from the holding tank/.test(c.text)), 'every person gets a chat from their new sponsor');
|
||||
ok(B.notices.filter(x => /holding tank are in your line/.test(x.subject)).length === 3 && B.mails.filter(m => /from the holding tank are in your line/.test(m.subject)).length === 3, 'each sponsor gets one notice and one email per batch, not one per person');
|
||||
ok(B.feeds.length === 0 && B.announces.length === 0, 'Telegram posts wait for the outbox');
|
||||
for (let i = 0; i < 4; i++) { await B.tb.mailTick(); await B.tb.mailTick(); B.advance(2 * 60000); }
|
||||
ok(B.announces.length === 1 && /3 new|51 new members just got a sponsor/.test(B.announces[0]) && /<b>Twin Engine<\/b>: @opgnetwerk 21/.test(B.announces[0]) && /= 25;/.test(B.announces[0]) && !/t0\d\d|income|\u2014/.test(B.announces[0]), 'one round announcement: total, sponsors by level, how to qualify, no people, no income', B.announces[0]);
|
||||
ok(B.feeds.length === 3 && B.feeds[0] === '@opgnetwerk just received 21 new team members from the holding tank (Twin Engine level)', 'tank feed cards: one per sponsor, sponsor, count, level', B.feeds);
|
||||
ok(adoptMails().length === 1, 'one email per 7.2 minutes at most (8 ticks over 6 minutes: one)', adoptMails().length);
|
||||
ok(!B.feeds.some(f => /t0\d\d/.test(f)) && B.toasts.length === 3 && B.toasts.every(t => t.type === 'Adopted' && !/t0\d\d/.test(t.member)), 'feed and toasts never name the people');
|
||||
ok(!B.mails.concat(B.notices).some(m => /—/.test(m.subject + m.text)), 'no em dash in any batch copy');
|
||||
// the member's own tank button and the 5x draft keep their own allowances
|
||||
ok((await B.tank.eligibility('opg@x.co')).ok, 'batch people do not use up the member\'s own tank-button cap');
|
||||
ok((await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok, '5x draft cap is separate from batches');
|
||||
const mv = await B.tb.myView('opg@x.co'); ok(mv.on && mv.me.size === 25 && mv.me.open === 21 && /month adds 5/.test(mv.me.next), 'member panel: level, size, open, next step', mv.me);
|
||||
|
||||
// cadence: nothing before 2 days; at 2 days only room (size - held) is topped up
|
||||
const more = n => { for (let i = 0; i < n; i++) B.accounts.add('late' + i + '@tank.co', { created: B.now() - 3 * DAY }); };
|
||||
more(30);
|
||||
B.advance(1 * DAY); let r2 = await B.tb.round(); ok(r2.assigned === 0, 'no new batch before 2 days');
|
||||
B.advance(1 * DAY + H); r2 = await B.tb.round();
|
||||
ok(got('opg@x.co') === 25 && got('fuel@x.co') === 20 && got('paid@x.co') === 10, 'after 2 days: opg topped up to 25, full sponsors get nothing', [got('opg@x.co'), got('fuel@x.co'), got('paid@x.co')]);
|
||||
ok(r2.assigned === 4, 'second round dealt 4', r2);
|
||||
|
||||
// tank.sweep leaves batch picks to tankbatch (its window ended in the tank's own terms)
|
||||
for (const a of B.tank._json.state().adoptions) if (a.status === 'open') a.expires = 0; B.tank._json.save();
|
||||
await B.tank.sweep();
|
||||
ok(got('opg@x.co') === 25, 'tank.sweep does not close batch adoptions');
|
||||
|
||||
// follow-up at 7 days: contacted stay / close, uncontacted go back to the tank as 'unreached' (not counted)
|
||||
const opgPeople = B.tank._json.state().adoptions.filter(a => a.adopter === 'opg@x.co' && a.status === 'open').map(a => a.adoptee).slice(0, 20);
|
||||
const [chatted, marked, walletC, activated] = opgPeople;
|
||||
B.advance(1 * DAY); // now 3 days after the first batch
|
||||
await B.messages.sendChat(2, 'opg@x.co', chatted, 'hello');
|
||||
B.tank._json.state().marks[marked] = { sponsor: 'opg@x.co', contacted: B.now(), warned: 0 }; B.tank._json.save();
|
||||
await B.messages.sendChat(2, 'opg@x.co', walletC, 'hi'); B.accounts._by.get(walletC).address = '0x' + 'a'.repeat(40);
|
||||
B.accounts._by.get(activated).memberId = 900;
|
||||
B.advance(2 * DAY); let f = await B.tb.followUp(); ok(f.done === 1 && f.unreached === 0, 'before 7 days only the activated one closes (done)', f);
|
||||
B.advance(2 * DAY + H); f = await B.tb.followUp();
|
||||
ok(f.unreached === 47 && f.done === 1 && f.returned === 2, 'at 7 days (first batch only): 47 never contacted go back, contacted+wallet done, 2 contacted without wallet back (counted); the 2-day-old top-up waits', f);
|
||||
ok(B.accounts._by.get(opgPeople[5]).sponsorRef === '' && (B.tank._json.state().adoptions.find(a => a.adoptee === opgPeople[5] && a.adopter === 'opg@x.co') || {}).status === 'unreached', 'an uncontacted person is back in the tank, status unreached');
|
||||
ok((await B.tank.countAll(opgPeople[5])) === 0, 'unreached does not count toward their two adoptions');
|
||||
ok((await B.tank.countAll(chatted)) === 1, 'a contacted, unconverted return still counts');
|
||||
ok(B.notices.some(x => x.to === 'opg@x.co' && /went back to the tank/.test(x.subject)), 'the sponsor is told once who went back');
|
||||
}
|
||||
|
||||
// ---- the 5x draft cap counts draft picks only ----
|
||||
{
|
||||
const B = bench({ site: { tankBatches: '1' } }); seed(B, 15); await B.start();
|
||||
let draftIds = new Set();
|
||||
B.tank.init({ dataDir: B.dir, accounts: B.accounts, chain: { recentEvents: () => B.events.slice(), getConfig: () => ({}) }, messages: B.messages, mailer: { hasKey: () => false }, capOpen: () => 10, hooks: { isDraftPick: async id => draftIds.has(id), isBatchPick: id => B.tb.isBatchPick(id) } });
|
||||
for (let i = 0; i < 10; i++) { const r = await B.tank.adopt('opg@x.co', 't' + String(i).padStart(3, '0') + '@tank.co'); if (r.ok) draftIds.add(r.adoption.id); }
|
||||
ok(draftIds.size === 10, 'ten plain adoptions');
|
||||
draftIds = new Set(); // they were plain: the draft has 0 of its own
|
||||
ok((await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok, 'ten plain adoptions do not fill the draft cap');
|
||||
ok(!(await B.tank.eligibility('opg@x.co')).ok, 'and they do fill the plain tank-button cap');
|
||||
const ids = B.tank._json.state().adoptions.filter(a => a.status === 'open').map(a => a.id); draftIds = new Set(ids);
|
||||
ok(!(await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok && (await B.tank.eligibility('opg@x.co')).ok, 'ten draft picks fill the draft cap only');
|
||||
}
|
||||
// ---- the throttled outbox: cap, window, skip-if-changed, pause, two app copies ----
|
||||
{
|
||||
const B = bench({ site: { tankBatches: '1', tankBatchEmailsPerDay: 5 } }); seed(B, 12); await B.start();
|
||||
await B.tb.round(); // 10 to paider? no: opg / fueler / paider share 12
|
||||
const ob = () => JSON.parse(fs.readFileSync(path.join(B.dir, 'tank-batch.json'), 'utf8')).outbox.filter(x => x.kind === 'mail');
|
||||
const sentMail = () => B.mails.filter(m => /is now your sponsor on InstantAdPay/.test(m.subject));
|
||||
ok(ob().length === 12, '12 queued');
|
||||
// window: 9 PM CT (03:00 UTC next day) nothing goes
|
||||
const at = (h, m) => { const d = new Date(B.now()); const want = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), h + 6, m || 0); B.advance(want - B.now()); };
|
||||
at(21, 0); await B.tb.mailTick(); ok(sentMail().length === 0, 'outside 8 AM to 8 PM CT: nothing sent');
|
||||
at(7, 59 + 24 * 60); await B.tb.mailTick(); ok(sentMail().length === 0, '7:59 AM CT: still nothing');
|
||||
B.advance(60000); await B.tb.mailTick(); ok(sentMail().length === 1, '8:00 AM CT: the first one goes');
|
||||
const v = await B.tb.mailView(); ok(v.sentToday === 1 && v.queued === 11 && v.spacingMin === 144 && v.nextSendAt === B.now() + 144 * 60000, 'admin view: sent today, queued, next send time (12 h / 5 = 144 min apart)', v);
|
||||
B.advance(60 * 60000); await B.tb.mailTick(); ok(sentMail().length === 1, 'spread through the day, not a burst');
|
||||
// skip if changed: the next queued person left that sponsor, the one after unsubscribed: both skipped, the third is sent in the same tick
|
||||
const q = ob().filter(x => x.status === 'queued');
|
||||
B.accounts._by.get(q[0].to).sponsorRef = ''; B.optOut.add(q[1].to);
|
||||
B.advance(90 * 60000); const r = await B.tb.mailTick();
|
||||
ok(r.skipped === 2 && r.sent === 1 && sentMail().length === 2 && !sentMail().some(m => m.to === q[0].to || m.to === q[1].to), 'skip-if-changed: moved and unsubscribed are skipped, the next is sent', r);
|
||||
ok(Object.keys(B.tank._ready.state().pay || {}).length === 2, 'the switch-on reminders start when each email goes out');
|
||||
// pause
|
||||
await B.tb.setPaused(true); B.advance(150 * 60000); await B.tb.mailTick(); ok(sentMail().length === 2 && (await B.tb.mailView()).paused, 'paused: nothing goes');
|
||||
await B.tb.setPaused(false); await B.tb.mailTick(); ok(sentMail().length === 3, 'resumed: sending again');
|
||||
// the day cap (5): 3 sent, 2 more today, then nothing until tomorrow
|
||||
for (let i = 0; i < 6; i++) { B.advance(145 * 60000); if (!B.tb._inWindow(B.now(), B.tb.cfg())) break; await B.tb.mailTick(); }
|
||||
const sentToday = (await B.tb.mailView()).sentToday; ok(sentToday <= 5, 'never more than tankBatchEmailsPerDay in a Central day', sentToday);
|
||||
// two app copies on one store: every row goes once
|
||||
for (const m of ['tankbatch.js']) delete require.cache[require.resolve(path.join(SITE, m))];
|
||||
const tb2 = require(path.join(SITE, 'tankbatch.js'));
|
||||
await tb2.init({ dataDir: B.dir, db: { enabled: () => false }, accounts: B.accounts, chain: { recentEvents: () => [], catalog: async () => [] }, tank: B.tank, messages: B.messages,
|
||||
mailer: { hasKey: () => true, send: async (to, subject, text) => { B.mails.push({ to, subject, text, copy: 2 }); } }, siteConfig: () => B.site, clock: () => B.now(),
|
||||
hooks: { claim: async k => { if (B.claims.has(k)) return false; B.claims.add(k); return true; }, excludedPerson: async e => B.optOut.has(e) ? 'unsubscribed' : null } });
|
||||
B.site.tankBatchEmailsPerDay = 5000; at(9, 0 + 24 * 60);
|
||||
for (let i = 0; i < 40; i++) { await Promise.all([B.tb.mailTick(), tb2.mailTick()]); B.advance(60000); }
|
||||
const per = {}; for (const m of sentMail()) per[m.to] = (per[m.to] || 0) + 1;
|
||||
ok(Object.values(per).every(n => n === 1) && ob().every(x => x.status === 'sent' || x.status === 'skipped'), 'two app copies: every email sent exactly once, the queue drains', per);
|
||||
// preview shows the email plan
|
||||
const pv = await B.tb.preview(); ok(pv.emailPlan && pv.emailPlan.perDay === 5000 && typeof pv.emailPlan.daysToClear === 'number', 'preview carries the email plan', pv.emailPlan);
|
||||
}
|
||||
console.log('\n' + passes + ' passed, ' + fails + ' failed'); process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,82 @@
|
||||
// Holding-tank readiness (2026-11-18): the site module against a REAL local network hub (its own temp data dir, throwaway people),
|
||||
// never production. Checks the entry reasons this site derives from its own records, the signed call, the cache, and that the
|
||||
// hub being down leaves the tank list exactly as it was. No mail module is even loaded.
|
||||
// node qa/tank-readiness.test.mjs (HUB_DIR = the network-hub checkout, default ../../network-hub)
|
||||
import { createRequire } from 'module';
|
||||
import fs from 'fs'; import os from 'os'; import path from 'path'; import assert from 'assert';
|
||||
const require = createRequire(import.meta.url);
|
||||
const HUB_DIR = process.env.HUB_DIR || path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '../../../network-hub');
|
||||
const SECRET = 'q'.repeat(40);
|
||||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'hub-rdy-'));
|
||||
process.env.HUB_SITES = JSON.stringify({ iap: { secret: SECRET, seeEmails: true } });
|
||||
process.env.HUB_ADMIN_SECRET = 'z'.repeat(40);
|
||||
delete process.env.DATABASE_URL;
|
||||
|
||||
const hubStore = require(path.join(HUB_DIR, 'lib/store'));
|
||||
const hubPeople = require(path.join(HUB_DIR, 'lib/people'));
|
||||
const hubAct = require(path.join(HUB_DIR, 'lib/activity'));
|
||||
const { start } = require(path.join(HUB_DIR, 'server'));
|
||||
const TR = require('../tankready.js');
|
||||
|
||||
let pass = 0; const ok = (c, m) => { assert.ok(c, m); pass++; console.log(' ok', m); };
|
||||
const DAY = 86400000; const now = Date.now();
|
||||
|
||||
// the hub knows two of the leads: one imported from an old site, one who signed in on LinkSpin yesterday
|
||||
hubPeople.importRows([{ email: 'old@t.test', username: 'oldtimer', joinedAt: now - 500 * DAY }], 'vbb');
|
||||
const live = hubPeople.join({ site: 'iap', email: 'live@t.test', username: 'livewire' }).person;
|
||||
hubAct.record(live.id, 'linkspin', 'signin', now - DAY, now);
|
||||
hubPeople.join({ site: 'iap', email: 'spons@t.test', username: 'sponsorx' });
|
||||
|
||||
const server = await start(0); const port = server.address().port;
|
||||
process.env.HUB_URL = 'http://127.0.0.1:' + port; process.env.HUB_SECRET = SECRET; process.env.HUB_SITE = 'iap'; process.env.HUB_ENABLED = '1';
|
||||
|
||||
// a fake site: accounts, tank waiting list, adoption history, follow records
|
||||
const accts = {
|
||||
'old@t.test': { email: 'old@t.test', username: 'oldtimer', created: now - 3 * DAY, joinedVia: 'hub', joinedRef: 'hub:vbb' },
|
||||
'live@t.test': { email: 'live@t.test', username: 'livewire', created: now - 10 * DAY, joinedVia: 'page', joinedRef: 'viefaucet.com', lastSeen: now - 2 * 3600e3 },
|
||||
'resc@t.test': { email: 'resc@t.test', username: 'rescued1', created: now - 30 * DAY },
|
||||
'dead@t.test': { email: 'dead@t.test', username: 'deadlink', created: now - 30 * DAY },
|
||||
'b4h@t.test': { email: 'b4h@t.test', created: now - 7 * DAY, joinedVia: 'btc4hits', joinedRef: 'btc4hits' },
|
||||
'back@t.test': { email: 'back@t.test', username: 'backagain', created: now - 40 * DAY },
|
||||
'spons@t.test': { email: 'spons@t.test', username: 'sponsorx' }
|
||||
};
|
||||
const waiting = ['old@t.test', 'live@t.test', 'resc@t.test', 'dead@t.test', 'b4h@t.test', 'back@t.test'].map(e => ({ email: e, name: '@' + (accts[e].username || 'x'), joined: accts[e].created, lastSeen: accts[e].lastSeen || 0, wallet: e === 'live@t.test' }));
|
||||
const hist = new Map([
|
||||
['resc@t.test', [{ adopter: 'spons@t.test', ts: now - 4 * DAY, status: 'rescued', closed: null }]],
|
||||
['dead@t.test', [{ adopter: 'dead:gone99', ts: now - 5 * DAY, status: 'rescued', closed: null }]],
|
||||
['back@t.test', [{ adopter: 'spons@t.test', ts: now - 20 * DAY, status: 'rescued' }, { adopter: 'spons@t.test', ts: now - 15 * DAY, status: 'expired', closed: now - 8 * DAY }]]
|
||||
]);
|
||||
let calls = 0;
|
||||
TR.init({ site: 'iap', accounts: { byEmail: async e => accts[e] || null }, tank: { waiting: async () => { calls++; return waiting; }, historyMap: async () => hist }, followGet: () => null });
|
||||
|
||||
console.log('tank readiness: local hub on :' + port);
|
||||
const c = await TR.refresh();
|
||||
ok(c && c.by.size === 6, 'one call returned readiness for all six leads');
|
||||
const get = e => c.by.get(e);
|
||||
ok(get('old@t.test').entry.reason === 'imported' && get('old@t.test').entry.detail.oldSite === 'vbb', 'hub-made account: the hub says imported from ViralBannerBlitz with the old join date');
|
||||
ok(get('live@t.test').entry.reason === 'joined' && get('live@t.test').entry.detail.ref === 'viefaucet.com', 'joined with no sponsor, with the source');
|
||||
ok(get('live@t.test').stage === 'activated' && get('live@t.test').heat.score >= 40, 'wallet linked = Activated, signed in recently = warm or hot (' + get('live@t.test').heat.score + ')');
|
||||
ok(get('live@t.test').last.kind === 'signin' && get('live@t.test').last.site === 'iap', 'last action: the site sign-in 2 hours ago beats the LinkSpin one yesterday');
|
||||
ok(get('resc@t.test').entry.reason === 'rescued' && get('resc@t.test').entry.detail.from === 'sponsorx', 'rescued, naming the sponsor by username');
|
||||
ok(get('dead@t.test').entry.reason === 'sponsor_gone' && !get('dead@t.test').entry.detail.from, 'dead sponsor link: sponsor gone, no name');
|
||||
ok(get('b4h@t.test').entry.reason === 'imported' && get('b4h@t.test').entry.detail.oldSite === 'BTC4Hits', 'BTC4Hits import (not on the hub: the site report alone)');
|
||||
ok(get('back@t.test').entry.reason === 'returned', 'back after an adoption window ended (newest record wins)');
|
||||
ok(get('b4h@t.test').stage === 'new' && get('b4h@t.test').heat.band === 'cold' && get('b4h@t.test').last === null, 'never seen: New, Cold, no activity');
|
||||
const txt = JSON.stringify([...c.by.values()]);
|
||||
ok(!/@t\.test/.test(txt), 'no email in anything the hub sent back');
|
||||
ok(!JSON.stringify(hubStore.all().map(p => p.tankEntry || null)).includes('@'), 'no email stored in the entry facts on the hub');
|
||||
ok(hubPeople.byEmail('live@t.test').tankEntry && hubPeople.byEmail('live@t.test').tankEntry.reason === 'joined', 'the entry fact is recorded on the hub');
|
||||
|
||||
const att = await TR.attach(waiting);
|
||||
ok(att.every(w => w.rd) && calls === 1, 'attach uses the fresh cache, no second call');
|
||||
ok(waiting.every(w => !w.rd), 'the original rows are not changed');
|
||||
|
||||
// the hub goes away: the card shows the rows as before (after the cache is gone)
|
||||
server.close(); TR._reset();
|
||||
const down = await TR.attach(waiting, 1500);
|
||||
ok(down.length === 6 && down.every(w => !w.rd), 'hub down: the same rows, no extras, no error');
|
||||
ok(TR.status().ok === false, 'status says the hub is not answering');
|
||||
process.env.HUB_ENABLED = '0'; TR._reset();
|
||||
ok((await TR.attach(waiting)) === waiting, 'switched off: untouched');
|
||||
console.log('tank readiness: ALL PASSED (' + pass + ')');
|
||||
process.exit(0);
|
||||
@@ -0,0 +1,94 @@
|
||||
// Network Weekend end to end on a local copy (throwaway data, JSON store, no DB, no mail key): the /weekend page, the Home strip,
|
||||
// the ribbon, /api/promodays, /api/network-deals (from a fake hub that serves the real network-hub deal list at the test time),
|
||||
// and the DownlineHydra builders feed's key check. The test clock is IAP_TEST_NOW (server) + window.__NW_NOW (pages).
|
||||
// node qa/weekend.e2e.mjs (needs ../../network-hub/lib/deals.js beside this repo, playwright from qa-tester)
|
||||
import http from 'node:http'; import { spawn } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path';
|
||||
import { createRequire } from 'node:module'; import assert from 'node:assert';
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1')), '..');
|
||||
const { chromium } = require(process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright');
|
||||
const deals = require(path.resolve(ROOT, '../../network-hub/lib/deals.js'));
|
||||
const KEY = 'k'.repeat(48);
|
||||
const out = []; const ok = m => { out.push('ok ' + m); console.log('ok', m); };
|
||||
|
||||
async function run(nowIso, port) {
|
||||
const hub = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(deals.current(Date.parse(nowIso)))); });
|
||||
await new Promise(r => hub.listen(0, r));
|
||||
const data = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-nw-')); fs.mkdirSync(path.join(data, 'uploads'));
|
||||
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: data, ADMIN_PASSWORD: 'localtest', IAP_TEST_NOW: nowIso, HUB_URL: 'http://127.0.0.1:' + hub.address().port, WEEKEND_BUNDLE_KEY: KEY, NODE_ENV: 'test', DATABASE_URL: '', DOCSTORE_URL: '' });
|
||||
const srv = spawn(process.execPath, ['server.js'], { cwd: ROOT, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let log = ''; srv.stdout.on('data', d => { log += d; }); srv.stderr.on('data', d => { log += d; });
|
||||
const base = 'http://127.0.0.1:' + port;
|
||||
try {
|
||||
for (let i = 0; i < 40; i++) { try { if ((await fetch(base + '/api/config')).ok) break; } catch (e) {} await new Promise(r => setTimeout(r, 500)); }
|
||||
return await fn(base, nowIso);
|
||||
} finally { srv.kill(); hub.close(); fs.rmSync(data, { recursive: true, force: true }); if (process.env.QA_LOG) console.log(log.slice(-3000)); }
|
||||
}
|
||||
let fn;
|
||||
(async () => {
|
||||
const browser = await chromium.launch();
|
||||
const page = async (base, nowIso, p) => {
|
||||
const ctx = await browser.newContext(); const pg = await ctx.newPage(); const errs = [];
|
||||
pg.on('pageerror', e => errs.push(e.message)); pg.on('console', m => { if (m.type() === 'error' && /Content Security Policy|Refused/.test(m.text())) errs.push(m.text()); });
|
||||
await pg.addInitScript(t => { window.__NW_NOW = t; }, Date.parse(nowIso));
|
||||
await pg.goto(base + p, { waitUntil: 'networkidle' }); await pg.waitForTimeout(800);
|
||||
return { pg, ctx, errs };
|
||||
};
|
||||
// 1. Black Friday 09:00 CT
|
||||
fn = async (base, nowIso) => {
|
||||
const v = await (await fetch(base + '/api/promodays')).json();
|
||||
assert.ok(v.live && v.today.name === 'Black Friday' && v.today.pct === 40 && v.lsCode === 'WEEKEND500'); ok('Black Friday /api/promodays live 40%');
|
||||
const f = await (await fetch(base + '/api/friday')).json(); assert.ok(f.live && f.pct === 40 && f.name === 'Black Friday'); ok('/api/friday says Black Friday +40%');
|
||||
const d = await (await fetch(base + '/api/network-deals')).json(); assert.strictEqual(d.self, 'iap'); assert.ok(d.events[0] && d.events[0].deals.length > 5); ok('/api/network-deals relays the hub');
|
||||
assert.strictEqual((await fetch(base + '/api/network/weekend-builders')).status, 401);
|
||||
assert.strictEqual((await fetch(base + '/api/network/weekend-builders', { headers: { 'X-Weekend-Key': 'x'.repeat(48) } })).status, 401);
|
||||
const b = await fetch(base + '/api/network/weekend-builders', { headers: { 'X-Weekend-Key': KEY } }); assert.strictEqual(b.status, 200);
|
||||
const bj = await b.json(); assert.ok(Array.isArray(bj.builders) && bj.cap === 24 && bj.start === '2026-11-27T06:00:00.000Z'); ok('builders feed: key required, shape right');
|
||||
let { pg, ctx, errs } = await page(base, nowIso, '/weekend');
|
||||
const state = await pg.textContent('#nwState'); assert.match(state, /It is Black Friday\. \+40% bonus ad credits on any \$5\+/); ok('/weekend live state');
|
||||
assert.strictEqual(await pg.locator('.nw-day').count(), 4); assert.ok(await pg.locator('.nw-day.today').count() === 1);
|
||||
assert.ok((await pg.locator('.nw-deal').count()) > 8); ok('/weekend day cards + every network deal');
|
||||
assert.ok(await pg.locator('.nw-ribbon').count() === 1 && /Black Friday/.test(await pg.textContent('.nw-ribbon'))); ok('ribbon on /weekend (no self link)');
|
||||
assert.strictEqual(await pg.locator('.nw-ribbon a').count(), 0);
|
||||
await pg.screenshot({ path: path.join(ROOT, 'qa/out/weekend-live.png'), fullPage: true });
|
||||
assert.deepStrictEqual(errs, []); await ctx.close();
|
||||
({ pg, ctx, errs } = await page(base, nowIso, '/'));
|
||||
assert.match(await pg.textContent('#nwStrip'), /Network Weekend: it\u2019s Black Friday\. \+40%/); ok('Home strip live');
|
||||
assert.ok(/Ad credits buy advertising, not income\./.test(await pg.textContent('#nwStrip')));
|
||||
assert.strictEqual(await pg.locator('.nw-ribbon').count(), 1); ok('ribbon on Home');
|
||||
await pg.screenshot({ path: path.join(ROOT, 'qa/out/weekend-home.png') });
|
||||
assert.deepStrictEqual(errs, []); await ctx.close();
|
||||
};
|
||||
await run('2026-11-27T15:00:00Z', 8811);
|
||||
// 2. Wed 11-18 (today-ish): nothing shows anywhere
|
||||
fn = async (base, nowIso) => {
|
||||
const v = await (await fetch(base + '/api/promodays')).json(); assert.ok(!v.live && !v.published && v.days.length === 0); ok('before Thursday: /api/promodays publishes nothing');
|
||||
const f = await (await fetch(base + '/api/friday')).json(); assert.strictEqual(f.pct, 20); ok('a normal week: Friday +20%');
|
||||
let { pg, ctx, errs } = await page(base, nowIso, '/weekend');
|
||||
assert.match(await pg.textContent('#nwState'), /Coming/); assert.strictEqual(await pg.locator('.nw-ribbon').count(), 0); assert.strictEqual(await pg.locator('.nw-deal').count(), 0); ok('/weekend dormant, no ribbon');
|
||||
assert.deepStrictEqual(errs, []); await ctx.close();
|
||||
({ pg, ctx, errs } = await page(base, nowIso, '/'));
|
||||
assert.strictEqual(await pg.locator('#nwStrip:not([hidden])').count(), 0); assert.strictEqual(await pg.locator('.nw-ribbon').count(), 0); ok('Home: no strip, no ribbon');
|
||||
assert.deepStrictEqual(errs, []); await ctx.close();
|
||||
};
|
||||
await run('2026-11-18T15:00:00Z', 8812);
|
||||
// 3. Thanksgiving 20:00 CT: heads-up strip, no ribbon yet; Cyber Monday; Tuesday off
|
||||
fn = async (base, nowIso) => {
|
||||
let { pg, ctx } = await page(base, nowIso, '/');
|
||||
assert.match(await pg.textContent('#nwStrip'), /starts at midnight Central/); assert.strictEqual(await pg.locator('.nw-ribbon').count(), 0); ok('Thanksgiving: heads-up strip, ribbon not yet');
|
||||
await ctx.close();
|
||||
};
|
||||
await run('2026-11-27T02:00:00Z', 8813);
|
||||
fn = async (base, nowIso) => {
|
||||
const v = await (await fetch(base + '/api/promodays')).json(); assert.ok(v.live && v.today.pct === 30 && v.today.minUsd === 20); ok('Cyber Monday +30% $20+');
|
||||
const { pg, ctx } = await page(base, nowIso, '/weekend'); assert.match(await pg.textContent('.nw-ribbon'), /Cyber Monday[\s\S]*\+30% bonus ad credits on any \$20\+/); ok('ribbon Cyber Monday text'); await ctx.close();
|
||||
};
|
||||
await run('2026-11-30T20:00:00Z', 8814);
|
||||
fn = async (base, nowIso) => {
|
||||
const v = await (await fetch(base + '/api/promodays')).json(); assert.ok(!v.live && v.today === null && v.passBonusLive === false); ok('Tue 12-01: weekend off; no pass days shown while sovTiers is off');
|
||||
const { pg, ctx } = await page(base, nowIso, '/'); assert.strictEqual(await pg.locator('.nw-ribbon').count(), 0); assert.strictEqual(await pg.locator('#nwStrip:not([hidden])').count(), 0); ok('Tue: no ribbon, no strip'); await ctx.close();
|
||||
};
|
||||
await run('2026-12-01T15:00:00Z', 8815);
|
||||
await browser.close();
|
||||
console.log('ALL OK weekend e2e (' + out.length + ' checks)');
|
||||
})().catch(e => { console.error('FAIL', e.message); process.exit(1); });
|
||||
@@ -404,6 +404,22 @@ async function setGoal(email, goal) {
|
||||
}
|
||||
function badgesOf(email) { return getRec(String(email || '').toLowerCase()).then(r => (r && cfg().on) ? Object.keys(r.badges || {}) : []).catch(() => []); }
|
||||
|
||||
// ---- one member's standing, read-only (holding tank batches, tankbatch.js 2026-11-15) ---------------------------------
|
||||
// streak + both engines this cycle (a settled COPY: a passed grace reads as it will be stored), and the biggest package of each
|
||||
// site the streak has seen (refuels and Pit Stops keep cents; LinkSpin packages reach InstantAdPay only through this record)
|
||||
async function standing(email, now) {
|
||||
email = String(email || '').toLowerCase(); if (!email) return null;
|
||||
const rec0 = await getRec(email); if (!rec0) return null;
|
||||
const rec = JSON.parse(JSON.stringify(rec0)); settle(rec, ctDay(now || Date.now()));
|
||||
const max = { iap: 0, linkspin: 0 };
|
||||
for (const cy of [rec.cycle].concat(rec.history || [])) {
|
||||
if (!cy) continue;
|
||||
for (const grp of [cy.sites || {}, cy.pit || {}]) for (const s of ['iap', 'linkspin']) if (grp[s]) max[s] = Math.max(max[s], Number(grp[s].cents) || 0);
|
||||
}
|
||||
return { active: !!rec.active && (rec.streak || 0) >= 1, streak: rec.active ? (rec.streak || 0) : 0, both: !!(rec.active && rec.cycle && rec.cycle.both),
|
||||
lastDay: rec.lastDay || null, dueDay: rec.dueDay || null, maxCents: max };
|
||||
}
|
||||
|
||||
// ---- admin ------------------------------------------------------------------------------------------
|
||||
async function stats() {
|
||||
const c = cfg(); const recs = await allRecs(); const rows = await outRows();
|
||||
@@ -414,5 +430,5 @@ async function stats() {
|
||||
recent: rows.slice(0, 40).map(r => ({ ref: r.ref, site: r.site, email: r.email, kind: r.kind === 'grant' ? r.payload.kind : 'reminder:' + r.payload.remind, credits: r.payload.credits || 0, status: r.status, at: r.created })) };
|
||||
}
|
||||
|
||||
module.exports = { setGoal, init, cfg, record, roundup, weekOf, feedLine, onIapPurchase, decide, settle, blank, view, streakLine, badgesOf, outbox, ack, drainLocal, tick, stats, reminderCopy,
|
||||
module.exports = { standing, setGoal, init, cfg, record, roundup, weekOf, feedLine, onIapPurchase, decide, settle, blank, view, streakLine, badgesOf, outbox, ack, drainLocal, tick, stats, reminderCopy,
|
||||
_days: { ctDay, addDays, diffDays, label, ctHour }, SINGLE, BOTH };
|
||||
|
||||
@@ -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=20261115nr"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
h += '</div><script src="/assets/common.js?v=20261117nw"></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 };
|
||||
|
||||
@@ -31,10 +31,12 @@ const drip = require('./drip');
|
||||
const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set)
|
||||
let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ }
|
||||
const chatbot = require('./chatbot');
|
||||
const netkb = require('./netkb'); // the shared network KB on the hub; suggest() for the Help pane (2026-11-16)
|
||||
const kb = require('./kb'); // the assistant's knowledge base: Admin > Knowledge base, seeded from chatbot.js CANNED + kb-seed.js (2026-10-20)
|
||||
const fraud = require('./fraud');
|
||||
const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats
|
||||
const tank = require('./tank');
|
||||
const tankready = require('./tankready'); // holding-tank readiness from the network hub (2026-11-18): entry reason, stage, heat, last action on the tank cards. No mail.
|
||||
const walletnudge = require('./walletnudge');
|
||||
const milestone = require('./milestone'); // players with POL waiting in the games and no wallet (2026-10-07) // holding tank: unsponsored free members, adoptions, pay-it-forward
|
||||
const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails
|
||||
@@ -55,9 +57,12 @@ const lssync = require('./lssync');
|
||||
const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23)
|
||||
const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07)
|
||||
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
|
||||
const tankbatch = require('./tankbatch'); // holding tank batches (2026-11-15): switch tankBatches, default off
|
||||
const siteinvite = require('./siteinvite'); // sponsor invite emails for other network sites (Video App Income, Marty approved 2026-11-20): signed eligible / send, needs SITE_INVITE_SECRET
|
||||
const draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET)
|
||||
const loginClock = require('./loginadclock'); // login ads on a clock, not only at sign-in (Marty 2026-11-15): see loginadclock.js
|
||||
const erase = require('./erase'); // member erase (2026-11-15, LS-1021): POST /api/admin/erase + the hub's member.erased event
|
||||
const adwriter = require('./hubadwriter'); // the network AI ad writer, asked through the hub (2026-11-17): text-ad campaigns
|
||||
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)
|
||||
@@ -111,6 +116,7 @@ const leaderboard = require('./leaderboard');
|
||||
const toolkit = require('./toolkit');
|
||||
const badge = require('./badge'); // achievement badge image drawn on the server with ffmpeg (2026-09-16)
|
||||
const friday = require('./friday');
|
||||
const promodays = require('./promodays'); // Network Weekend 2026 (Black Friday to Cyber Monday): date-to-percent bonus days, bundles, pass days
|
||||
const prohibited = require('./prohibited'); // prohibited-content policy shared with LinkSpin (2026-10-30 link-farm incident)
|
||||
const spamscan = require('./spamscan'); // daily link-farm scan + quarantine rule, byte-for-byte copy on LinkSpin
|
||||
const starter = require('./starter'); // member welcome offer from the games (2026-10-05)
|
||||
@@ -133,6 +139,7 @@ const TRAFFIC_PAGES = new Set(['/chasing-unicorns', '/', '/ledger', '/contract',
|
||||
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 netdeals = require('./netdeals'); // Network Weekend ribbon: date-gated deal list from the hub (2026-11-17)
|
||||
const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY)
|
||||
|
||||
const PORT = Number(process.env.PORT || 3000);
|
||||
@@ -210,6 +217,45 @@ function loadOpenTokens() {
|
||||
}
|
||||
const gauntletTokens = persistedMap('gauntlet'); // email -> welcome-tour token (server-clock dwell floor)
|
||||
const videoTokens = persistedMap('video'); // email -> watch-to-earn video token (server-clock watch floor)
|
||||
// One watch-to-earn video for a member, and the completion of it (2026-11-22). Shared by the member area (/api/my/videos,
|
||||
// /api/my/videowatch) and the signed partner calls (/api/partner/watch/*, Social Tube), so the daily cap, the server-clock
|
||||
// watch floor, once-a-day-per-video, the advertiser charge and the viewer credit are one piece of code wherever the video plays.
|
||||
async function videoNextFor(email, orientation, g) {
|
||||
const status = await ads.videoStatus(email);
|
||||
if (status.left <= 0) return { ad: null, status };
|
||||
const ad = await ads.serveVideo(Object.assign({ excludeEmail: email, orientation }, g)); // never your own video
|
||||
if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13)
|
||||
let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: email, orientation, ignoreSeen: true }, g))); } catch (e) {}
|
||||
// this surface is empty but the other one may not be: the Watch tab holds the landscape
|
||||
// videos and Shorts holds the portrait ones, and they share one daily cap, so a member
|
||||
// who runs the tab dry still has clips waiting (Marty, 2026-09-22)
|
||||
let otherFormat = null;
|
||||
if (status.left > 0 && (orientation === 'landscape' || orientation === 'portrait')) {
|
||||
const alt = orientation === 'landscape' ? 'portrait' : 'landscape';
|
||||
try { if (await ads.serveVideo(Object.assign({ excludeEmail: email, orientation: alt }, g))) otherFormat = alt === 'portrait' ? 'shorts' : 'watch'; } catch (e) {}
|
||||
}
|
||||
return { ad: null, status, allWatched, otherFormat };
|
||||
}
|
||||
const token = crypto.randomBytes(16).toString('hex');
|
||||
videoTokens.set(email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs });
|
||||
return { ad, token, status };
|
||||
}
|
||||
async function videoDoneFor(email, tokenIn, where) { // -> { code, body }; where = '' or a short place name for the credit line (' on Social Tube')
|
||||
const t = videoTokens.get(email);
|
||||
if (!t || t.token !== String(tokenIn || '')) return { code: 400, body: { error: 'That video is no longer open. Load the next one.' } };
|
||||
const age = Date.now() - t.ts;
|
||||
if (age < t.secs * 1000 - 600) return { code: 400, body: { error: 'Watch the full video first.' } };
|
||||
if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(email); return { code: 400, body: { error: 'That watch went stale. Load a fresh video.' } }; }
|
||||
videoTokens.delete(email); // single use
|
||||
if (await ads.hasWatchedVideoToday(email, t.id)) // once-per-day-per-video: no double earning
|
||||
return { code: 200, body: { ok: true, credited: 0, status: await ads.videoStatus(email), already: true } };
|
||||
const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry
|
||||
if (!tier) return { code: 200, body: { ok: true, credited: 0, status: await ads.videoStatus(email), gone: true } };
|
||||
await ads.addEarned(email, tier.reward, { log: { kind: 'earn', note: 'Watched a video' + (where || '') + ' (' + tier.secs + 's)' } });
|
||||
await ads.markVideoSeen(email, t.id);
|
||||
const status = await ads.recordVideoWatch(email);
|
||||
return { code: 200, body: { ok: true, credited: tier.reward, status } };
|
||||
}
|
||||
const faucetHits = new Map(); // address -> last faucet ts (rehearsal test-POL faucet rate limit)
|
||||
const visitTokens = persistedMap('visit'); // email -> verified-visit token (dwell + captcha floor)
|
||||
// walk the referral chain upward via sponsorRef (code/username/member id)
|
||||
@@ -602,6 +648,7 @@ async function boot() {
|
||||
Promise.all([friday.onEvent(ev).catch(e => { console.error('friday bonus', e.message); return null; }), gamepass.onEvent(ev).then(r => { if (r && r.stackPro && r.email) stackProMark(r.email).catch(() => {}); return r; }).catch(e => { console.error('gamepass order', e.message); return null; })])
|
||||
.then(([bonus, gp]) => fridayPassPerk(ev, bonus, gp)).catch(e => console.error('friday pass perk', e.message));
|
||||
wednesday.onEvent(ev).catch(e => console.error('wednesday bonus', e.message));
|
||||
promodays.onEvent(ev).catch(e => console.error('promo days', e.message)); // Sat-Mon bonus (Fridays: friday.js) + weekend bundle notices
|
||||
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)
|
||||
@@ -613,7 +660,8 @@ async function boot() {
|
||||
// only (the admin portal is never shared); an account that is not here yet, or is still a waiting LinkSpin/BTC4Hits account,
|
||||
// gets the normal email-code sign-in with the email filled in, so every new-account check (anti-fraud, sponsor) runs as before.
|
||||
networksso.init({ self: 'iap', peer: 'linkspin', peerBase: LS_BASE, isProd: IS_PROD, dataDir: DATA_DIR, db, defaultPath: '/my',
|
||||
wallets: { bannerline: BL_BASE, vbb: VBB_BASE, viraladblitz: VAB_BASE, downlinehydra: DH_BASE, fivex: FIVEX_BASE }, // Downline Banners members are wallets: vouch for the wallet they signed in with, else the account's linked one
|
||||
wallets: { bannerline: BL_BASE, vbb: VBB_BASE, viraladblitz: VAB_BASE, downlinehydra: DH_BASE, fivex: FIVEX_BASE }, // Downline Banners members are wallets: vouch for the wallet they signed in with, else the account's linked one; every other hub sign-in site comes from the hub (2026-11-17)
|
||||
walletPath: '/my#wallet', // a site that needs a wallet, and none linked yet: the Wallet tab first, then back (2026-11-17)
|
||||
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;
|
||||
@@ -642,7 +690,7 @@ async function boot() {
|
||||
messages.init({ dataDir: DATA_DIR });
|
||||
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 })) }; },
|
||||
chatbot.init({ dataDir: DATA_DIR, chain, weekend: { fact: () => promodays.chatFact(), answer: m => promodays.chatAnswer(m) }, 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, 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);
|
||||
@@ -661,7 +709,9 @@ async function boot() {
|
||||
sendPhoto: (c, jpeg, cap, th) => telegramSendPhoto(c, jpeg, cap, th) });
|
||||
fridaybank.init({ db });
|
||||
starter.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts });
|
||||
friday.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts, mailer, drip, marks,
|
||||
promodays.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts, marks,
|
||||
notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; const html = '<p>' + String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/(https:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); } });
|
||||
friday.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts, mailer, drip, marks, promodays,
|
||||
telegram: 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); },
|
||||
notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; const html = '<p>' + String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/(https:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); } });
|
||||
// Campaign refill notices: an advertiser is told when an ad is nearly out and when it has stopped,
|
||||
@@ -734,6 +784,7 @@ 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 });
|
||||
tankready.init({ site: 'iap', accounts, tank, followGet: e => followStore.get(e) }); // read-only: sends this site's facts, keeps the hub's answer for the tank cards
|
||||
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
|
||||
// network hub rule 3 (2026-11-14, only with HUB_ENABLED): the hub's sponsor comes first for alignment, and nobody it reports
|
||||
@@ -742,6 +793,7 @@ async function boot() {
|
||||
networkHeld: hubsync.enabled() ? accts => hubsync.heldAmong(accts) : null, networkLocked: hubsync.enabled() ? email => hubsync.lockedAnywhere(email) : null,
|
||||
isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em),
|
||||
isDraftPick: id => draftpartner.isDraftPick(id), // a 5xYourTeam pick's adoption: draftpartner.js owns its 3-day window
|
||||
isBatchPick: id => tankbatch.isBatchPick(id), // a holding tank batch adoption: tankbatch.js owns its follow-up window
|
||||
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
|
||||
assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text),
|
||||
// switch-on-payouts reminders after an assignment (2026-10-27): one send per key across both app copies (deploy overlap),
|
||||
@@ -760,10 +812,10 @@ async function boot() {
|
||||
reload: { 'legacy.json': () => legacy.reload(), 'legacy-grants.json': () => legacy.reload() },
|
||||
forget: [email => loginClock.forget(String(email || '').toLowerCase()), email => lssync._forget(email), email => { if (hubsync.enabled()) hubsync._forgetHeld(email); }] });
|
||||
// network hub (hubsync.js): nothing at all happens here unless HUB_ENABLED is on; the LinkSpin sync above runs either way
|
||||
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain, erase }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
|
||||
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain, erase, endSessions: (email, wallet) => auth.endSessions(email, wallet) }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
|
||||
// 5xYourTeam draft picks (draftpartner.js, 2026-11-15): the routes answer 503 until DRAFT_PARTNER_SECRET is set; the pool stays empty
|
||||
// and nobody can be drafted while the hub is off (DRAFT_ALLOW_NO_HUB=1 is for local tests only, refused in production)
|
||||
await draftpartner.init({ dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
|
||||
await draftpartner.init({ maxOpen: () => siteConfig().fiveXDraftCap, dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
|
||||
hooks: { hubInfo: email => (hubsync.enabled() ? hubsync.hubInfo(email) : null), resolvePerson: q => (hubsync.enabled() ? hubsync.resolvePerson(q) : null), networkOn: () => hubsync.enabled(),
|
||||
excluded: em => fraud.excluded(em), spamEmails: () => (((spamscan.view() || {}).last || {}).candidates || []).map(c => c.email), suggestDomain: d => require('./emailcheck').suggestDomain(d) } }).catch(e => console.error('draftpartner init', e.message));
|
||||
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
|
||||
@@ -793,6 +845,7 @@ async function boot() {
|
||||
blog.init({ dataDir: DATA_DIR, extraPages: () => bixpay.live() ? ['/bixpay'] : [] });
|
||||
adminMember.init({ accounts, ads, chain, tank, legacy, promos, messages, dataDir: DATA_DIR });
|
||||
gamepass.init({ dataDir: DATA_DIR, siteConfig, accounts, marks, isProd: IS_PROD, persistedMap, polUsd: polUsdLive,
|
||||
bonusDays: (tier, ts) => promodays.passBonusDays(tier, ts), // Network Weekend tier pass bonus days (2026-11-17)
|
||||
blockTime: async n => { const blk = await chain.rpc('eth_getBlockByNumber', ['0x' + Number(n).toString(16), false]); return blk && blk.timestamp ? parseInt(blk.timestamp, 16) : 0; }, // a pass order is fulfilled only by a purchase mined after it
|
||||
telegram: async html => { const sc = siteConfig(); const chat = String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(); if (!sc.telegramBotToken || !chat) return false; await telegramSend(chat, html, sc.telegramGamesTopicId || null); return true; },
|
||||
notify: (to, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice') }); // before loadOpenTokens: its maps must exist to be restored
|
||||
@@ -847,6 +900,26 @@ async function boot() {
|
||||
geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message));
|
||||
setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily
|
||||
setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window
|
||||
// holding tank batches (tankbatch.js, 2026-11-15): hourly follow-up + a round while tankBatches is on; the feed card goes where the other sale cards go
|
||||
{ let spamC = { at: 0, set: new Set() }; const spamSet = () => { if (Date.now() - spamC.at > 60000) { try { spamC = { at: Date.now(), set: new Set((((spamscan.view() || {}).last || {}).candidates || []).map(c => String(c.email || '').toLowerCase())) }; } catch (e) { spamC = { at: Date.now(), set: new Set() }; } } return spamC.set; };
|
||||
await tankbatch.init({ dataDir: DATA_DIR, db, accounts, chain, tank, refuel, messages, mailer, siteConfig,
|
||||
hooks: { excluded: em => fraud.excluded(em), companyId: () => Number(siteConfig().defaultSponsorId) || 1, claim: key => marks.claim(key), toast: ev => pushFeed(ev),
|
||||
excludedPerson: async em => { if (spamSet().has(em)) return 'spam scan'; const d = String(em).split('@')[1] || ''; const fix = require('./emailcheck').suggestDomain(d); if (fix && fix !== d) return 'mistyped email domain'; if (erase.isErased(em)) return 'erased'; if (await drip.isUnsubscribed(em).catch(() => false)) return 'unsubscribed from email'; return null; },
|
||||
notify: async (email, subject, text) => { const html = '<p>' + String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/(https:\/\/[^\s)]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [email], subject, html, 'notice'); },
|
||||
// the round's announcement in the new members area (CTB group General: no thread id), with the ladder card image; a caption over
|
||||
// Telegram's 1,024 characters goes as one text post instead
|
||||
announce: async html => { const sc = siteConfig(); const chat = String(sc.tankBatchAnnounceChatId || sc.telegramEchoChatId || '').trim(); if (!sc.telegramBotToken || !chat) return; const topic = String(sc.tankBatchAnnounceTopicId || '').trim() || null;
|
||||
let jpeg = null; try { jpeg = fs.readFileSync(path.join(__dirname, 'public', 'banners', 'holding-tank-leads-1200x675.jpg')); } catch (e) {}
|
||||
if (jpeg && html.length <= 1024 && await telegramSendPhoto(chat, jpeg, html, topic)) return; await telegramSend(chat, html, topic); },
|
||||
feed: async (who, what, level) => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; const clean = t => String(t || '').replace(/[<>&]/g, ''); await telegramSend(sc.telegramEchoChatId, '\u{1F91D} <b>InstantAdPay</b> · <b>' + clean(who) + '</b> just received ' + clean(what) + ' from the holding tank (' + clean(level) + ' level)', sc.telegramEchoTopicId); } } }).catch(e => console.error('tankbatch init', e.message)); }
|
||||
// sponsor invite emails for other network sites (siteinvite.js, 2026-11-21): the same never-mail list the tank batches use
|
||||
{ let spamC = { at: 0, set: new Set() }; const spamSet = () => { if (Date.now() - spamC.at > 60000) { try { spamC = { at: Date.now(), set: new Set((((spamscan.view() || {}).last || {}).candidates || []).map(c => String(c.email || '').toLowerCase())) }; } catch (e) { spamC = { at: Date.now(), set: new Set() }; } } return spamC.set; };
|
||||
await siteinvite.init({ dataDir: DATA_DIR, accounts, mailer, siteConfig, prohibited,
|
||||
hooks: { excluded: em => fraud.excluded(em), suggestDomain: d => require('./emailcheck').suggestDomain(d), erased: em => erase.isErased(em),
|
||||
excludedPerson: async em => { if (spamSet().has(em)) return 'spam scan'; const d = String(em).split('@')[1] || ''; const fix = require('./emailcheck').suggestDomain(d); if (fix && fix !== d) return 'mistyped email domain'; if (erase.isErased(em)) return 'erased'; if (await drip.isUnsubscribed(em).catch(() => false)) return 'unsubscribed from email'; return null; } } }).catch(e => console.error('siteinvite init', e.message)); }
|
||||
setTimeout(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 4 * 60 * 1000); // past the deploy overlap window
|
||||
setInterval(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 60 * 60 * 1000);
|
||||
setInterval(() => tankbatch.mailTick().catch(e => console.error('tankbatch mail', e.message)), 60 * 1000); // throttled batch emails (tankBatchEmailsPerDay, 8 AM to 8 PM CT) + spaced Telegram cards
|
||||
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);
|
||||
@@ -921,6 +994,9 @@ function siteConfig() {
|
||||
leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover)
|
||||
loginAdEveryHours: 3, // login ad: shown again on the next member page once the last finished view is this many hours old (Marty 2026-11-15)
|
||||
tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11
|
||||
fiveXDraftCap: 10, // 5xYourTeam draft: open picks one coach may hold, its own cap (Marty 2026-11-15), never shared with tankAdoptCap or batches
|
||||
...siteinvite.DEFAULTS, // sponsor invite emails for other network sites (siteinvite.js): siteInvitesPaused '1' stops them; per-sender and all-senders daily caps
|
||||
...tankbatch.DEFAULTS, // holding tank batches (tankbatch.js, Marty 2026-11-15): master switch tankBatches '0'; every number of the ladder, cadence and follow-up
|
||||
legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand>
|
||||
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
|
||||
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
|
||||
@@ -960,7 +1036,7 @@ const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': '
|
||||
'.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2',
|
||||
'.gif': 'image/gif', '.webm': 'video/webm', '.vtt': 'text/vtt; charset=utf-8', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' };
|
||||
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com https://linkspin.app https://downlinebanners.com https://viralbannerblitz.com https://viraladblitz.com https://downlinehydra.com https://5xyourteam.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:";
|
||||
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com https://linkspin.app https://downlinebanners.com https://viralbannerblitz.com https://viraladblitz.com https://viraladsource.com https://yourprogrambuilder.com https://downlinehydra.com https://5xyourteam.com https://videoappincome.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 || {});
|
||||
@@ -1668,6 +1744,7 @@ async function tankAdminAlert(text) {
|
||||
// who linked a wallet, run the safety net, and tell the shared payments topic once per member who became ready
|
||||
async function tankReadyTick() {
|
||||
const r = await tank.readyTick();
|
||||
tankready.refresh().catch(() => {}); // readiness: send the hub this site's entry facts and refresh the card cache (no mail, no sponsor change)
|
||||
if (r.aligned || r.assigned.length || r.held || r.fresh.length || (r.reminders || []).length) console.log('tank ready tick', JSON.stringify({ fresh: r.fresh.length, aligned: r.aligned, assigned: r.assigned.length, held: r.held, payReminders: (r.reminders || []).map(x => x.stage) }));
|
||||
const sc = siteConfig();
|
||||
if (!r.fresh.length || !sc.telegramBotToken || !sc.telegramEchoChatId) return r;
|
||||
@@ -1730,8 +1807,12 @@ const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json');
|
||||
function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } }
|
||||
// Post a member's badge to the payments topic + General ONCE ever (the same card and caption as an unlock). Used by the
|
||||
// automatic Friday Game Pass perk; returns how many chats it reached (0 when already posted or not configured).
|
||||
// Stack POL Pro given by a grant or comp never posts its badge to Telegram; Pro from the member's own purchase still does (Marty 2026-11-21:
|
||||
// "If someone purchases one, that's fine but it's just too noisy when all the grants are popping up"). The admin re-post button still works.
|
||||
function badgeSilent(email, key) { if (key !== 'stackpro') return false; let r = null; try { r = gamepass.stackPro(email); } catch (e) {} return !!(r && (r.via === 'comp' || r.note)); }
|
||||
async function postBadgeOnce(email, key, note) {
|
||||
const e = String(email || '').toLowerCase(); const log = badgeLog(); const mine = log[e] || {}; if (mine[key] || !BADGE_META[key]) return 0;
|
||||
if (badgeSilent(e, key)) { mine[key] = { ts: Date.now(), sent: 0, silent: true }; log[e] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (er) {} return 0; }
|
||||
const a = await accounts.byEmail(e); if (!a) return 0;
|
||||
const who = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'a member');
|
||||
const link = a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com';
|
||||
@@ -2377,13 +2458,19 @@ const server = http.createServer(async (req, res) => {
|
||||
// share-link domains (instantadpay.link active since 2026-11-04; ctbgo.com and mylinehq.com still answer): /<ref> goes to that member's join page, anything else to the same path
|
||||
// here. 302 (not 301) so links never get pinned in caches; the query (?v= angle, ?promo=) rides along.
|
||||
{ const sh = String(req.headers.host || '').toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '');
|
||||
if (SHARE_HOSTS.includes(sh)) {
|
||||
const ref = /^\/([A-Za-z0-9_]{1,40})\/?$/.exec(p);
|
||||
// answered in place on a share host, never redirected (2026-11-17, mail links moved to the share domain): the
|
||||
// unsubscribe link (RFC 8058 one-click is a POST, which a 302 would break) and the banner images mail and promo tools embed
|
||||
if (SHARE_HOSTS.includes(sh) && !(p === '/unsubscribe' || ((req.method === 'GET' || req.method === 'HEAD') && /^\/banners\/[\w.-]+$/.test(p)))) {
|
||||
// a public page name is that page, not a username (2026-11-17: the Network Weekend email links instantadpay.link/weekend;
|
||||
// leaderboard/blog/presentation added the same day when every email's links moved here; no member holds those names)
|
||||
const ref = /^\/(weekend|friday|wednesday|ledger|refuel|facts|games|support|my|join|leaderboard|blog|presentation|partners|launch|plays|bixpay|wall)\/?$/.test(p) ? null : /^\/([A-Za-z0-9_]{1,40})\/?$/.exec(p);
|
||||
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;
|
||||
if (req.method === 'GET' && await networksso.page(req, res, u)) return; // network hub: daily activity ping + the hub sign-in push (2026-11-15)
|
||||
// every /go/<site> and every ?return=<site> link goes to networksso (2026-11-17): it knows the hub's sign-in sites, so a new site no longer needs a line here
|
||||
if (req.method === 'GET' && (p.startsWith('/go/') || p.startsWith('/sso/') || p === '/api/sso/status' || u.searchParams.has('return')) && 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') {
|
||||
@@ -2523,6 +2610,15 @@ const server = http.createServer(async (req, res) => {
|
||||
|
||||
// -- public API
|
||||
if (p === '/api/friday' && req.method === 'GET') return json(res, 200, friday.view(), { 'Cache-Control': 'public, max-age=60' });
|
||||
// Network Weekend (2026-11-17): the promo-day view (strip, Overview card, /weekend), the network deal list for the ribbon,
|
||||
// and the $100+ buyers DownlineHydra grants Pro to (X-Weekend-Key = env WEEKEND_BUNDLE_KEY, compared in constant time)
|
||||
if (p === '/api/promodays' && req.method === 'GET') return json(res, 200, promodays.view(), { 'Cache-Control': 'public, max-age=30' });
|
||||
if (p === '/api/network-deals' && req.method === 'GET') return netdeals.handle(req, res, 'iap');
|
||||
if (p === '/api/network/weekend-builders' && req.method === 'GET') {
|
||||
const want = String(process.env.WEEKEND_BUNDLE_KEY || ''), got = String(req.headers['x-weekend-key'] || '');
|
||||
if (want.length < 32 || got.length !== want.length || !crypto.timingSafeEqual(Buffer.from(got), Buffer.from(want))) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, await promodays.builders(), { 'Cache-Control': 'no-store' });
|
||||
}
|
||||
// member welcome offer from the games: public numbers for the game cards, the member's own view, and the 'came from' mark
|
||||
if (p === '/api/starter/public' && req.method === 'GET') return json(res, 200, starter.publicView(), { 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' });
|
||||
if (p === '/api/starter' && (req.method === 'GET' || req.method === 'POST')) {
|
||||
@@ -2548,7 +2644,11 @@ const server = http.createServer(async (req, res) => {
|
||||
const c = chain.getConfig();
|
||||
// public copy of the site settings: never anything that looks like a credential
|
||||
const pubSite = {};
|
||||
for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k) && !/^support/.test(k)) pubSite[k] = v; // support* = help desk internals (Marty's chat id, saved replies)
|
||||
// also never: Telegram chat/topic ids, the link-farm allow list, or any value holding an email address (2026-11-20: spamScanAllow
|
||||
// put seven member emails and telegramAdminChatId in this public answer; only the admin pages use them, through /api/admin/site)
|
||||
const EMAIL = /[^\s@"]+@[^\s@"]+\.[a-z]{2,}/i;
|
||||
for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k) && !/^support/.test(k)
|
||||
&& !/^telegram|ChatId$|TopicId$|^spamScan/i.test(k) && !EMAIL.test(typeof v === 'string' ? v : JSON.stringify(v))) pubSite[k] = v; // support* = help desk internals (Marty's chat id, saved replies)
|
||||
return json(res, 200, Object.assign({ contract: c.contract, chainId: c.chainId,
|
||||
chainName: c.chainName, explorer: c.explorer, rpc: c.rpcs[0],
|
||||
emailAuth: mailer.hasKey() || !IS_PROD }, pubSite));
|
||||
@@ -3042,7 +3142,7 @@ const server = http.createServer(async (req, res) => {
|
||||
const lr = await accounts.linkWallet(s.email, r.address);
|
||||
if (lr.error) return json(res, 400, lr);
|
||||
await auth.updateSession(s.token, { address: r.address, memberId });
|
||||
return json(res, 200, { ok: true, linked: true, address: r.address, memberId, next: parseCookies(req)['iap.return'] === 'polhunter' ? '/api/my/polhunter' : null });
|
||||
return json(res, 200, { ok: true, linked: true, address: r.address, memberId, next: parseCookies(req)['iap.return'] === 'polhunter' ? '/api/my/polhunter' : networksso.afterWallet(req), backTo: parseCookies(req)['iap.return'] === 'polhunter' ? 'PolHunter' : networksso.backName(req) }); // a network site waiting on this wallet: straight back there (2026-11-17)
|
||||
}
|
||||
const acct = await accounts.byAddress(r.address);
|
||||
if (!acct && await accounts.positionOwner(r.address))
|
||||
@@ -3051,6 +3151,15 @@ const server = http.createServer(async (req, res) => {
|
||||
return json(res, 200, { ok: true, address: r.address, memberId },
|
||||
{ 'Set-Cookie': auth.sessionCookie(token) });
|
||||
}
|
||||
// "Sign out everywhere" (Marty 2026-11-15): the network hub ends every hub sign-in of this member and tells every hooked site;
|
||||
// every session of this member here ends too. Same-origin POST only (SameSite=Lax session cookie).
|
||||
if (p === '/api/auth/logout-everywhere' && req.method === 'POST') {
|
||||
const s = await auth.fromRequest(req).catch(() => null);
|
||||
let hub = { ok: false };
|
||||
if (s) { hub = await networksso.signOutEverywhere(s); try { await auth.endSessions(s.email || null, s.address || null); } catch (e) {} }
|
||||
try { await auth.logout(req); } catch (e) {}
|
||||
return json(res, 200, { ok: true, everywhere: !!hub.ok }, { 'Set-Cookie': [auth.clearCookie(), networksso.offCookie()] }); // no silent network sign-in here for 12 h
|
||||
}
|
||||
if (p === '/api/auth/logout' && req.method === 'POST') {
|
||||
await auth.logout(req);
|
||||
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
|
||||
@@ -3085,7 +3194,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, nssoBack: networksso.pendingBack(req), gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['turkeydrop', 'polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'polminer', 'warpwares', 'shardsofvalor', 'forum'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : (networksso.pendingBack(req) ? 'nsso' : null), sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
|
||||
const out = { signedIn: true, nssoBack: networksso.pendingBack(req), nssoBackTo: networksso.backName(req), gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['turkeydrop', 'polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'polminer', 'warpwares', 'shardsofvalor', 'forum'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : (networksso.pendingBack(req) ? 'nsso' : null), sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
|
||||
address: s.address || (acct && acct.address) || null, memberId,
|
||||
username: (acct && acct.username) || null, theme: (acct && acct.theme) || null,
|
||||
inviteAsk: !memberId && acct ? tank.inviteAsk(acct) : null, // the Who invited you card (2026-11-07)
|
||||
@@ -3571,10 +3680,12 @@ const server = http.createServer(async (req, res) => {
|
||||
for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i;
|
||||
return json(res, 200, { suggest: pick });
|
||||
}
|
||||
if (p === '/api/my/tank/feed' && req.method === 'GET') { const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); return json(res, 200, await tankbatch.myView(s.email)); } // How to get fed leads (off with tankBatches)
|
||||
if (p === '/api/my/tank' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
return json(res, 200, await tank.view(s.email));
|
||||
const v = await tank.view(s.email); v.waiting = await tankready.attach(v.waiting); // readiness (hub): entry, stage, heat, last action
|
||||
return json(res, 200, v);
|
||||
}
|
||||
// -- achievement badge -> Telegram (payments topic + the main group), once per badge per member.
|
||||
// The browser composes the personalised image (canvas, same as Share) and posts it here.
|
||||
@@ -3590,6 +3701,8 @@ const server = http.createServer(async (req, res) => {
|
||||
if (!held.includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' });
|
||||
const log = badgeLog(); const mine = log[s.email] || {};
|
||||
if (mine[key]) return json(res, 200, { ok: true, already: true });
|
||||
// granted Stack POL Pro is silent (see badgeSilent): logged so the page stops asking, nothing sent
|
||||
if (badgeSilent(s.email, key) && u.searchParams.get('manual') !== '1') { mine[key] = { ts: Date.now(), sent: 0, silent: true }; log[s.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {} return json(res, 200, { ok: true, already: true, silent: true }); }
|
||||
// manual re-posts (the button) are Marty's only; members' badges go out automatically on unlock
|
||||
if (u.searchParams.get('manual') === '1' && s.email !== ADMIN_EMAIL) return json(res, 403, { error: 'Badges post automatically when they unlock.' });
|
||||
const a = await accounts.byEmail(s.email);
|
||||
@@ -3863,13 +3976,59 @@ const server = http.createServer(async (req, res) => {
|
||||
const r = await draftpartner.handle(op, sg.body);
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
// -- sponsor invite emails for other network sites (siteinvite.js, 2026-11-21): signed partner calls, SITE_INVITE_SECRET as X-Invite-Ts + X-Invite-Sig
|
||||
if (p.startsWith('/api/partner/invite/') && 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 = siteinvite.verify(req.headers, raw); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
||||
const op = p.slice('/api/partner/invite/'.length);
|
||||
if (!['eligible', 'send', 'code'].includes(op)) return json(res, 404, { error: 'unknown op' });
|
||||
const r = await siteinvite.handle(op, sg.body);
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
// -- watch-to-earn videos played on another network site (Social Tube, Marty 2026-11-22: "a member watching on Social Tube earns the same
|
||||
// InstantAdPay credits"). The other site only shows the video: this app picks it, times it on its own clock, charges the advertiser and
|
||||
// credits the viewer through videoNextFor / videoDoneFor, so every rule and the daily cap are shared with the member area.
|
||||
// POST /api/partner/watch/next { site:'socialtube', email, ip?, orientation? } -> { ad, token, status } | { ad:null, status, ... }
|
||||
// POST /api/partner/watch/done { site:'socialtube', email, token } -> { ok, credited, status, already?, gone? }
|
||||
// Signature: X-Watch-Ts (ms) + X-Watch-Sig = hex HMAC-SHA256(SITE_INVITE_SECRET, 'watch.v1.' + ts + '\n' + raw body), 5 minutes.
|
||||
if (p.startsWith('/api/partner/watch/') && req.method === 'POST') {
|
||||
const secret = String(process.env.SITE_INVITE_SECRET || '').trim(); if (secret.length < 32) return json(res, 503, { error: 'not configured' });
|
||||
let raw; try { raw = (await readRaw(req, 16384)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
|
||||
const ts = String(req.headers['x-watch-ts'] || ''), sig = String(req.headers['x-watch-sig'] || '');
|
||||
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return json(res, 401, { error: 'stale' });
|
||||
if (!gpSigOk(crypto.createHmac('sha256', secret).update('watch.v1.' + ts + '\n' + raw).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' });
|
||||
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
|
||||
if (!b || String(b.site) !== 'socialtube') return json(res, 400, { error: 'unknown site' });
|
||||
const who = await gpResolve(0, b.email); if (!who) return json(res, 404, { error: 'no such member' });
|
||||
if (fraud.isSuspended(who.email)) return json(res, 403, { error: 'suspended' });
|
||||
const op = p.slice('/api/partner/watch/'.length);
|
||||
if (op === 'next') {
|
||||
const cc = geo.countryOf(String(b.ip || '').slice(0, 60) || 'unknown'), ori = ['portrait', 'landscape'].includes(b.orientation) ? b.orientation : '';
|
||||
const r = await videoNextFor(who.email, ori, { cc, tier: geo.tierOf(cc, siteConfig()) });
|
||||
if (r.ad) r.ad = Object.assign({}, r.ad, { ctaUrl: 'https://instantadpay.com' + r.ad.ctaUrl, videoUrl: /^\//.test(r.ad.videoUrl || '') ? 'https://instantadpay.com' + r.ad.videoUrl : r.ad.videoUrl });
|
||||
return json(res, 200, r);
|
||||
}
|
||||
if (op === 'done') { const vd = await videoDoneFor(who.email, b.token, ' on Social Tube'); return json(res, vd.code, vd.body); }
|
||||
return json(res, 404, { error: 'unknown op' });
|
||||
}
|
||||
if (p === '/api/admin/site-invites' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await siteinvite.adminView()); }
|
||||
if (p === '/api/admin/site-invites/sample' && req.method === 'POST') { // one sample of the invite email to the admin address only
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); if (!ADMIN_EMAIL) return json(res, 400, { error: 'no admin email set' });
|
||||
return json(res, 200, await siteinvite.sample(ADMIN_EMAIL, 'videoappincome'));
|
||||
}
|
||||
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/batches/preview' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.preview()); } // read-only: no writes, no mail
|
||||
if (p === '/api/admin/tank/batches/mail' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.mailView()); } // queued, sent today, next send time
|
||||
if (p === '/api/admin/tank/batches/mail' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await tankbatch.setPaused(!!(b && b.paused))); } // pause / resume
|
||||
if (p === '/api/admin/tank/batches/round' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.round()); } // run a round now (the normal path; nothing while tankBatches is off)
|
||||
if (p === '/api/admin/tank/batches' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.adminView()); }
|
||||
if (p === '/api/admin/tank' && req.method === 'GET') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, await tank.adminView());
|
||||
const v = await tank.adminView(); v.waiting = await tankready.attach(v.waiting); v.readiness = Object.assign(tankready.status(), { counts: tankready.counts() });
|
||||
return json(res, 200, v);
|
||||
}
|
||||
// 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
|
||||
@@ -4751,7 +4910,7 @@ const server = http.createServer(async (req, res) => {
|
||||
return json(res, 200, Object.assign({ ok: true, memberId: r.memberId, username: r.acct.username || null, wallet: r.acct.address || null, suspended: fraud.isSuspended(r.email),
|
||||
pass: gamepass.flag(r.email, now), caps: gamepass.capsFor(r.email, now, game), gamePassEnabled: gamepass.cfg().enabled }, game === 'shardsofvalor' ? gamepass.heroClaim(r.email) : {}));
|
||||
}
|
||||
if ((p === '/api/partner/polgrant' || p === '/api/partner/polgrant/void' || p === '/api/partner/tournament/paid') && req.method === 'POST') {
|
||||
if ((p === '/api/partner/polgrant' || p === '/api/partner/polgrant/void' || p === '/api/partner/tournament/paid' || p === '/api/partner/credits') && req.method === 'POST') {
|
||||
let raw; try { raw = (await readRaw(req, 16384)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
|
||||
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
|
||||
const game = String(b.game || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error });
|
||||
@@ -4761,6 +4920,22 @@ const server = http.createServer(async (req, res) => {
|
||||
if (p === '/api/partner/tournament/paid') { const r = gamepass.markPaid(b.week, b.place, b.tx, game); if (!r.error) console.log('gamepass prize paid', b.week, '#' + b.place, 'by', game, String(b.tx || '').slice(0, 14)); return json(res, r.error ? 400 : 200, r); }
|
||||
const r = await gpResolve(b.memberId, b.email); if (!r) return json(res, 404, { error: 'no such member' });
|
||||
const now = gpDevNow(b.devDay);
|
||||
// PolHunter tour stops (Marty 2026-11-17): a free member's repeat find pays a few earned-grade ad credits instead of POL. PolHunter
|
||||
// decides the amount (its settings tourStopCredits / tourStopCreditsDailyMax); here a hard ceiling per call (siteConfig partnerCreditsMax,
|
||||
// default 25), once per ref across every instance (marks), with a credit-activity line. A retry of the same ref answers repeat: true.
|
||||
if (p === '/api/partner/credits') {
|
||||
if (game !== 'polhunter') return json(res, 400, { error: 'not enabled for ' + game });
|
||||
const n = Math.round(Number(b.credits) || 0), max = Math.max(0, Math.round(Number(siteConfig().partnerCreditsMax) || 25)), ref = String(b.ref || '');
|
||||
if (!(n > 0) || n > max) return json(res, 400, { error: 'credits must be 1 to ' + max });
|
||||
if (!/^[A-Za-z0-9:_-]{3,60}$/.test(ref)) return json(res, 400, { error: 'bad ref' });
|
||||
const who = await gpResolve(b.memberId, b.email); if (!who) return json(res, 404, { error: 'no such member' });
|
||||
if (fraud.isSuspended(who.email)) return json(res, 403, { error: 'suspended' });
|
||||
if (!(await marks.claim('pcred:' + game + ':' + ref))) return json(res, 200, { ok: true, repeat: true, credits: n });
|
||||
try { await ads.addEarned(who.email, n, { log: { kind: 'earn', note: String(b.note || 'PolHunter tour stop').replace(/[<>]/g, '').slice(0, 120), ref: ('ph' + ref).slice(0, 40) } }); }
|
||||
catch (e) { console.error('partner credits', ref, e.message); return json(res, 500, { error: 'grant failed' }); }
|
||||
console.log('partner credits', game, ref, n, who.email.replace(/^(.).*(@.*)$/, '$1***$2'));
|
||||
return json(res, 200, { ok: true, credits: n });
|
||||
}
|
||||
if (p.endsWith('/void')) return json(res, 200, gamepass.voidGrant({ game, ref: b.ref }));
|
||||
if (fraud.isSuspended(r.email)) return json(res, 200, { allowed: 0, deferred: 0, pass: false, day: gamepass.dayKey(now), suspended: true }); // nothing is recorded: a cleared account replays the ref later
|
||||
const out = gamepass.grant({ email: r.email, game, kind: b.kind, pol: b.pol, ref: b.ref, now });
|
||||
@@ -4825,7 +5000,8 @@ const server = http.createServer(async (req, res) => {
|
||||
const a = await accounts.byMemberId(id); if (!a || !a.email) return json(res, 404, { error: 'No account for member #' + id });
|
||||
const r = gamepass.grantStackProForPackage(a.email, tx, Number(ev.priceCents), id, b.note);
|
||||
try { await stackProMark(a.email); } catch (e) {}
|
||||
let posted = 0; try { posted = await postBadgeOnce(a.email, 'stackpro'); } catch (e) { console.error('stackpro badge', e.message); }
|
||||
// quiet: no badge post (2026-11-20, Marty: Pro for every member whose $10+ package came before Pro launched; 141 at once would flood Telegram)
|
||||
let posted = 0; if (!b.quiet && !r.already) try { posted = await postBadgeOnce(a.email, 'stackpro'); } catch (e) { console.error('stackpro badge', e.message); }
|
||||
return json(res, 200, Object.assign({ username: a.username, posted }, r));
|
||||
}
|
||||
if (p === '/api/admin/heroes/stats' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, gamepass.heroStats()); }
|
||||
@@ -5013,6 +5189,17 @@ const server = http.createServer(async (req, res) => {
|
||||
const r = await tickets.create({ source: 'form', email: s.email, name: (a && a.username) || '', username: a && a.username, subject: b.subject, category: b.category, body: b.body, attachments: b.attachments });
|
||||
return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, ref: r.ticket.ref });
|
||||
}
|
||||
// help desk suggestions (2026-11-16): while a signed-in member types a new ticket, the closest help answers (the hub's semantic
|
||||
// match over the network KB, BM25 here when the hub is slow or down). KB entries only, never another member's ticket. Never blocks sending.
|
||||
if (p === '/api/my/support/suggest' && req.method === 'POST') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
const b = await readBody(req);
|
||||
if (supportFlood('sg:' + String(s.email).toLowerCase(), 240, 3600000)) return json(res, 200, { items: [], via: 'limited' });
|
||||
const text = (String(b.subject || '').slice(0, 200) + '. ' + String(b.body || '').slice(0, 800)).trim();
|
||||
try { return json(res, 200, await netkb.suggest(text, { own: await kb.own(), fallback: q => kb.context(q, 4) })); }
|
||||
catch (e) { console.error('support suggest', e.message); return json(res, 200, { items: [], via: 'error' }); }
|
||||
}
|
||||
m = /^\/api\/my\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p);
|
||||
if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) {
|
||||
const s = await auth.fromRequest(req);
|
||||
@@ -5379,44 +5566,15 @@ const server = http.createServer(async (req, res) => {
|
||||
if (p === '/api/my/videos' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
const status = await ads.videoStatus(s.email);
|
||||
if (status.left <= 0) return json(res, 200, { ad: null, status });
|
||||
const orientation = String(u.searchParams.get('orientation') || ''); // 'portrait' = Shorts reel, 'landscape' = Watch videos tab
|
||||
const ad = await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation }, viewerGeo(req))); // never your own video
|
||||
if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13)
|
||||
let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation, ignoreSeen: true }, viewerGeo(req)))); } catch (e) {}
|
||||
// this surface is empty but the other one may not be: the Watch tab holds the landscape
|
||||
// videos and Shorts holds the portrait ones, and they share one daily cap, so a member
|
||||
// who runs the tab dry still has clips waiting (Marty, 2026-09-22)
|
||||
let otherFormat = null;
|
||||
if (status.left > 0 && (orientation === 'landscape' || orientation === 'portrait')) {
|
||||
const alt = orientation === 'landscape' ? 'portrait' : 'landscape';
|
||||
try { if (await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation: alt }, viewerGeo(req)))) otherFormat = alt === 'portrait' ? 'shorts' : 'watch'; } catch (e) {}
|
||||
}
|
||||
return json(res, 200, { ad: null, status, allWatched, otherFormat });
|
||||
}
|
||||
const token = crypto.randomBytes(16).toString('hex');
|
||||
videoTokens.set(s.email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs });
|
||||
return json(res, 200, { ad, token, status });
|
||||
return json(res, 200, await videoNextFor(s.email, orientation, viewerGeo(req)));
|
||||
}
|
||||
if (p === '/api/my/videowatch' && req.method === 'POST') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
const b = await readBody(req);
|
||||
const t = videoTokens.get(s.email);
|
||||
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That video is no longer open. Load the next one.' });
|
||||
const age = Date.now() - t.ts;
|
||||
if (age < t.secs * 1000 - 600) return json(res, 400, { error: 'Watch the full video first.' });
|
||||
if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(s.email); return json(res, 400, { error: 'That watch went stale. Load a fresh video.' }); }
|
||||
videoTokens.delete(s.email); // single use
|
||||
if (await ads.hasWatchedVideoToday(s.email, t.id)) // once-per-day-per-video: no double earning
|
||||
return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), already: true });
|
||||
const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry
|
||||
if (!tier) return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), gone: true });
|
||||
await ads.addEarned(s.email, tier.reward, { log: { kind: 'earn', note: 'Watched a video (' + tier.secs + 's)' } });
|
||||
await ads.markVideoSeen(s.email, t.id);
|
||||
const status = await ads.recordVideoWatch(s.email);
|
||||
return json(res, 200, { ok: true, credited: tier.reward, status });
|
||||
const vd = await videoDoneFor(s.email, b.token, '');
|
||||
return json(res, vd.code, vd.body);
|
||||
}
|
||||
// -- verified visits: view a member's site (new tab) for the dwell, pass a
|
||||
// human check, and it counts as one guaranteed unique visit for the pack
|
||||
@@ -5480,6 +5638,27 @@ const server = http.createServer(async (req, res) => {
|
||||
if (req.method === 'POST' || !!so.pro[un] !== !!pv.pro || pv.pro) { so.updatedAt = Date.now(); const tmp = F + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(so)); fs.renameSync(tmp, F); }
|
||||
return json(res, 200, { on: so.users[un] !== false, username: un, url: 'https://stackpol.com/' + un, wallet: !!(acct && acct.address), pro: pv, buy });
|
||||
}
|
||||
// the same switch read and written from stackpol.com/my (Marty 2026-11-19, My Stack POL): signed by Stack POL with STACKPOL_SWITCH_KEY
|
||||
// (X-Stack-Ts + X-Stack-Sig = HMAC(ts + "\n" + body)), for the member signed in there (email from their hub token). Only the page switch.
|
||||
if (p === '/api/partner/stackpol/switch' && req.method === 'POST') {
|
||||
const key = String(process.env.STACKPOL_SWITCH_KEY || '');
|
||||
if (key.length < 32) return json(res, 503, { error: 'not configured' });
|
||||
let raw; try { raw = (await readRaw(req, 4096)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too large' }); }
|
||||
const ts = String(req.headers['x-stack-ts'] || ''); const sig = String(req.headers['x-stack-sig'] || '');
|
||||
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return json(res, 401, { error: 'auth' });
|
||||
const want = crypto.createHmac('sha256', key).update(ts + '\n' + raw).digest('hex');
|
||||
if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) return json(res, 401, { error: 'auth' });
|
||||
let b = {}; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
|
||||
const acct = await accounts.byEmail(String(b.email || '').trim().toLowerCase());
|
||||
if (!acct) return json(res, 404, { error: 'no account' });
|
||||
const un = String(acct.username || '').toLowerCase();
|
||||
if (!un) return json(res, 409, { error: 'no username' });
|
||||
const F = path.join(DATA_DIR, 'stack-optin.json'); let so = { users: {} }; try { so = JSON.parse(fs.readFileSync(F, 'utf8')); if (!so.users) so.users = {}; } catch (e) {}
|
||||
if (typeof b.on === 'boolean') so.users[un] = b.on;
|
||||
so.pro = so.pro || {}; const pv = gamepass.stackProView(acct.email); if (pv.pro) so.pro[un] = true; else delete so.pro[un];
|
||||
if (typeof b.on === 'boolean' || !!so.pro[un] !== !!pv.pro || pv.pro) { so.updatedAt = Date.now(); const tmp = F + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(so)); fs.renameSync(tmp, F); }
|
||||
return json(res, 200, { on: so.users[un] !== false, username: un, pro: !!pv.pro });
|
||||
}
|
||||
if (p === '/api/my/inbox' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
@@ -5542,7 +5721,8 @@ const server = http.createServer(async (req, res) => {
|
||||
if (t === 'login') { // on the member's clock (loginadclock.js); back = a network sign-in hop to finish when the countdown ends (2026-11-15)
|
||||
const s = await auth.fromRequest(req).catch(() => null); const lk = loginClock.keyOf(s);
|
||||
const back = networksso.pendingBack(req) ? '/sso/resume' : null;
|
||||
if (lk && !(await loginClock.due(lk))) return json(res, 200, { ad: null, notDue: true, back });
|
||||
if (!lk) return json(res, 200, { ad: null, signedOut: true }); // signed out (bots, probes, link previews) never draws or counts a login ad (2026-11-15); the games' kit has its own route
|
||||
if (!(await loginClock.due(lk))) return json(res, 200, { ad: null, notDue: true, back });
|
||||
const ad = await loginAdFor(req, 'dashboard');
|
||||
if (ad && lk) await loginClock.served(lk);
|
||||
return json(res, 200, { ad, back });
|
||||
@@ -5561,6 +5741,10 @@ const server = http.createServer(async (req, res) => {
|
||||
let own = false, cm = null;
|
||||
try { cm = await ads.campaignById(m[1]); } catch (e) {}
|
||||
try { const s = cm && await auth.fromRequest(req); if (s && s.email) own = !!(cm.owner && String(cm.owner).toLowerCase() === String(s.email).toLowerCase()); } catch (e) {}
|
||||
// only a running campaign redirects off-site (2026-11-17, Spamhaus DBL): an ended, paused, archived or flagged campaign's
|
||||
// click link used to keep forwarding to its target forever (e.g. #164 -> a URL shortener), a ready-made instantadpay.com
|
||||
// redirector for anyone. Those now land on the home page, uncounted. The owner can still open their own link.
|
||||
if (!own && (!cm || cm.status !== 'active')) { res.writeHead(302, baseHeaders({ Location: '/', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' })); return res.end(); }
|
||||
const target = own ? await ads.targetOf(m[1]) : await ads.click(m[1]);
|
||||
if (!target) { res.writeHead(404, baseHeaders()); return res.end(); }
|
||||
if (!own) coach.recordClick(m[1], req.headers.referer); // where the click happened
|
||||
@@ -5682,6 +5866,19 @@ const server = http.createServer(async (req, res) => {
|
||||
out.loginLine = await ads.loginQueueView(s.email); // login-ad slots: open now, the paid line, this member's places + estimated starts
|
||||
return json(res, 200, out);
|
||||
}
|
||||
// the AI ad writer (Marty 2026-11-17: "do it on the other sites too"): the hub reads the member's target page and suggests 3
|
||||
// text ads (headline 60, ad text 140) written only from it. Nothing is created here: the member picks one, edits it, creates the campaign.
|
||||
if (p === '/api/my/adwriter' && (req.method === 'GET' || req.method === 'POST')) {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
if (req.method === 'GET') { const w = await adwriter.status(s.email); return json(res, 200, { on: !!w.on, daily: w.daily || 0, left: w.left }); }
|
||||
if (!(await adwriter.enabled())) return json(res, 503, { error: 'The ad writer is switched off right now. You can still write your ad yourself.' });
|
||||
if (supportFlood('aiw:' + clientIp(req), 12, 3600000)) return json(res, 429, { error: 'Too many ad writes from this connection this hour. Try again later, or write your ad yourself.' });
|
||||
const b = await readBody(req);
|
||||
const r = await adwriter.write(s.email, String((b && b.url) || '').trim().slice(0, 600), { headline: 60, line: 140 });
|
||||
if (r.error) return json(res, r.status || 400, { error: r.error, code: r.code, left: r.left });
|
||||
return json(res, 200, { ok: true, options: r.options, url: r.url, cached: r.cached, left: r.left });
|
||||
}
|
||||
if (p === '/api/my/campaigns' && req.method === 'POST') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
@@ -6354,7 +6551,7 @@ const server = http.createServer(async (req, res) => {
|
||||
+ '<style>.bp{max-width:560px;text-align:center;padding:40px 16px 60px}.bp img{width:100%;max-width:520px;border-radius:18px;border:1px solid var(--line);box-shadow:0 20px 60px rgba(0,0,0,.45)}.bp h1{font-size:clamp(24px,5vw,34px);margin:22px 0 8px}.bp p{color:var(--muted);max-width:44ch;margin:0 auto 20px}</style></head>'
|
||||
+ '<body><div class="wrap bp"><img src="' + img + '" alt="' + esc(label) + ' badge for @' + esc(un) + '"><h1>@' + esc(un) + ' unlocked <em>' + label + '</em></h1><p>' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On InstantAdPay every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.</p>'
|
||||
+ '<a class="btn" href="/join/' + esc(un) + '">Join @' + esc(un) + '\u2019s line free</a><p class="small" style="margin-top:26px">Advertising with a performance referral program. Not an investment; no income is guaranteed.</p></div>'
|
||||
+ '<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
|
||||
+ '<script src="/assets/common.js?v=20261117nw"></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);
|
||||
}
|
||||
@@ -6386,6 +6583,7 @@ const server = http.createServer(async (req, res) => {
|
||||
if (p === '/wallets') return sendFile(res, path.join(PUBLIC_DIR, 'wallets.html'));
|
||||
if (p === '/support' || /^\/support\/t\/[A-Za-z0-9_.-]{20,80}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'support.html')); // help desk (2026-10-16): the form, and the private ticket link
|
||||
if (p === '/friday') return sendFile(res, path.join(PUBLIC_DIR, 'friday.html'));
|
||||
if (p === '/weekend') return sendFile(res, path.join(PUBLIC_DIR, 'weekend.html')); // Network Weekend deals page (2026-11-17)
|
||||
if (p === '/wednesday') return sendFile(res, path.join(PUBLIC_DIR, 'wednesday.html'));
|
||||
if (p === '/conversion-tracking') return sendFile(res, path.join(PUBLIC_DIR, 'conversion-tracking.html')); // how to set up the conversion pixel, the member guide (2026-10-24)
|
||||
if (p === '/bixpay') { if (!bixpay.live()) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } return sendFile(res, path.join(PUBLIC_DIR, 'bixpay.html')); } // the BixPay card guide (2026-10-29), public once bixpayLive is on
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
'use strict';
|
||||
// Sponsor invite emails sent on behalf of another network site (first and only site: Video App Income).
|
||||
// Marty approved 2026-11-20: directs only, the wording below, "IAP sends it" (the hub cannot send mail; this app already mails
|
||||
// members from an authenticated domain). A sponsor on the other site picks directs and one of their own videos; that site asks
|
||||
// here; this module decides who may be mailed and sends through mailer.send, so the opt-out rule, the unsubscribe link and the
|
||||
// share-domain rewrite all apply (never `transactional`).
|
||||
//
|
||||
// POST /api/partner/invite/eligible { site, sender: { email?, wallet? } }
|
||||
// -> { ok, sender: username, directs: [{ username, state: 'ok' | 'sent' | 'no' }], left: { sender, network }, paused }
|
||||
// POST /api/partner/invite/send { rid, site, sender, items: [{ username, link }], note?, kind? } kind 'promo' = the link is one of the site's own ready-made videos, not one the sender made
|
||||
// -> { ok, results: [{ username, status: 'sent' | <refusal code> }], sent, left }
|
||||
// POST /api/partner/invite/code { site, email, code } -> { ok } | { error, code } (2026-11-21)
|
||||
// the email-check code for the site's network gate: the SITE makes and checks the 6-digit code, this app only mails it
|
||||
// (a requested code is transactional, like a sign-in code). Fixed wording, no links; 5 an hour per address, 2,000 a day in all.
|
||||
// Signature: X-Invite-Ts (ms) + X-Invite-Sig = hex HMAC-SHA256(SITE_INVITE_SECRET, 'invite.v1.' + ts + '\n' + raw body), 5 minutes.
|
||||
//
|
||||
// The rules:
|
||||
// - DIRECTS ONLY: each recipient is checked with accounts.isDownlineOf(sender, recipient, 1) at send time (the directs-only email
|
||||
// rule of 2026-11-12: levels 2 and 3 belong to someone else's direct relationship)
|
||||
// - ONCE EVER per site per recipient: the row in site_invites (unique site + recipient) is the claim, written before the send, so
|
||||
// two copies of the app during a deploy cannot both send. A send that fails removes its row so it can be tried again.
|
||||
// - never to: an account that has never signed in here (waiting / shell accounts), suspended or flagged members, the spam scan's
|
||||
// suspects, erased members, anyone unsubscribed from email, throwaway or mistyped email domains, the sender themself
|
||||
// - caps: siteInvitePerSender a Central day for one sender (default 25), siteInvitePerDay for all senders together (default 200);
|
||||
// siteInvitesPaused '1' stops all sending
|
||||
// - the other site never learns an email address: it gets usernames and a state, nothing else
|
||||
// - the wording is fixed here. The sender may add one short note; it is refused if it has a link or trips the prohibited list.
|
||||
// The video link must be a share page on an allowed host (SITE_INVITE_LINK_HOSTS).
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const db = require('./db');
|
||||
|
||||
const SITES = { videoappincome: { name: 'Video App Income' } };
|
||||
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 DEFAULTS = { siteInvitesPaused: '0', siteInvitePerSender: 25, siteInvitePerDay: 200 };
|
||||
const TZ = 'America/Chicago';
|
||||
const lc = v => String(v || '').trim().toLowerCase();
|
||||
|
||||
let R = null; // { dataDir, accounts, mailer, siteConfig, prohibited, hooks: { excluded(email), excludedPerson(email) -> reason|null }, secret?, linkHosts?, clock?, gapMs? }
|
||||
const clock = () => (R && R.clock ? R.clock() : Date.now());
|
||||
const SECRET = () => String((R && R.secret) || process.env.SITE_INVITE_SECRET || '').trim();
|
||||
const enabled = () => SECRET().length >= 32;
|
||||
const hosts = () => String((R && R.linkHosts) || process.env.SITE_INVITE_LINK_HOSTS || 'clickvidpro.com').split(',').map(lc).filter(Boolean);
|
||||
function cfg() { const sc = (R && R.siteConfig && R.siteConfig()) || {}; const n = (k, lo, hi) => { const v = Math.round(Number(sc[k] == null ? DEFAULTS[k] : sc[k])); return v >= lo && v <= hi ? v : DEFAULTS[k]; };
|
||||
return { paused: String(sc.siteInvitesPaused == null ? DEFAULTS.siteInvitesPaused : sc.siteInvitesPaused) === '1', perSender: n('siteInvitePerSender', 1, 500), perDay: n('siteInvitePerDay', 1, 5000) }; }
|
||||
function dayStart(ts) { const o = {}; for (const p of new Intl.DateTimeFormat('en-US', { timeZone: TZ, hourCycle: 'h23', hour: '2-digit', minute: '2-digit' }).formatToParts(new Date(ts))) o[p.type] = Number(p.value); return ts - (o.hour * 60 + o.minute) * 60000 - (ts % 60000); }
|
||||
|
||||
// ---- storage: MySQL site_invites when DATABASE_URL is set, else a JSON document (local QA) ----
|
||||
const J = {
|
||||
st: null, FILE: () => path.join(R.dataDir, 'site-invites.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 || !Array.isArray(this.st.rows)) this.st = { rows: [] }; return this.st; },
|
||||
save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); },
|
||||
async claim(row) { const s = this.load(); if (s.rows.some(r => r.site === row.site && r.recipient === row.recipient)) return false; s.rows.push(Object.assign({}, row)); this.save(); return true; },
|
||||
async unclaim(site, recipient) { const s = this.load(); s.rows = s.rows.filter(r => !(r.site === site && r.recipient === recipient)); this.save(); },
|
||||
async mark(site, recipient, status) { const r = this.load().rows.find(x => x.site === site && x.recipient === recipient); if (r) { r.status = status; this.save(); } },
|
||||
async sentTo(site, emails) { const set = new Set(emails); return new Set(this.load().rows.filter(r => r.site === site && set.has(r.recipient)).map(r => r.recipient)); },
|
||||
async count(since, sender) { return this.load().rows.filter(r => r.ts >= since && (!sender || r.sender === sender)).length; },
|
||||
async byRid(rid) { return this.load().rows.filter(r => r.rid === rid).map(r => Object.assign({}, r)); },
|
||||
async recent(n) { return this.load().rows.slice(-(n || 100)).reverse().map(r => Object.assign({}, r)); }
|
||||
};
|
||||
const rowP = r => ({ site: r.site, recipient: r.recipient, username: r.username, sender: r.sender, senderName: r.sender_name, link: r.link, rid: r.rid, ts: Number(r.ts), status: r.status });
|
||||
const Q = {
|
||||
async claim(row) { const r = await db.q('INSERT IGNORE INTO site_invites (site,recipient,username,sender,sender_name,link,rid,ts,status) VALUES (?,?,?,?,?,?,?,?,?)', [row.site, row.recipient, row.username, row.sender, row.senderName, row.link, row.rid, row.ts, row.status]); return !!(r && r.affectedRows === 1); },
|
||||
async unclaim(site, recipient) { await db.q('DELETE FROM site_invites WHERE site=? AND recipient=?', [site, recipient]); },
|
||||
async mark(site, recipient, status) { await db.q('UPDATE site_invites SET status=? WHERE site=? AND recipient=?', [status, site, recipient]); },
|
||||
async sentTo(site, emails) { if (!emails.length) return new Set(); const out = new Set(); for (let i = 0; i < emails.length; i += 500) { const part = emails.slice(i, i + 500); for (const r of await db.q('SELECT recipient FROM site_invites WHERE site=? AND recipient IN (' + part.map(() => '?').join(',') + ')', [site].concat(part))) out.add(r.recipient); } return out; },
|
||||
async count(since, sender) { const r = sender ? await db.q('SELECT COUNT(*) n FROM site_invites WHERE ts>=? AND sender=?', [since, sender]) : await db.q('SELECT COUNT(*) n FROM site_invites WHERE ts>=?', [since]); return Number(r[0].n); },
|
||||
async byRid(rid) { return (await db.q('SELECT * FROM site_invites WHERE rid=?', [rid])).map(rowP); },
|
||||
async recent(n) { return (await db.q('SELECT * FROM site_invites ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); }
|
||||
};
|
||||
const S = () => (db.enabled() ? Q : J);
|
||||
async function ensureTables() {
|
||||
if (!db.enabled()) return;
|
||||
await db.q(`CREATE TABLE IF NOT EXISTS site_invites (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY, site VARCHAR(40) NOT NULL, recipient VARCHAR(190) NOT NULL, username VARCHAR(40) NULL, sender VARCHAR(190) NOT NULL, sender_name VARCHAR(40) NULL,
|
||||
link VARCHAR(300) NULL, rid VARCHAR(80) NULL, ts BIGINT NOT NULL, status VARCHAR(16) NOT NULL,
|
||||
UNIQUE KEY once (site, recipient), KEY sender (sender, ts), KEY t (ts), KEY rid (rid)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // sponsor invite emails for other network sites: one row per recipient per site, ever
|
||||
}
|
||||
async function init(opts) { R = opts; J.st = null; await ensureTables(); }
|
||||
|
||||
// ---- signature ----
|
||||
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('invite.v1.' + ts + '\n' + raw).digest('hex'); }
|
||||
function verify(headers, raw) {
|
||||
if (!enabled()) return { status: 503, error: 'site invites not configured' };
|
||||
const ts = String(headers['x-invite-ts'] || ''), sig = String(headers['x-invite-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' }; }
|
||||
}
|
||||
|
||||
// ---- who ----
|
||||
async function senderOf(s) {
|
||||
const A = R.accounts; let a = null;
|
||||
if (s && s.email) a = await A.byEmail(lc(s.email));
|
||||
if (!a && s && /^0x[0-9a-f]{40}$/.test(lc(s.wallet))) { a = await A.byAddress(lc(s.wallet)); if (!a && A.positionByAddress) { const p = await A.positionByAddress(lc(s.wallet)); if (p && p.email) a = await A.byEmail(p.email); } }
|
||||
if (!a || !a.username) return null;
|
||||
if (R.hooks && R.hooks.excluded && R.hooks.excluded(a.email)) return null;
|
||||
return a;
|
||||
}
|
||||
// why this person cannot be mailed, or null. Reasons stay in this app (the other site only sees 'no').
|
||||
async function refusal(a, sender) {
|
||||
if (!a || !a.email || !a.username) return 'no account';
|
||||
const em = lc(a.email);
|
||||
if (em === lc(sender.email)) return 'self';
|
||||
if (R.accounts.isUnclaimedShell && R.accounts.isUnclaimedShell(a)) return 'never signed in';
|
||||
if (!a.lastSeen) return 'never signed in';
|
||||
const d = em.split('@')[1] || ''; if (!d || THROWAWAY.has(d)) return 'throwaway email';
|
||||
if (R.hooks && R.hooks.excluded && R.hooks.excluded(em)) return 'suspended or flagged';
|
||||
if (R.hooks && R.hooks.excludedPerson) { const why = await R.hooks.excludedPerson(em); if (why) return why; }
|
||||
return null;
|
||||
}
|
||||
async function left(sender) { const c = cfg(), since = dayStart(clock()); return { sender: Math.max(0, c.perSender - await S().count(since, lc(sender.email))), network: Math.max(0, c.perDay - await S().count(since)) }; }
|
||||
|
||||
// ---- the email (Marty approved the wording 2026-11-20). Plain text first; the HTML is the same words. ----
|
||||
// kind 'promo' (Marty 2026-11-21): the video is one of the site's own ready-made ones, so the email must not say the sender made it.
|
||||
function compose(site, sponsor, user, link, note, kind) {
|
||||
const promo = kind === 'promo';
|
||||
const P = [
|
||||
'Hi ' + user + ',',
|
||||
"It's " + sponsor + ', your sponsor on InstantAdPay. I\'ve started using a new app in our network called ' + site.name + ', and I wanted you to hear about it from me.',
|
||||
];
|
||||
if (note) P.push(note);
|
||||
P.push('It makes short promo videos from your phone. You paste a link to whatever you promote, and about a minute and a half later you have a finished video with a voice, captions and music. No camera, no editing. Each video gets its own page that shows you who opened it and who tapped your button.',
|
||||
"Your first video is free, so you can see if it's useful before spending anything. After that, videos cost credits, and a $10 pack makes 10 videos.",
|
||||
"I'll be straight with you: I earn a share if you buy credits. That's how the app works for everyone, and you'd earn the same way from people you bring in. Nothing is promised, and plenty of people will just use it for the videos.",
|
||||
(promo ? "Here's a short video that shows how it works: " : "Here's one I made: ") + link,
|
||||
"You're already on my team, so if you join you'll be placed with me automatically. No link needed.",
|
||||
sponsor,
|
||||
"You're getting this because " + sponsor + ' is your sponsor in the Crypto Team Build Network. This is a one-time note sent through the network on their behalf.');
|
||||
const esc = t => String(t).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const html = '<div style="font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:1.55;color:#222;max-width:560px">' + P.map((p, i) => i === P.length - 1 ? '<p style="font-size:12px;color:#888;margin-top:24px">' + esc(p) + '</p>' : '<p>' + esc(p).replace(esc(link), '<a href="' + esc(link) + '">' + esc(link) + '</a>') + '</p>').join('') + '</div>';
|
||||
return { subject: sponsor + (promo ? ' sent you a video' : ' made you a video'), text: P.join('\n\n'), html };
|
||||
}
|
||||
function cleanNote(n) {
|
||||
const note = String(n || '').replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
if (!note) return { note: '' };
|
||||
if (note.length > 400) return { error: 'Keep your note under 400 characters.' };
|
||||
const P = R.prohibited;
|
||||
if (P && P.hasUrl && P.hasUrl(note)) return { error: 'Your note cannot contain a link. The email already carries your video.' };
|
||||
if (P && P.checkText) { const r = P.checkText(note, 'InstantAdPay'); if (r && r.error) return { error: r.error }; }
|
||||
if (/\b(guarantee\w*|risk[ -]?free|passive income|get rich|double your)\b/i.test(note)) return { error: 'Your note cannot promise income or results.' };
|
||||
return { note };
|
||||
}
|
||||
const linkOk = l => { try { const u = new URL(String(l)); return u.protocol === 'https:' && hosts().includes(u.hostname.toLowerCase()) && /^\/p\/[A-Za-z0-9]{4,20}(\/[A-Za-z0-9]{4,20})?$/.test(u.pathname) && !u.search && !u.hash; } catch (e) { return false; } };
|
||||
|
||||
// ---- the two calls ----
|
||||
async function eligible(b) {
|
||||
const site = SITES[lc(b.site)]; if (!site) return { error: 'unknown site', code: 'site' };
|
||||
const sender = await senderOf(b.sender); if (!sender) return { error: 'The sender has no InstantAdPay account with a username.', code: 'sender' };
|
||||
const lv = await R.accounts.downline(sender.email, 1), kids = (lv[0] && lv[0].members) || [];
|
||||
const sent = await S().sentTo(lc(b.site), kids.map(k => lc(k.email))), directs = [];
|
||||
for (const k of kids) { if (!k.username) continue; directs.push({ username: k.username, state: sent.has(lc(k.email)) ? 'sent' : (await refusal(k, sender)) ? 'no' : 'ok' }); }
|
||||
return { ok: true, sender: sender.username, directs, left: await left(sender), paused: cfg().paused };
|
||||
}
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
async function send(b) {
|
||||
const siteId = lc(b.site), site = SITES[siteId]; if (!site) return { error: 'unknown site', code: 'site' };
|
||||
const rid = String(b.rid || ''); if (!/^[A-Za-z0-9_.:-]{8,80}$/.test(rid)) return { error: 'rid needed', code: 'rid' };
|
||||
const before = await S().byRid(rid); if (before.length) return { ok: true, already: true, results: before.map(r => ({ username: r.username, status: r.status })), sent: before.filter(r => r.status === 'sent').length };
|
||||
if (cfg().paused) return { error: 'Invites are paused right now.', code: 'paused' };
|
||||
if (!R.mailer || !R.mailer.hasKey()) return { error: 'Email is not available right now.', code: 'mail' };
|
||||
const sender = await senderOf(b.sender); if (!sender) return { error: 'The sender has no InstantAdPay account with a username.', code: 'sender' };
|
||||
const items = Array.isArray(b.items) ? b.items : []; if (!items.length || items.length > 25) return { error: 'Send 1 to 25 invites at a time.', code: 'count' };
|
||||
const cn = cleanNote(b.note); if (cn.error) return { error: cn.error, code: 'note' };
|
||||
const results = []; let sentN = 0; const seen = new Set();
|
||||
for (const it of items) {
|
||||
const uname = String((it && it.username) || '').trim(), res = { username: uname, status: '' }; results.push(res);
|
||||
if (seen.has(lc(uname))) { res.status = 'duplicate'; continue; } seen.add(lc(uname));
|
||||
if (!linkOk(it && it.link)) { res.status = 'bad link'; continue; }
|
||||
const a = await R.accounts.byUsername(uname); if (!a) { res.status = 'no'; continue; }
|
||||
if (!(await R.accounts.isDownlineOf(sender.email, a.email, 1))) { res.status = 'not your direct'; continue; }
|
||||
if (await refusal(a, sender)) { res.status = 'no'; continue; }
|
||||
const lf = await left(sender); if (lf.sender < 1) { res.status = 'your daily limit'; continue; } if (lf.network < 1) { res.status = 'network daily limit'; continue; }
|
||||
const row = { site: siteId, recipient: lc(a.email), username: a.username, sender: lc(sender.email), senderName: sender.username, link: String(it.link), rid, ts: clock(), status: 'sending' };
|
||||
if (!(await S().claim(row))) { res.status = 'sent before'; continue; }
|
||||
try {
|
||||
const m = compose(site, sender.username, a.username, row.link, cn.note, b.kind === 'promo' ? 'promo' : '');
|
||||
const okSent = await R.mailer.send(a.email, m.subject, m.text, m.html);
|
||||
if (okSent === false) { await S().unclaim(siteId, row.recipient); res.status = 'no'; continue; } // unsubscribed between the check and the send
|
||||
await S().mark(siteId, row.recipient, 'sent'); res.status = 'sent'; sentN++;
|
||||
} catch (e) { console.error('site invite send', e.message); await S().unclaim(siteId, row.recipient).catch(() => {}); res.status = 'failed'; }
|
||||
await sleep(R.gapMs == null ? 400 : R.gapMs);
|
||||
}
|
||||
console.log('site invite', siteId, 'from', sender.username, 'sent', sentN, 'of', items.length);
|
||||
return { ok: true, results, sent: sentN, left: await left(sender) };
|
||||
}
|
||||
// ---- the email-check code a site asks for when a new person gives their email at its network gate ----
|
||||
const codeLog = new Map(); let codeDay = { start: 0, n: 0 };
|
||||
async function code(b) {
|
||||
const site = SITES[lc(b.site)]; if (!site) return { error: 'unknown site', code: 'site' };
|
||||
const em = lc(b.email), c = String(b.code || '');
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(em) || em.length > 190 || !/^\d{6}$/.test(c)) return { error: 'That does not look like an email address.', code: 'email' };
|
||||
const d = em.split('@')[1] || '';
|
||||
if (THROWAWAY.has(d)) return { error: 'Please use your regular email address, not a temporary one.', code: 'email' };
|
||||
if (R.hooks && R.hooks.suggestDomain) { const fix = R.hooks.suggestDomain(d); if (fix && fix !== d) return { error: 'Check the spelling of your email. Did you mean ' + em.split('@')[0] + '@' + fix + '?', code: 'email' }; }
|
||||
if (R.hooks && R.hooks.excluded && R.hooks.excluded(em)) return { error: 'That email cannot be used here.', code: 'email' };
|
||||
if (R.hooks && R.hooks.erased && R.hooks.erased(em)) return { error: 'That email cannot be used here.', code: 'email' };
|
||||
if (!R.mailer || !R.mailer.hasKey()) return { error: 'Email is not available right now.', code: 'mail' };
|
||||
const now = clock(), day = dayStart(now); if (codeDay.start !== day) codeDay = { start: day, n: 0 };
|
||||
const mine = (codeLog.get(em) || []).filter(t => now - t < 3600000);
|
||||
if (mine.length >= 5) return { error: 'Too many codes were sent to that address. Try again in an hour.', code: 'limit' };
|
||||
if (codeDay.n >= 2000) return { error: 'Please try again later.', code: 'limit' };
|
||||
mine.push(now); codeLog.set(em, mine); codeDay.n++; if (codeLog.size > 20000) codeLog.clear();
|
||||
const text = 'Your code is: ' + c + '\n\nEnter it in ' + site.name + ' to confirm your email. It works for 15 minutes. If you did not ask for it, ignore this email.\n\n' + site.name + ' is part of the Crypto Team Build Network. This email was sent by InstantAdPay, the mail service of the network.';
|
||||
try { await R.mailer.send(em, c + ' is your ' + site.name + ' code', text, null, { transactional: true, fromName: site.name }); } catch (e) { console.error('site code mail', e.message); return { error: 'The email could not be sent. Check the address and try again.', code: 'mail' }; }
|
||||
return { ok: true };
|
||||
}
|
||||
async function handle(op, b) { if (op === 'eligible') return eligible(b || {}); if (op === 'send') return send(b || {}); if (op === 'code') return code(b || {}); return { error: 'unknown op' }; }
|
||||
async function adminView() { const since = dayStart(clock()), c = cfg(); return { on: enabled(), paused: c.paused, perSender: c.perSender, perDay: c.perDay, today: await S().count(since), recent: (await S().recent(200)).map(r => ({ site: r.site, to: r.username, from: r.senderName, ts: r.ts, status: r.status, link: r.link })) }; }
|
||||
// one sample to one address, for the owner to read before the feature opens. Not counted, not recorded.
|
||||
async function sample(to, siteId) { const site = SITES[lc(siteId) || 'videoappincome']; if (!site) return { error: 'unknown site' }; const m = compose(site, 'yoursponsor', 'yourname', 'https://' + hosts()[0] + '/p/faceless', ''); await R.mailer.send(to, '[SAMPLE] ' + m.subject, m.text, m.html); return { ok: true, to, subject: m.subject, text: m.text }; }
|
||||
|
||||
module.exports = { init, enabled, verify, sign, handle, adminView, sample, compose, cleanNote, linkOk, DEFAULTS, SITES };
|
||||
@@ -17,13 +17,19 @@ const db = require('./db');
|
||||
const CAP_DEFAULT = 10; let capFn = () => CAP_DEFAULT;
|
||||
const capOpen = () => { const n = Math.round(Number(capFn())); return n >= 1 && n <= 50 ? n : CAP_DEFAULT; };
|
||||
async function holding(open) { const out = []; for (const ad of open || []) { const a = await accounts.byEmail(ad.adoptee); if (!(a && Number(a.memberId) > 0)) out.push(ad); } return out; }
|
||||
// each allowance counts only its own people (Marty 2026-11-15: "5x your team's draft is a different thing altogether"): the member's own
|
||||
// tank button and the 24-hour safety net count plain adoptions; a 5xYourTeam draft pick counts only against the draft's cap; a holding
|
||||
// tank batch (tankbatch.js) only against the batch size. A hook that throws counts the adoption as plain (the conservative side).
|
||||
const pickKind = async id => { try { if (hooks.isDraftPick && await hooks.isDraftPick(id)) return 'draft'; if (hooks.isBatchPick && await hooks.isBatchPick(id)) return 'batch'; } catch (e) {} return 'plain'; };
|
||||
async function holdingOf(open, kind) { const out = []; for (const ad of await holding(open)) if (await pickKind(ad.id) === kind) out.push(ad); return out; }
|
||||
const TTL_MS = 7 * 86400000; // an adoption's window to convert
|
||||
const MAX_ADOPTIONS = 2; // per adoptee, lifetime (dropped adoptions count too, since 2026-09-13)
|
||||
const HOLD_MS = 3 * 24 * 3600 * 1000; // an adoption is a commitment: no releasing someone you picked up less than 3 days ago (Marty, 2026-09-13)
|
||||
// statuses that do not count toward a person's two adoptions: a release record, and the later side of a network race
|
||||
// (both sites adopted the same person within minutes; the earlier adoption won on both, sponsorfollow.js), and a record of a
|
||||
// member naming who invited them (nobody adopted them; nameSponsor below)
|
||||
const NOT_COUNTED = ['released', 'conflict', 'invited'];
|
||||
// 'unreached' (2026-11-15): a holding tank batch person the sponsor never contacted, back in the tank; the sponsor's miss, not theirs
|
||||
const NOT_COUNTED = ['released', 'conflict', 'invited', 'unreached'];
|
||||
const MIN_OWN_BUY_CENTS = 2000; // adopter must have bought a $20+ package themselves
|
||||
const WARN_DAYS = 10; // dormant lead: sponsor warned after this many days without contact
|
||||
const RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old)
|
||||
@@ -57,10 +63,10 @@ const D = {
|
||||
const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'");
|
||||
return rows.map(rowA);
|
||||
},
|
||||
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n); },
|
||||
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited','unreached')", [adoptee]); return Number(r[0].n); },
|
||||
async setStatus(id, status) { await db.q('UPDATE adoptions SET status=?, closed=? WHERE id=?', [status, Date.now(), Number(id)]); },
|
||||
async recent(n) { return (await db.q('SELECT * FROM adoptions ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowA); },
|
||||
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n) > 0; },
|
||||
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited','unreached')", [adoptee]); return Number(r[0].n) > 0; },
|
||||
async all() { return (await db.q('SELECT * FROM adoptions ORDER BY id')).map(rowA); },
|
||||
async mark(lead) { const r = await db.q('SELECT * FROM lead_marks WHERE `lead`=?', [lead]); return r[0] ? { sponsor: r[0].sponsor, contacted: Number(r[0].contacted_ts || 0), warned: Number(r[0].warned_ts || 0) } : null; },
|
||||
async setMark(lead, f) {
|
||||
@@ -135,7 +141,7 @@ async function eligibility(email) {
|
||||
if (!a) return { ok: false, reason: 'Sign in first.' };
|
||||
if (!a.memberId) return { ok: false, reason: 'Switch on payouts and buy your first $20 package to adopt from the tank.' };
|
||||
if (!hasOwnBuy(a.memberId)) return { ok: false, reason: 'Buy your own $20 or more package first. Adopting is for members who have made that move themselves.' };
|
||||
const open = await impl().open(a.email); const held = await holding(open); const cap = capOpen();
|
||||
const open = await impl().open(a.email); const held = await holdingOf(open, 'plain'); const cap = capOpen();
|
||||
if (held.length >= cap) return { ok: false, reason: 'You are already helping ' + held.length + ' people from the holding tank, and ' + cap + ' at one time is the most anyone can hold. A slot opens when one of them switches on payouts, or when their 7-day window ends.', full: true, cap, held: held.length };
|
||||
return { ok: true, account: a, open };
|
||||
}
|
||||
@@ -154,11 +160,25 @@ async function partnerEligibility(email, p) {
|
||||
const payee = await firstOnContract(a);
|
||||
if (!payee) return { ok: false, code: 'no_contract_line', reason: 'Neither you nor anyone above you has switched on payouts on InstantAdPay, so a pick who starts there would land under the company. Switch on payouts on InstantAdPay first (one free transaction).' };
|
||||
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { ok: false, code: 'payout_blocked', reason: 'Your line cannot take new members right now.' };
|
||||
const open = await impl().open(a.email); const held = await holding(open); const cap = Math.min(capOpen(), Number(p.maxOpen) > 0 ? Number(p.maxOpen) : capOpen());
|
||||
if (held.length >= cap) return { ok: false, code: 'full', reason: 'You are already helping ' + held.length + ' people from the holding tank, and ' + cap + ' at one time is the most anyone can hold.', full: true, cap, held: held.length };
|
||||
// the draft's own cap (2026-11-15): only open draft picks count, never the member's plain adoptions or tank batches
|
||||
const open = await impl().open(a.email); const held = await holdingOf(open, 'draft'); const cap = Number(p.maxOpen) > 0 ? Number(p.maxOpen) : 10;
|
||||
if (held.length >= cap) return { ok: false, code: 'full', reason: 'You already have ' + held.length + ' open draft picks, and ' + cap + ' at one time is the most a coach can hold.', full: true, cap, held: held.length };
|
||||
return { ok: true, account: a, open };
|
||||
}
|
||||
|
||||
// a holding tank batch (tankbatch.js, 2026-11-15): tankbatch has already decided the sponsor qualifies (active, own paid package on
|
||||
// InstantAdPay or LinkSpin) and has room in their batch; this is the InstantAdPay side of the same gate as a 5x coach: a real account,
|
||||
// not suspended or flagged, someone on THIS contract in their line, and that line takes payouts (else the person walks up to the company)
|
||||
async function batchEligibility(email) {
|
||||
const a = await accounts.byEmail(email);
|
||||
if (!a) return { ok: false, code: 'no_account', reason: 'No such member.' };
|
||||
const bar = hooks.excluded || hooks.isSuspended; if (bar && bar(a.email)) return { ok: false, code: 'excluded', reason: 'Adoptions are not available on this account.' };
|
||||
const payee = await firstOnContract(a);
|
||||
if (!payee) return { ok: false, code: 'no_contract_line', reason: 'Nobody in this line has switched on payouts on InstantAdPay.' };
|
||||
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { ok: false, code: 'payout_blocked', reason: 'This line cannot take new members right now.' };
|
||||
return { ok: true, account: a };
|
||||
}
|
||||
|
||||
async function view(email) {
|
||||
const e = String(email || '').toLowerCase();
|
||||
const el = await eligibility(e);
|
||||
@@ -175,8 +195,9 @@ async function adopt(adopterEmail, who, note, opts) {
|
||||
// partner = a 5xYourTeam draft pick (draftpartner.js, 2026-11-15): the coach qualifies by a 5x position instead of the $20 buy,
|
||||
// the window is the pick's (3 days, partner.ttlMs), the hub is asked fresh that nobody locked is taken, no reminder mails
|
||||
const partner = (opts && opts.partner) || null;
|
||||
const batch = !!(opts && opts.batch); // a holding tank batch (tankbatch.js): its own allowance, the grace and the two-adoptions rule still apply
|
||||
const e = String(adopterEmail || '').toLowerCase();
|
||||
const el = partner ? await partnerEligibility(e, partner) : await eligibility(e);
|
||||
const el = partner ? await partnerEligibility(e, partner) : batch ? await batchEligibility(e) : await eligibility(e);
|
||||
if (!el.ok) return { error: el.reason, code: el.code || 'not_eligible' };
|
||||
const me = el.account;
|
||||
const key = String(who || '').trim().toLowerCase().replace(/^@/, '');
|
||||
@@ -187,10 +208,10 @@ async function adopt(adopterEmail, who, note, opts) {
|
||||
if (!auto && target.opensAt > clock()) return { error: 'That member joined less than 24 hours ago, so they still have time to tell us who invited them. You can adopt them in ' + leftText(target.opensAt - clock()) + '.', code: 'grace' }; // the safety net is not held by this: it keeps its 24-hour clock from the wallet link
|
||||
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.', code: 'linkspin' };
|
||||
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.', code: 'adopted_twice' }; // the safety net never leaves anyone to the company
|
||||
if ((partner || batch) && await inDownlineOf(target.email, me)) return { error: 'That member is above you in your own line.', code: 'loop' };
|
||||
if (partner) { // never anyone locked on a network contract: asked fresh, a hub that does not answer refuses (the conservative side)
|
||||
const lk = await lockedWhy(target.email);
|
||||
if (lk) return { error: lk === 'locked' ? 'That member is locked to a sponsor on a network contract.' : 'The network record cannot be checked right now. Try again in a few minutes.', code: lk === 'locked' ? 'locked' : 'hub_unknown' };
|
||||
if (await inDownlineOf(target.email, me)) return { error: 'That member is above you in your own line.', code: 'loop' };
|
||||
}
|
||||
const token = me.username || me.code || String(me.memberId);
|
||||
const r = await setSponsor(target.email, token, 'adopt');
|
||||
@@ -201,12 +222,14 @@ async function adopt(adopterEmail, who, note, opts) {
|
||||
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
|
||||
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)
|
||||
if (!partner && !(opts && opts.queueMail)) payTrack(target.email, e, ad.id, auto); // a batch person's reminders start when their queued email goes out (tankbatch.js), so they stay spread too // 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()) {
|
||||
// a holding tank batch (2026-11-15, Marty: "spread the emails out"): the same email, handed to the throttled queue (opts.queueMail)
|
||||
const queueMail = opts && typeof opts.queueMail === 'function' ? opts.queueMail : null;
|
||||
if (queueMail || (mailer && mailer.hasKey())) {
|
||||
try {
|
||||
await mailer.send(target.email, nameOf(me) + ' is now your sponsor on InstantAdPay',
|
||||
await (queueMail ? (to, subject, body) => queueMail({ to, subject, body, adoptionId: ad.id, sponsor: e }) : (to, subject, body) => mailer.send(to, subject, body))(target.email, nameOf(me) + ' is now your sponsor on InstantAdPay',
|
||||
(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) {
|
||||
@@ -255,7 +278,8 @@ async function sweep() {
|
||||
let done = 0, back = 0, kept = 0;
|
||||
for (const ad of await impl().open(null)) {
|
||||
if (ad.expires > now) continue;
|
||||
if (hooks.isDraftPick && await Promise.resolve(hooks.isDraftPick(ad.id)).catch(() => true)) continue; // a 5xYourTeam pick: draftpartner.js owns its 3-day window (started = payouts on, not a wallet)
|
||||
if (hooks.isDraftPick && await Promise.resolve(hooks.isDraftPick(ad.id)).catch(() => true)) continue;
|
||||
if (hooks.isBatchPick && await Promise.resolve(hooks.isBatchPick(ad.id)).catch(() => true)) continue; // a holding tank batch: tankbatch.js owns its follow-up window // a 5xYourTeam pick: draftpartner.js owns its 3-day window (started = payouts on, not a wallet)
|
||||
const a = await accounts.byEmail(ad.adoptee);
|
||||
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
|
||||
if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; }
|
||||
@@ -517,7 +541,7 @@ async function autoAssignRun() {
|
||||
let done = null;
|
||||
for (const c of pool) {
|
||||
if (c.a.email === e) continue;
|
||||
if ((await holding(await impl().open(c.a.email))).length >= capOpen()) continue;
|
||||
if ((await holdingOf(await impl().open(c.a.email), 'plain')).length >= capOpen()) continue;
|
||||
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(c.a.memberId))).catch(() => true)) continue; // no-payout chain: they would fall to the company after all
|
||||
if (await inDownlineOf(e, c.a)) continue;
|
||||
const msg = 'Hi, I am ' + nameOf(c.a) + '. ' + ((a.joinedVia === 'btc4hits' || a.joinedRef === 'btc4hits') ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor and nobody picked you up from the holding tank within 24 hours, so you were matched with me. I will walk you through the first steps whenever you are ready. Reply here.';
|
||||
@@ -718,5 +742,5 @@ async function adminView() {
|
||||
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
|
||||
}
|
||||
|
||||
module.exports = { _ready: { state: () => RS.load(), save: () => RS.save() }, _json: { state: () => J.db, save: () => J.save() } /* member erase (erase.js) */, partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
|
||||
module.exports = { payTrack, batchEligibility, holdingOf, firstOnContract, inDownlineOf, markOf: email => impl().mark(String(email || '').toLowerCase()), _ready: { state: () => RS.load(), save: () => RS.save() }, _json: { state: () => J.db, save: () => J.save() } /* member erase (erase.js) */, partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
|
||||
init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
|
||||
|
||||
@@ -0,0 +1,444 @@
|
||||
'use strict';
|
||||
// Holding tank batches (Marty 2026-11-15: "let's auto-assign 10 at a time if they've got a paid package of $20 or $25, depending on
|
||||
// which platform it was. If they fueled their engines or they've bought higher packages, let's raise that batch up to be like 20 or
|
||||
// 25 at a time and keep climbing up (because I want those people in the holding tank to get people that are active paying sponsors)").
|
||||
//
|
||||
// THE RULES (every number is a site setting, see DEFAULTS)
|
||||
// eligible sponsor signed in within tankBatchActiveDays (7) and holds their own paid package: $20+ on InstantAdPay (a chain
|
||||
// Purchase by their member number or a linked position) or $25+ on LinkSpin (known here through the refuel
|
||||
// streak record, the only place LinkSpin packages reach InstantAdPay); not the company, not suspended or flagged,
|
||||
// someone on this contract in their line and that line takes payouts (tank.batchEligibility)
|
||||
// batch size Paid 10. Fueled 20: a counted refuel streak is active, or a higher package ($50+ on either site). Twin Engine
|
||||
// 25: both engines refueled this cycle, or the top package (the highest package on the live InstantAdPay
|
||||
// catalog, $500 Elite today; LinkSpin $500 Network). Then +5 for every further consecutive refuel month, up to 50.
|
||||
// "at a time" a sponsor holds at most one batch size of batch people who have not switched on payouts; a person who
|
||||
// switches on payouts frees their place at once
|
||||
// cadence every tankBatchEveryDays (2) per sponsor a fresh batch tops them back up to their size. One round deals by
|
||||
// rotation, highest tier first (ties: longest since their last batch), one person per sponsor per pass, warmest
|
||||
// first (hub heat score, ties in tank order) from the waiting tank (tank.adoptable: past the 24-hour sign-up grace, rule 3
|
||||
// applied, nobody adopted on LinkSpin). Never: the sponsor themself, anyone above them in their own line, anyone
|
||||
// adopted twice, a flagged, spam, throwaway or unsubscribed address
|
||||
// assignment tank.adopt(.., { batch: true }): the same sponsor change, chat, "X is now your sponsor" email and switch-on-payouts
|
||||
// reminders as any adoption. The sponsor gets one notice per batch (not one per person)
|
||||
// follow-up a batch person the sponsor has not contacted (a chat after the assignment, or "Contacted them") within
|
||||
// tankBatchFollowDays (7) goes back to the tank as 'unreached' (does not count toward their two adoptions:
|
||||
// the sponsor's miss). Contacted ones close like any adoption window: payouts on or wallet linked = done,
|
||||
// else back to the tank (counted)
|
||||
// tank feed per batch: one card to the shared payments topic and the live toast feed, naming the sponsor, the count and
|
||||
// the level, never the people (Marty 2026-11-15: "if the others see that happening, it may pick up the pace")
|
||||
// the 24-hour activation-hold safety net (tank.autoAssign) is unchanged and runs beside this; the 5xYourTeam draft has its own cap
|
||||
// MASTER SWITCH: site setting tankBatches (default '0'). Off: no round, no feed, the member panel answers { on:false }. The follow-up
|
||||
// still runs for batch people already assigned (they must not sit uncontacted). preview() is read-only whatever the switch says.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const tankready = require('./tankready');
|
||||
|
||||
const D = 86400000;
|
||||
const DEFAULTS = {
|
||||
tankBatches: '0', tankBatchActiveDays: 7, tankBatchBase: 10, tankBatchFueled: 20, tankBatchTwin: 25, tankBatchStep: 5, tankBatchMax: 50,
|
||||
tankBatchEveryDays: 2, tankBatchFollowDays: 7, tankBatchMinIapCents: 2000, tankBatchMinLsCents: 2500,
|
||||
tankBatchHigherIapCents: 5000, tankBatchHigherLsCents: 5000, tankBatchTopIapCents: 0 /* 0 = the highest package on the live catalog */, tankBatchTopLsCents: 50000,
|
||||
tankBatchFeed: '1',
|
||||
// the assigned people's "X is now your sponsor" emails go out through a throttled queue (Marty 2026-11-15: "spread the emails out"):
|
||||
// at most tankBatchEmailsPerDay per Central day, spaced evenly between the start and end hour (CT); Telegram cards at least tankBatchFeedGapMin apart
|
||||
// one announcement per round in the CTB group's General topic (blank topic = General, no thread id; blank chat = the payments group)
|
||||
tankBatchAnnounce: '1', tankBatchAnnounceChatId: '', tankBatchAnnounceTopicId: '',
|
||||
tankBatchEmailsPerDay: 100, tankBatchEmailStartHour: 8, tankBatchEmailEndHour: 20, tankBatchFeedGapMin: 2
|
||||
};
|
||||
let R = null; // { dataDir, db, accounts, chain, tank, refuel, messages, mailer, siteConfig, hooks: { excluded, excludedPerson, claim, feed, toast, notify, companyId, networkSeen }, clock }
|
||||
const clock = () => (R && R.clock ? R.clock() : Date.now());
|
||||
const lc = v => String(v || '').trim().toLowerCase();
|
||||
const usd = c => ('$' + (Number(c || 0) / 100).toFixed(2)).replace(/\.00$/, '');
|
||||
const nameOf = a => a ? (a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'a member')) : 'a member';
|
||||
|
||||
function cfg() {
|
||||
const sc = (R && R.siteConfig && R.siteConfig()) || {};
|
||||
const num = (k, lo, hi) => { const v = Number(sc[k] == null || sc[k] === '' ? DEFAULTS[k] : sc[k]); return Number.isFinite(v) && v >= lo && v <= hi ? v : DEFAULTS[k]; };
|
||||
return { on: String(sc.tankBatches == null ? DEFAULTS.tankBatches : sc.tankBatches) === '1', feed: String(sc.tankBatchFeed == null ? '1' : sc.tankBatchFeed) !== '0', announce: String(sc.tankBatchAnnounce == null ? '1' : sc.tankBatchAnnounce) !== '0',
|
||||
activeDays: num('tankBatchActiveDays', 1, 60), base: num('tankBatchBase', 1, 200), fueled: num('tankBatchFueled', 1, 200), twin: num('tankBatchTwin', 1, 200),
|
||||
step: num('tankBatchStep', 0, 100), max: num('tankBatchMax', 1, 500), everyDays: num('tankBatchEveryDays', 0.04, 60), followDays: num('tankBatchFollowDays', 1, 60),
|
||||
minIap: num('tankBatchMinIapCents', 0, 1e7), minLs: num('tankBatchMinLsCents', 0, 1e7), higherIap: num('tankBatchHigherIapCents', 0, 1e7), higherLs: num('tankBatchHigherLsCents', 0, 1e7),
|
||||
topIap: num('tankBatchTopIapCents', 0, 1e8), topLs: num('tankBatchTopLsCents', 0, 1e8),
|
||||
perDay: num('tankBatchEmailsPerDay', 1, 5000), startHour: num('tankBatchEmailStartHour', 0, 23), endHour: num('tankBatchEmailEndHour', 1, 24), feedGapMin: num('tankBatchFeedGapMin', 0, 120) };
|
||||
}
|
||||
|
||||
// ---- the ladder (pure: the tests drive it directly) ----
|
||||
// f = { iapMax, lsMax, refuel: { active, streak, both } | null }, c = cfg() with topIap resolved
|
||||
function tierFor(f, c) {
|
||||
const rf = f.refuel || {}; const reasons = [];
|
||||
const paidIap = f.iapMax >= c.minIap, paidLs = f.lsMax >= c.minLs;
|
||||
if (!paidIap && !paidLs) return { level: null, size: 0, reasons: ['no own package of ' + usd(c.minIap) + '+ on InstantAdPay or ' + usd(c.minLs) + '+ on LinkSpin'] };
|
||||
if (paidIap) reasons.push('own ' + usd(f.iapMax) + ' InstantAdPay package'); if (paidLs) reasons.push('own ' + usd(f.lsMax) + ' LinkSpin package');
|
||||
let level = 'Paid', size = c.base;
|
||||
const higher = (c.higherIap > 0 && f.iapMax >= c.higherIap) || (c.higherLs > 0 && f.lsMax >= c.higherLs);
|
||||
const top = (c.topIap > 0 && f.iapMax >= c.topIap) || (c.topLs > 0 && f.lsMax >= c.topLs);
|
||||
if (rf.active || higher) { level = 'Fueled'; size = c.fueled; if (rf.active) reasons.push('refuel streak month ' + rf.streak); if (higher) reasons.push('higher package (' + usd(c.higherIap) + '+ InstantAdPay / ' + usd(c.higherLs) + '+ LinkSpin)'); }
|
||||
if ((rf.active && rf.both) || top) { level = 'Twin Engine'; size = c.twin; if (rf.active && rf.both) reasons.push('both engines refueled this cycle'); if (top) reasons.push('top package'); }
|
||||
const extra = rf.active && rf.streak > 1 ? (rf.streak - 1) * c.step : 0;
|
||||
if (extra) { size += extra; reasons.push('+' + extra + ' for ' + (rf.streak - 1) + ' further refuel month' + (rf.streak === 2 ? '' : 's')); }
|
||||
size = Math.min(size, c.max);
|
||||
const label = level + (rf.active && rf.streak > 1 ? ', month ' + rf.streak : '');
|
||||
return { level, label, size, reasons };
|
||||
}
|
||||
// the member panel's "next step" line: what raises their batch, in leads they can sponsor (never money)
|
||||
function nextStep(t, f, c) {
|
||||
const rf = f.refuel || {};
|
||||
if (!t.level) return 'Buy your own ' + usd(c.minIap) + ' package on InstantAdPay (or ' + usd(c.minLs) + ' on LinkSpin) to start receiving ' + c.base + ' people at a time.';
|
||||
if (t.size >= c.max) return 'You are at the top of the ladder: ' + c.max + ' people at a time. Keep your refuel streak going to stay there.';
|
||||
if (t.level === 'Paid') return 'A counted monthly refuel (or a higher package) raises your batch to ' + c.fueled + '. Refuel both InstantAdPay and LinkSpin in the same cycle for ' + c.twin + '.';
|
||||
if (t.level === 'Fueled' && !(rf.active && rf.both)) return 'Refuel the other engine this cycle too (InstantAdPay and LinkSpin) to raise your batch to ' + Math.min(c.max, c.twin + (rf.active && rf.streak > 1 ? (rf.streak - 1) * c.step : 0)) + '.';
|
||||
return 'Your next consecutive refuel month adds ' + c.step + ' more (up to ' + c.max + ').';
|
||||
}
|
||||
const ladderView = c => [
|
||||
{ level: 'Paid', size: c.base, how: 'your own ' + usd(c.minIap) + ' InstantAdPay package or ' + usd(c.minLs) + ' LinkSpin package' },
|
||||
{ level: 'Fueled', size: c.fueled, how: 'a counted monthly refuel, or a higher package (' + usd(c.higherIap) + '+)' },
|
||||
{ level: 'Twin Engine', size: c.twin, how: 'both engines refueled this cycle, or the top package' },
|
||||
{ level: 'Streak', size: c.max, how: '+' + c.step + ' for every further consecutive refuel month, up to ' + c.max }
|
||||
];
|
||||
|
||||
// ---- storage: MySQL tank_batch_picks when DATABASE_URL is set, else a JSON document (local QA) ----
|
||||
const J = {
|
||||
st: null, FILE: () => path.join(R.dataDir, 'tank-batch.json'),
|
||||
load() { try { this.st = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.st = null; } if (!this.st || typeof this.st !== 'object') this.st = {}; this.st.nextId = this.st.nextId || 1; this.st.picks = this.st.picks || []; this.st.rounds = this.st.rounds || []; this.st.outbox = this.st.outbox || []; this.st.state = this.st.state || {}; this.st.nextOut = this.st.nextOut || 1; return this.st; },
|
||||
save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.st || this.load())); fs.renameSync(f + '.tmp', f); },
|
||||
async add(p) { const s = this.load(); const row = Object.assign({ id: s.nextId++ }, p); s.picks.push(row); this.save(); return Object.assign({}, row); },
|
||||
async close(id, status, why) { const x = this.load().picks.find(r => r.id === id); if (x) { x.status = status; x.closed = clock(); x.why = why || null; this.save(); } },
|
||||
async open() { return this.load().picks.filter(r => r.status === 'open').map(x => Object.assign({}, x)); },
|
||||
async byAdoption(aid) { const x = this.load().picks.find(r => r.adoptionId === Number(aid)); return x ? Object.assign({}, x) : null; },
|
||||
async lastBySponsor() { const m = new Map(); for (const r of this.load().picks) m.set(r.sponsor, Math.max(m.get(r.sponsor) || 0, r.roundAt || r.at)); return m; },
|
||||
async recent(n) { return this.load().picks.slice(-(n || 100)).reverse().map(x => Object.assign({}, x)); },
|
||||
async addRound(x) { const s = this.load(); s.rounds.push(x); if (s.rounds.length > 200) s.rounds = s.rounds.slice(-200); this.save(); },
|
||||
async rounds(n) { return this.load().rounds.slice(-(n || 30)).reverse(); },
|
||||
// outbox: kind 'mail' | 'feed', status queued -> sending -> sent | skipped
|
||||
async enqueue(x) { const s = this.load(); const row = Object.assign({ id: s.nextOut++, status: 'queued', created: clock(), sentAt: null, why: null }, x); s.outbox.push(row); this.save(); return row; },
|
||||
async oldest(kind, n) { return this.load().outbox.filter(r => r.kind === kind && r.status === 'queued').sort((a, b) => a.id - b.id).slice(0, n || 1).map(x => Object.assign({}, x)); },
|
||||
async take(id) { const s = this.load(); const x = s.outbox.find(r => r.id === id); if (!x || x.status !== 'queued') return false; x.status = 'sending'; this.save(); return true; },
|
||||
async finish(id, status, why) { const s = this.load(); const x = s.outbox.find(r => r.id === id); if (x) { x.status = status; x.sentAt = clock(); x.why = why || null; this.save(); } },
|
||||
async counts(kind, since) { const rows = this.load().outbox.filter(r => r.kind === kind); return { queued: rows.filter(r => r.status === 'queued').length, sent: rows.filter(r => r.status === 'sent' && r.sentAt >= since).length, skipped: rows.filter(r => r.status === 'skipped' && r.sentAt >= since).length }; },
|
||||
async getState(k) { const v = this.load().state[k]; return v === undefined ? null : v; },
|
||||
async setState(k, v) { const s = this.load(); s.state[k] = v; this.save(); }
|
||||
};
|
||||
const rowP = r => ({ id: Number(r.id), adoptionId: Number(r.adoption_id), sponsor: r.sponsor, adoptee: r.adoptee, at: Number(r.at), roundAt: Number(r.round_at), level: r.level, size: Number(r.size), status: r.status, closed: r.closed ? Number(r.closed) : null, why: r.why || null });
|
||||
const Q = {
|
||||
async add(p) { const r = await R.db.q('INSERT INTO tank_batch_picks (adoption_id,sponsor,adoptee,at,round_at,level,size,status) VALUES (?,?,?,?,?,?,?,?)', [p.adoptionId, p.sponsor, p.adoptee, p.at, p.roundAt, p.level, p.size, 'open']); return Object.assign({ id: r.insertId }, p); },
|
||||
async close(id, status, why) { await R.db.q('UPDATE tank_batch_picks SET status=?, closed=?, why=? WHERE id=?', [status, clock(), why ? String(why).slice(0, 200) : null, Number(id)]); },
|
||||
async open() { return (await R.db.q("SELECT * FROM tank_batch_picks WHERE status='open' ORDER BY id")).map(rowP); },
|
||||
async byAdoption(aid) { const r = (await R.db.q('SELECT * FROM tank_batch_picks WHERE adoption_id=? LIMIT 1', [Number(aid)]))[0]; return r ? rowP(r) : null; },
|
||||
async lastBySponsor() { return new Map((await R.db.q('SELECT sponsor, MAX(round_at) t FROM tank_batch_picks GROUP BY sponsor')).map(r => [r.sponsor, Number(r.t)])); },
|
||||
async recent(n) { return (await R.db.q('SELECT * FROM tank_batch_picks ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); },
|
||||
async addRound(x) { await R.db.q('INSERT INTO tank_batch_rounds (at, summary) VALUES (?,?)', [x.at, JSON.stringify(x).slice(0, 60000)]); },
|
||||
async rounds(n) { return (await R.db.q('SELECT summary FROM tank_batch_rounds ORDER BY id DESC LIMIT ?', [Number(n) || 30])).map(r => { try { return JSON.parse(r.summary); } catch (e) { return null; } }).filter(Boolean); },
|
||||
async enqueue(x) { const r = await R.db.q("INSERT INTO tank_batch_outbox (kind,to_email,sponsor,adoption_id,subject,body,payload,created,status) VALUES (?,?,?,?,?,?,?,?,'queued')", [x.kind, x.to || null, x.sponsor || null, x.adoptionId || null, x.subject || null, x.body || null, x.payload ? JSON.stringify(x.payload) : null, clock()]); return Object.assign({ id: r.insertId, status: 'queued' }, x); },
|
||||
async oldest(kind, n) { return (await R.db.q("SELECT * FROM tank_batch_outbox WHERE kind=? AND status='queued' ORDER BY id LIMIT ?", [kind, Number(n) || 1])).map(r => ({ id: Number(r.id), kind: r.kind, to: r.to_email, sponsor: r.sponsor, adoptionId: r.adoption_id ? Number(r.adoption_id) : null, subject: r.subject, body: r.body, payload: r.payload ? JSON.parse(r.payload) : null, created: Number(r.created), status: r.status })); },
|
||||
async take(id) { const r = await R.db.q("UPDATE tank_batch_outbox SET status='sending' WHERE id=? AND status='queued'", [Number(id)]); return Number(r.affectedRows) === 1; },
|
||||
async finish(id, status, why) { await R.db.q('UPDATE tank_batch_outbox SET status=?, sent_at=?, why=? WHERE id=?', [status, clock(), why ? String(why).slice(0, 200) : null, Number(id)]); },
|
||||
async counts(kind, since) { const r = (await R.db.q("SELECT SUM(status='queued') q, SUM(status='sent' AND sent_at>=?) s, SUM(status='skipped' AND sent_at>=?) k FROM tank_batch_outbox WHERE kind=?", [since, since, kind]))[0] || {}; return { queued: Number(r.q || 0), sent: Number(r.s || 0), skipped: Number(r.k || 0) }; },
|
||||
async getState(k) { const r = (await R.db.q('SELECT v FROM tank_batch_state WHERE k=?', [k]))[0]; return r ? JSON.parse(r.v) : null; },
|
||||
async setState(k, v) { await R.db.q('INSERT INTO tank_batch_state (k,v) VALUES (?,?) ON DUPLICATE KEY UPDATE v=VALUES(v)', [k, JSON.stringify(v)]); }
|
||||
};
|
||||
const dbOn = () => !!(R && R.db && R.db.enabled && R.db.enabled());
|
||||
const S = () => (dbOn() ? Q : J);
|
||||
async function ensureTables() {
|
||||
if (!dbOn()) return;
|
||||
await R.db.q(`CREATE TABLE IF NOT EXISTS tank_batch_picks (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY, adoption_id INT NOT NULL, sponsor VARCHAR(190) NOT NULL, adoptee VARCHAR(190) NOT NULL, at BIGINT NOT NULL, round_at BIGINT NOT NULL,
|
||||
level VARCHAR(40) NULL, size INT NOT NULL DEFAULT 0, status VARCHAR(16) NOT NULL, closed BIGINT NULL, why VARCHAR(200) NULL,
|
||||
KEY adoption (adoption_id), KEY sp (sponsor, status), KEY st (status), KEY adoptee (adoptee)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // holding tank batches (each one a tank adoption)
|
||||
await R.db.q(`CREATE TABLE IF NOT EXISTS tank_batch_outbox (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY, kind VARCHAR(8) NOT NULL, to_email VARCHAR(190) NULL, sponsor VARCHAR(190) NULL, adoption_id INT NULL, subject VARCHAR(300) NULL,
|
||||
body MEDIUMTEXT NULL, payload TEXT NULL, created BIGINT NOT NULL, status VARCHAR(10) NOT NULL, sent_at BIGINT NULL, why VARCHAR(200) NULL,
|
||||
KEY ks (kind, status, id), KEY sent (kind, sent_at), KEY toe (to_email)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // the throttled batch emails + spaced Telegram cards (survives deploys)
|
||||
await R.db.q('CREATE TABLE IF NOT EXISTS tank_batch_state (k VARCHAR(40) PRIMARY KEY, v TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||
await R.db.q('CREATE TABLE IF NOT EXISTS tank_batch_rounds (id INT AUTO_INCREMENT PRIMARY KEY, at BIGINT NOT NULL, summary MEDIUMTEXT NOT NULL, KEY t (at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||
}
|
||||
async function init(opts) { R = opts; R.hooks = R.hooks || {}; J.st = null; await ensureTables(); }
|
||||
|
||||
// ---- facts about the members ----
|
||||
function iapMaxByMember() { const m = new Map(); for (const ev of R.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.buyerId) { const id = Number(ev.buyerId); m.set(id, Math.max(m.get(id) || 0, Number(ev.priceCents) || 0)); } return m; }
|
||||
async function topIapCents(c) {
|
||||
if (c.topIap > 0) return c.topIap;
|
||||
try { const cat = await R.chain.catalog(); const top = Math.max(0, ...(cat || []).map(p => Number(p.priceCents) || 0)); if (top > 0) return top; } catch (e) {}
|
||||
return 50000; // Elite $500, the top of the published ladder (chatbot.js) when the catalog cannot be read
|
||||
}
|
||||
async function factsOf(a, byMember) {
|
||||
let iapMax = Number(a.memberId) > 0 ? byMember.get(Number(a.memberId)) || 0 : 0;
|
||||
if (R.accounts.positions) { try { for (const p of await R.accounts.positions(a.email)) if (p.memberId) iapMax = Math.max(iapMax, byMember.get(Number(p.memberId)) || 0); } catch (e) {} }
|
||||
let rf = null; try { rf = R.refuel && R.refuel.standing ? await R.refuel.standing(a.email, clock()) : null; } catch (e) { rf = null; }
|
||||
const lsMax = rf ? Number(rf.maxCents.linkspin) || 0 : 0;
|
||||
if (rf) iapMax = Math.max(iapMax, Number(rf.maxCents.iap) || 0);
|
||||
return { iapMax, lsMax, refuel: rf };
|
||||
}
|
||||
const companyIds = () => new Set([1, Number(R.hooks.companyId ? R.hooks.companyId() : 1) || 1]);
|
||||
async function lastSeenOf(a) {
|
||||
let t = Number(a.lastSeen) || 0;
|
||||
if (R.hooks.networkSeen) { try { t = Math.max(t, Number(await R.hooks.networkSeen(a.email)) || 0); } catch (e) {} }
|
||||
return t;
|
||||
}
|
||||
|
||||
// every member, sorted out: eligible sponsors (with tier, room, due) and the near misses (why not)
|
||||
async function sponsors(c, now) {
|
||||
const byMember = iapMaxByMember(); const co = companyIds(); const last = await S().lastBySponsor();
|
||||
const openByS = new Map(); for (const p of await S().open()) { if (!openByS.has(p.sponsor)) openByS.set(p.sponsor, []); openByS.get(p.sponsor).push(p); }
|
||||
const out = [], skipped = []; const why = {};
|
||||
const skip = (a, reason, extra) => { why[reason] = (why[reason] || 0) + 1; if (skipped.length < 300) skipped.push(Object.assign({ name: nameOf(a), reason }, extra || {})); };
|
||||
for (const a of await R.accounts.listAll(1e6)) {
|
||||
if (Number(a.memberId) > 0 && co.has(Number(a.memberId))) continue;
|
||||
const seen = await lastSeenOf(a); const active = !!seen && now - seen <= c.activeDays * D;
|
||||
if (!active && !(Number(a.memberId) > 0)) continue; // cheap first: a free inactive account is nobody's near miss
|
||||
const f = await factsOf(a, byMember); const t = tierFor(f, Object.assign({}, c, { topIap: c.topIapResolved }));
|
||||
if (!t.level) continue; // free members are not sponsors here (not listed: the near misses are paid members)
|
||||
if (!active) { skip(a, 'not active in the last ' + c.activeDays + ' days', { level: t.label, size: t.size, lastSeen: seen || 0 }); continue; }
|
||||
const bar = R.hooks.excluded || R.hooks.isSuspended; if (bar && bar(a.email)) { skip(a, 'suspended or flagged'); continue; }
|
||||
const el = await R.tank.batchEligibility(a.email); if (!el.ok) { skip(a, el.code === 'no_contract_line' ? 'nobody in their line has payouts on at InstantAdPay' : el.reason, { level: t.label, size: t.size }); continue; }
|
||||
const open = []; for (const p of openByS.get(a.email) || []) { const acc = await R.accounts.byEmail(p.adoptee); if (!(acc && Number(acc.memberId) > 0)) open.push(p); }
|
||||
const lastAt = last.get(a.email) || 0; const dueAt = lastAt ? lastAt + c.everyDays * D : 0;
|
||||
out.push({ account: a, email: a.email, name: nameOf(a), username: a.username || null, memberId: Number(a.memberId) || 0, lastSeen: seen, tier: t, facts: f,
|
||||
holding: open.length, room: Math.max(0, t.size - open.length), lastBatchAt: lastAt, dueAt, due: !dueAt || now >= dueAt });
|
||||
}
|
||||
const rank = { 'Twin Engine': 3, Fueled: 2, Paid: 1 };
|
||||
out.sort((x, y) => y.tier.size - x.tier.size || (rank[y.tier.level] || 0) - (rank[x.tier.level] || 0) || x.lastBatchAt - y.lastBatchAt || y.lastSeen - x.lastSeen || (x.email < y.email ? -1 : 1));
|
||||
return { list: out, skipped, why };
|
||||
}
|
||||
|
||||
// the waiting people a batch may take, warmest first
|
||||
async function poolOf() {
|
||||
const list = await R.tank.adoptable(); const local = await R.tank.summaryMap(); const ex = {}; const rows = [];
|
||||
const no = k => { ex[k] = (ex[k] || 0) + 1; };
|
||||
for (const w of list) {
|
||||
if (R.hooks.excluded && R.hooks.excluded(w.email)) { no('flagged or suspended'); continue; }
|
||||
const n = ((local.get(w.email) || {}).count || 0) + (R.tank.remoteCount ? R.tank.remoteCount(w.email) : 0);
|
||||
if (n >= (R.tank.MAX_ADOPTIONS || 2)) { no('adopted twice already'); continue; }
|
||||
let px = null; if (R.hooks.excludedPerson) { try { px = await R.hooks.excludedPerson(w.email); } catch (e) { px = 'check failed'; } }
|
||||
if (px) { no(px); continue; }
|
||||
rows.push(w);
|
||||
}
|
||||
// warmest first (Marty 2026-11-19): the hub heat score from the tank card (tankready.js). No reading (hub down) counts as 0,
|
||||
// so ties and a dark hub keep the tank's own order
|
||||
const heat = new Map((await tankready.attach(rows, 4000)).map(w => [w.email, w.rd && w.rd.heat ? Number(w.rd.heat.score) || 0 : 0]));
|
||||
rows.sort((a, b) => (heat.get(b.email) || 0) - (heat.get(a.email) || 0));
|
||||
return { waiting: list.length, rows, excluded: ex };
|
||||
}
|
||||
|
||||
// one round: who gets whom. Read-only: the live run applies it, the preview shows it.
|
||||
async function plan(c, now) {
|
||||
const sp = await sponsors(c, now); const pool = await poolOf();
|
||||
const takers = sp.list.filter(s => s.due && s.room > 0).map(s => Object.assign(s, { give: [] }));
|
||||
const left = pool.rows.slice(); const loopCache = new Map();
|
||||
let moved = true;
|
||||
while (moved && left.length) {
|
||||
moved = false;
|
||||
for (const s of takers) {
|
||||
if (s.give.length >= s.room || !left.length) continue;
|
||||
for (let i = 0; i < left.length; i++) {
|
||||
const w = left[i];
|
||||
if (w.email === s.email) continue;
|
||||
const k = w.email + '>' + s.email;
|
||||
if (!loopCache.has(k)) loopCache.set(k, await R.tank.inDownlineOf(w.email, s.account).catch(() => true));
|
||||
if (loopCache.get(k)) continue;
|
||||
s.give.push(w); left.splice(i, 1); moved = true; break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { sponsors: sp, pool, takers, left: left.length };
|
||||
}
|
||||
|
||||
// ---- the live round ----
|
||||
let busy = null;
|
||||
const lock = fn => (dbOn() && R.db.withLock ? R.db.withLock('tankbatch', fn, 5) : fn());
|
||||
async function round() {
|
||||
const c = cfg(); if (!c.on) return { on: false };
|
||||
if (busy) return busy;
|
||||
busy = (async () => {
|
||||
c.topIapResolved = await topIapCents(c);
|
||||
const now = clock(); const summary = { at: now, batches: [], assigned: 0, refused: 0 }; const cards = [];
|
||||
await lock(async () => {
|
||||
const p = await plan(c, now);
|
||||
for (const s of p.takers) {
|
||||
if (!s.give.length) continue;
|
||||
const got = [];
|
||||
for (const w of s.give) {
|
||||
const msg = 'Hi, I am ' + s.name + '. ' + (w.via === 'btc4hits' ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor, so you were matched with me from the holding tank: active members who have bought their own package take turns. I will walk you through the first steps whenever you are ready. Reply here.';
|
||||
const r = await R.tank.adopt(s.email, w.username || w.email, msg, { batch: true, recordNote: 'holding tank batch (' + s.tier.label + ', ' + s.tier.size + ' at a time)', queueMail: m => S().enqueue({ kind: 'mail', to: m.to, sponsor: m.sponsor, adoptionId: m.adoptionId, subject: m.subject, body: m.body }) }).catch(e => ({ error: e.message }));
|
||||
if (!(r && r.ok)) { summary.refused++; continue; }
|
||||
await S().add({ adoptionId: Number(r.adoption.id), sponsor: s.email, adoptee: r.adoptee, at: clock(), roundAt: now, level: s.tier.label, size: s.tier.size, status: 'open' });
|
||||
got.push(r.adopteeName);
|
||||
}
|
||||
if (!got.length) continue;
|
||||
summary.assigned += got.length; summary.batches.push({ sponsor: s.name, level: s.tier.label, size: s.tier.size, count: got.length });
|
||||
await tellSponsor(s, got, c);
|
||||
cards.push([s, got.length]);
|
||||
}
|
||||
// the round's announcement for the new members area (General) first, then one card per sponsor in the payments topic;
|
||||
// all queued: mailTick posts them at least tankBatchFeedGapMin apart
|
||||
if (cards.length && c.announce) await S().enqueue({ kind: 'feed', payload: { announce: announceText(cards, c), roundAt: now } });
|
||||
for (const [s, n] of cards) await feedCard(s, n, now, c);
|
||||
});
|
||||
if (summary.batches.length) { try { await S().addRound(summary); } catch (e) { console.error('tankbatch round log', e.message); } console.log('tankbatch round', JSON.stringify({ assigned: summary.assigned, batches: summary.batches.length, refused: summary.refused })); }
|
||||
return Object.assign({ on: true }, summary);
|
||||
})().finally(() => { busy = null; });
|
||||
return busy;
|
||||
}
|
||||
async function tellSponsor(s, names, c) {
|
||||
const subject = names.length + ' new ' + (names.length === 1 ? 'person' : 'people') + ' from the holding tank are in your line';
|
||||
const text = 'As a ' + s.tier.label + ' member you receive up to ' + s.tier.size + ' people at a time from the holding tank. These ' + names.length + ' joined without a sponsor and are now in your line: ' + names.join(', ')
|
||||
+ '.\n\nEach one got a chat from you and an email saying you are their sponsor. Say hello in the next ' + c.followDays + ' days: anyone you have not contacted by then (a chat from you, or "Contacted them" on their row in My line) goes back to the holding tank for another member.\n\n' + 'https://instantadpay.com/my#line';
|
||||
if (R.hooks.notify) { try { await R.hooks.notify(s.email, subject, text); } catch (e) {} }
|
||||
if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) { try { await R.mailer.send(s.email, 'InstantAdPay: ' + subject, text + '\n\nInstantAdPay'); } catch (e) {} }
|
||||
}
|
||||
// the round's post for the CTB group's new members area (General topic; Marty 2026-11-15: "Post it to the new members area in
|
||||
// Telegram"): how many got a sponsor, who received leads grouped by level, and how to qualify. Never the people, never income.
|
||||
function announceText(cards, c) {
|
||||
const clean = t => String(t || '').replace(/[<>&]/g, '');
|
||||
const total = cards.reduce((n, x) => n + x[1], 0);
|
||||
const order = ['Twin Engine', 'Fueled', 'Paid']; const groups = {};
|
||||
for (const [s, n] of cards) { const k = order.find(o => s.tier.level === o) || s.tier.level; (groups[k] = groups[k] || []).push(clean(s.username ? '@' + s.username : s.name) + ' ' + n); }
|
||||
const lines = order.filter(k => groups[k]).map(k => '<b>' + k + '</b>: ' + groups[k].join(', '));
|
||||
return '\u{1F91D} <b>Holding tank: ' + total + ' new member' + (total === 1 ? '' : 's') + ' just got a sponsor</b>\n'
|
||||
+ 'Active members who bought their own package received leads they can sponsor:\n\n' + lines.join('\n') + '\n\n'
|
||||
+ '<b>How to get fed leads:</b> your own ' + usd(c.minIap) + ' InstantAdPay or ' + usd(c.minLs) + ' LinkSpin package = ' + c.base + ' at a time; a counted monthly refuel or a ' + usd(c.higherIap) + '+ package = ' + c.fueled + '; both engines refueled this cycle or the top package = ' + c.twin + '; +' + c.step + ' for every further refuel month in a row, up to ' + c.max + '. Sign in at least once a week to stay on the list.\n'
|
||||
+ 'https://instantadpay.com/my';
|
||||
}
|
||||
async function feedCard(s, n, roundAt, c) {
|
||||
if (!c.feed) return;
|
||||
const who = s.username ? '@' + s.username : s.name;
|
||||
const what = n + ' new team member' + (n === 1 ? '' : 's');
|
||||
await S().enqueue({ kind: 'feed', sponsor: s.email, payload: { who, what, level: s.tier.label, roundAt } });
|
||||
}
|
||||
|
||||
// ---- the outbox: throttled emails + spaced Telegram cards. Once everywhere: one MySQL lock across app copies, a row claimed
|
||||
// queued -> sending by a conditional UPDATE, and a marks claim per row; a crash between claim and send loses that one (never twice).
|
||||
const TZ = 'America/Chicago';
|
||||
const ctParts = ts => { const o = {}; for (const p of new Intl.DateTimeFormat('en-US', { timeZone: TZ, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }).formatToParts(new Date(ts))) o[p.type] = p.value; return { day: o.year + '-' + o.month + '-' + o.day, hour: Number(o.hour) % 24, minute: Number(o.minute) }; };
|
||||
const inWindow = (ts, c) => { const h = ctParts(ts).hour; return h >= c.startHour && h < c.endHour; };
|
||||
function dayStart(ts) { const p = ctParts(ts); return ts - (p.hour * 60 + p.minute) * 60000 - (ts % 60000); } // Central midnight (to the minute)
|
||||
const gapMs = c => Math.max(60000, Math.floor((c.endHour - c.startHour) * 3600000 / c.perDay));
|
||||
function nextWindowOpen(ts, c) { let t = ts - (ts % 60000); for (let i = 0; i < 4 * 24 * 7 && !inWindow(t, c); i++) t += 15 * 60000; return t; }
|
||||
const mlock = fn => (dbOn() && R.db.withLock ? R.db.withLock('tankbatchmail', fn, 2) : fn());
|
||||
async function stillOk(it) { // right before each send: still in that sponsor's line, and not unsubscribed, blocked or erased
|
||||
const a = await R.accounts.byEmail(it.to); if (!a) return 'account gone';
|
||||
const sp = await R.accounts.byEmail(it.sponsor); if (!sp) return 'sponsor gone';
|
||||
const toks = [sp.username, sp.code, sp.memberId ? String(sp.memberId) : null].filter(Boolean).map(x => String(x).toLowerCase());
|
||||
if (!toks.includes(String(a.sponsorRef || '').toLowerCase())) return 'no longer with this sponsor';
|
||||
if (R.hooks.excluded && R.hooks.excluded(a.email)) return 'flagged or suspended';
|
||||
if (R.hooks.excludedPerson) { const px = await Promise.resolve(R.hooks.excludedPerson(a.email)).catch(() => 'check failed'); if (px) return px; }
|
||||
return null;
|
||||
}
|
||||
let mailing = null;
|
||||
function mailTick() { if (!mailing) mailing = Promise.resolve().then(() => mlock(mailRun)).catch(e => { if (!/lock busy/.test(e.message)) console.error('tankbatch mail', e.message); return { busy: true }; }).finally(() => { mailing = null; }); return mailing; }
|
||||
async function mailRun() {
|
||||
const c = cfg(); const now = clock(); const out = { feed: 0, sent: 0, skipped: 0 };
|
||||
if (await S().getState('paused')) return Object.assign(out, { paused: true });
|
||||
// one Telegram card per tick, at least feedGapMin after the last
|
||||
const lastFeed = Number(await S().getState('lastFeedAt')) || 0;
|
||||
if (now - lastFeed >= c.feedGapMin * 60000) {
|
||||
const [f] = await S().oldest('feed', 1);
|
||||
if (f && await S().take(f.id) && (!R.hooks.claim || await Promise.resolve(R.hooks.claim('tbfeed:' + f.id)).catch(() => false))) {
|
||||
await S().setState('lastFeedAt', now);
|
||||
const p = f.payload || {};
|
||||
if (p.announce) { try { if (R.hooks.announce) await R.hooks.announce(p.announce); } catch (e) { console.error('tankbatch announce', e.message); } }
|
||||
else try { if (R.hooks.feed) await R.hooks.feed(p.who, p.what, p.level); } catch (e) { console.error('tankbatch feed', e.message); }
|
||||
if (!p.announce) try { if (R.hooks.toast) R.hooks.toast({ type: 'Adopted', sponsor: p.who, member: p.what + ' (' + p.level + ' level)', ts: now }); } catch (e) {}
|
||||
await S().finish(f.id, 'sent'); out.feed++;
|
||||
}
|
||||
}
|
||||
// one email per tick at most, inside the window, under the day cap, evenly spaced
|
||||
if (!inWindow(now, c)) return out;
|
||||
const today = await S().counts('mail', dayStart(now)); if (today.sent >= c.perDay) return out;
|
||||
const lastMail = Number(await S().getState('lastMailAt')) || 0; if (now - lastMail < gapMs(c)) return out;
|
||||
for (const it of await S().oldest('mail', 25)) { // skipped rows do not use the slot: the next one goes in the same tick
|
||||
if (!(await S().take(it.id))) continue;
|
||||
if (R.hooks.claim && !(await Promise.resolve(R.hooks.claim('tbmail:' + it.id)).catch(() => false))) continue;
|
||||
const why = await stillOk(it);
|
||||
if (why) { await S().finish(it.id, 'skipped', why); out.skipped++; continue; }
|
||||
await S().setState('lastMailAt', now);
|
||||
try { if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) await R.mailer.send(it.to, it.subject, it.body); } catch (e) { console.error('tankbatch mail send', e.message); }
|
||||
await S().finish(it.id, 'sent'); out.sent++;
|
||||
try { if (R.tank.payTrack) R.tank.payTrack(it.to, it.sponsor, it.adoptionId, false); } catch (e) {} // the 24 h / 72 h reminders count from this email
|
||||
break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
async function mailView() {
|
||||
const c = cfg(); const now = clock(); const today = await S().counts('mail', dayStart(now)); const feeds = await S().counts('feed', dayStart(now));
|
||||
const paused = !!(await S().getState('paused')); const lastMail = Number(await S().getState('lastMailAt')) || 0;
|
||||
let next = null;
|
||||
if (!paused && today.queued) {
|
||||
next = Math.max(now, lastMail + gapMs(c));
|
||||
if (today.sent >= c.perDay) next = dayStart(now) + 86400000 + 3 * 3600000; // into tomorrow (DST-safe), then the window
|
||||
next = nextWindowOpen(next, c);
|
||||
}
|
||||
return { paused, perDay: c.perDay, window: c.startHour + ':00 to ' + c.endHour + ':00 CT', spacingMin: Math.round(gapMs(c) / 60000 * 10) / 10, queued: today.queued, sentToday: today.sent, skippedToday: today.skipped,
|
||||
nextSendAt: next, feed: { queued: feeds.queued, sentToday: feeds.sent, gapMin: c.feedGapMin }, daysToClear: Math.ceil(today.queued / c.perDay) };
|
||||
}
|
||||
async function setPaused(v) { await S().setState('paused', !!v); return mailView(); }
|
||||
|
||||
// ---- follow-up: uncontacted batch people go back to the tank ----
|
||||
let following = null;
|
||||
function followUp() { if (!following) following = followRun().finally(() => { following = null; }); return following; }
|
||||
async function followRun() {
|
||||
const c = cfg(); const now = clock(); const out = { done: 0, unreached: 0, returned: 0, kept: 0, moved: 0, waiting: 0 }; const back = new Map();
|
||||
for (const p of await S().open()) {
|
||||
const open = await R.tank.openOf(p.adoptee);
|
||||
if (!open.some(ad => Number(ad.id) === p.adoptionId)) { await S().close(p.id, 'moved', 'the adoption was closed elsewhere (released, moved or followed)'); out.moved++; continue; }
|
||||
const a = await R.accounts.byEmail(p.adoptee);
|
||||
if (a && Number(a.memberId) > 0) { await R.tank.closeAdoption(p.adoptionId, 'done'); await S().close(p.id, 'done', 'payouts on'); out.done++; continue; }
|
||||
if (now - p.at < c.followDays * D) continue;
|
||||
if (!a) { await R.tank.closeAdoption(p.adoptionId, 'expired'); await S().close(p.id, 'gone', 'account gone'); continue; }
|
||||
const chat = R.messages && R.messages.lastFrom ? await R.messages.lastFrom(p.sponsor, p.adoptee).catch(() => 0) : 0;
|
||||
const mk = R.tank.markOf ? await R.tank.markOf(p.adoptee).catch(() => null) : null;
|
||||
const contacted = chat > p.at + 60000 || !!(mk && mk.contacted > p.at); // the assignment's own chat is sent at p.at: it does not count
|
||||
if (contacted && a.address) { await R.tank.closeAdoption(p.adoptionId, 'done'); await S().close(p.id, 'done', 'contacted, wallet linked'); out.done++; continue; }
|
||||
if (contacted && await R.tank.countAll(p.adoptee) >= (R.tank.MAX_ADOPTIONS || 2)) { await R.tank.closeAdoption(p.adoptionId, 'expired'); await S().close(p.id, 'kept', 'adopted twice: stays with this sponsor'); out.kept++; continue; }
|
||||
const lk = await R.tank.lockedWhy(p.adoptee);
|
||||
if (lk === 'unknown') { out.waiting++; continue; }
|
||||
if (lk === 'locked') { await R.tank.closeAdoption(p.adoptionId, 'expired'); await S().close(p.id, 'kept', 'locked on a network contract'); out.kept++; continue; }
|
||||
const r = await R.tank.setSponsorDeliberate(p.adoptee, '', 'expire', contacted ? 'holding tank batch window ended' : 'holding tank batch: not contacted in ' + c.followDays + ' days');
|
||||
if (r && r.error) { out.waiting++; continue; }
|
||||
await R.tank.closeAdoption(p.adoptionId, contacted ? 'expired' : 'unreached');
|
||||
await S().close(p.id, contacted ? 'returned' : 'unreached', contacted ? 'window ended' : 'not contacted');
|
||||
if (contacted) out.returned++; else { out.unreached++; if (!back.has(p.sponsor)) back.set(p.sponsor, []); back.get(p.sponsor).push(nameOf(a)); }
|
||||
}
|
||||
for (const [sp, names] of back) {
|
||||
if (R.hooks.notify) { try { await R.hooks.notify(sp, names.length + ' from your holding tank batch went back to the tank', names.join(', ') + (names.length === 1 ? ' was' : ' were') + ' in your line for ' + c.followDays + ' days with no chat from you and no "Contacted them" mark, so ' + (names.length === 1 ? 'they have' : 'they have') + ' gone back to the holding tank for another member. Your next batch still comes on schedule: say hello to each new person in the first few days.\n\nhttps://instantadpay.com/my#line'); } catch (e) {} }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
async function isBatchPick(adoptionId) { if (!R) return false; const p = await S().byAdoption(adoptionId); return !!(p && p.status === 'open'); }
|
||||
|
||||
// the hourly pass (server.js): follow-up always, a round only while the switch is on
|
||||
async function tick() { const f = await followUp().catch(e => { console.error('tankbatch follow', e.message); return null; }); const r = await round().catch(e => { console.error('tankbatch round', e.message); return { error: e.message }; }); return { follow: f, round: r }; }
|
||||
|
||||
// ---- admin preview: the first round against the live tank, nothing written, nothing sent ----
|
||||
async function preview() {
|
||||
const c = cfg(); c.topIapResolved = await topIapCents(c); const now = clock();
|
||||
const p = await plan(c, now);
|
||||
const sp = p.sponsors.list.map(s => ({ name: s.name, memberId: s.memberId || null, level: s.tier.label, size: s.tier.size, reasons: s.tier.reasons,
|
||||
lastSeen: s.lastSeen, iapMaxUsd: s.facts.iapMax / 100, lsMaxUsd: s.facts.lsMax / 100,
|
||||
refuel: s.facts.refuel ? { active: s.facts.refuel.active, streak: s.facts.refuel.streak, both: s.facts.refuel.both, lastDay: s.facts.refuel.lastDay } : null,
|
||||
holding: s.holding, room: s.room, due: s.due, dueAt: s.dueAt || null,
|
||||
wouldGet: (s.give || []).length, firstNames: (s.give || []).slice(0, 8).map(w => w.name) }));
|
||||
const byLevel = {}; for (const s of sp) { const b = byLevel[s.level.replace(/, month \d+$/, '')] = byLevel[s.level.replace(/, month \d+$/, '')] || { sponsors: 0, people: 0 }; b.sponsors++; b.people += s.wouldGet; }
|
||||
return { readOnly: true, on: c.on, generatedAt: now, settings: Object.assign({}, c, { topIapCents: c.topIapResolved }), ladder: ladderView(c),
|
||||
emailPlan: await (async () => { const q = (await S().counts('mail', 0)).queued; const people = p.takers.reduce((n, t) => n + t.give.length, 0); return { alreadyQueued: q, thisRound: people, perDay: c.perDay, window: c.startHour + ':00 to ' + c.endHour + ':00 CT', spacingMin: Math.round(gapMs(c) / 60000 * 10) / 10, daysToClear: Math.ceil((q + people) / c.perDay) }; })(),
|
||||
tank: { waiting: p.pool.waiting, offered: p.pool.rows.length, excluded: p.pool.excluded, leftAfterRound: p.left },
|
||||
totals: { eligibleSponsors: sp.length, takingThisRound: p.takers.filter(t => t.give.length).length, people: p.takers.reduce((n, t) => n + t.give.length, 0), capacity: sp.reduce((n, s) => n + s.room, 0), byLevel },
|
||||
sponsors: sp, notEligible: { counts: p.sponsors.why, members: p.sponsors.skipped } };
|
||||
}
|
||||
|
||||
// ---- the member panel "How to get fed leads" ----
|
||||
async function myView(email) {
|
||||
const c = cfg(); if (!c.on) return { on: false };
|
||||
c.topIapResolved = await topIapCents(c);
|
||||
const a = await R.accounts.byEmail(lc(email)); if (!a) return { on: true, ladder: ladderView(c) };
|
||||
const f = await factsOf(a, iapMaxByMember()); const t = tierFor(f, Object.assign({}, c, { topIap: c.topIapResolved }));
|
||||
const seen = await lastSeenOf(a); const active = !!seen && clock() - seen <= c.activeDays * D;
|
||||
const mine = (await S().open()).filter(p => p.sponsor === a.email);
|
||||
const last = (await S().lastBySponsor()).get(a.email) || 0;
|
||||
return { on: true, ladder: ladderView(c), everyDays: c.everyDays, followDays: c.followDays,
|
||||
me: { level: t.level, label: t.label || null, size: t.size, reasons: t.reasons, next: nextStep(t, f, c), active, open: mine.length, lastBatchAt: last || null, nextBatchAt: last ? last + c.everyDays * D : null } };
|
||||
}
|
||||
async function adminView() { return { settings: cfg(), open: (await S().open()).length, recent: await S().recent(100), rounds: await S().rounds(20) }; }
|
||||
|
||||
module.exports = { announceText, mailTick, mailView, setPaused, _gapMs: gapMs, _inWindow: inWindow, init, cfg, tierFor, nextStep, ladderView, plan, round, followUp, tick, preview, myView, adminView, isBatchPick, DEFAULTS };
|
||||
@@ -0,0 +1,125 @@
|
||||
'use strict';
|
||||
// Holding-tank readiness (Marty 2026-11-18, stage 1 of the tank warm-up; review page claude.ai/artifact/76vTtcB67KJNopG3KZu5ca).
|
||||
// What an adopting sponsor sees on each waiting lead: how they got into the tank, how far along they are (New, Warming, Engaged,
|
||||
// Activated, Ready), a 0-100 heat score with its band, and their last real action. The network hub computes it
|
||||
// (POST <hub>/v1/tank/readiness, the one heat formula in network-hub lib/heat.js); this module sends the hub what only this
|
||||
// site knows (its own last sign-in, a linked wallet, and the entry reason from its adoption records and join data) and keeps
|
||||
// the answer in memory for the tank card.
|
||||
//
|
||||
// NO EMAIL, NO MESSAGE, NO SPONSOR CHANGE: read-only here; the hub stores only the entry fact. The hub down = no extras, the tank
|
||||
// card works exactly as before. The same file runs on InstantAdPay and LinkSpin (deps.site names the site; copy changes to both).
|
||||
const crypto = require('crypto');
|
||||
|
||||
const FRESH_MS = 5 * 60 * 1000; // a cached answer this young is used as is
|
||||
const STALE_MS = 6 * 3600 * 1000; // an older one is still shown while a refresh runs, never past this
|
||||
const DOWN_MS = 2 * 60 * 1000; // the hub failed: no new try for this long
|
||||
let R = null; // deps: { site, accounts, tank, followGet(email) }
|
||||
let cache = { at: 0, by: new Map() }; let busy = null; let downUntil = 0; let last = { at: 0, ok: null, n: 0, ms: 0, error: null, recorded: 0 };
|
||||
|
||||
const on = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_ENABLED || '')) && String(process.env.HUB_READINESS || '1') !== '0'
|
||||
&& !!process.env.HUB_URL && String(process.env.HUB_SECRET || '').length >= 32 && typeof fetch === 'function';
|
||||
const lc = v => String(v || '').trim().toLowerCase();
|
||||
function init(deps) { R = deps; }
|
||||
|
||||
async function hubPost(p, body, timeout) {
|
||||
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', process.env.HUB_SECRET).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(String(process.env.HUB_URL).replace(/\/+$/, '') + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': process.env.HUB_SITE || R.site, 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeout || 20000) });
|
||||
let j = null; try { j = await r.json(); } catch (e) {}
|
||||
if (r.status !== 200) throw new Error('hub ' + p + ' ' + r.status + (j && j.error ? ' ' + j.error : ''));
|
||||
return j;
|
||||
}
|
||||
|
||||
// ── how they got into the tank, from this site's own records ──
|
||||
// adoption history (tank.historyMap: newest 6 per person: adopter, ts, status, closed, note), the sponsor-follow record (a move
|
||||
// made on the other platform), and the join data. Sponsor emails never leave the site: a username, or nothing.
|
||||
const ENTRY_STATUS = { rescued: 'rescued', released: 'released', dropped: 'released', expired: 'returned', unreached: 'returned' };
|
||||
const LATER = new Set(['open', 'done', 'invited', 'gift', 'moved', 'conflict']); // a sponsor came after: that entry is over
|
||||
const FOLLOW_BY = { rescue: 'rescued', release: 'released', expire: 'returned', expiry: 'returned' };
|
||||
const IMPORTS = { btc4hits: 'BTC4Hits', faucetwave: 'FaucetWave', socialpix: 'SocialPix' };
|
||||
async function nameOfEmail(email) {
|
||||
if (!email || String(email).startsWith('dead:')) return null;
|
||||
try { const a = await R.accounts.byEmail(lc(email)); return a && a.username ? a.username : null; } catch (e) { return null; }
|
||||
}
|
||||
async function localEntry(a, hist, pv) {
|
||||
const rows = (hist || []).slice().sort((x, y) => (x.closed || x.ts || 0) - (y.closed || y.ts || 0));
|
||||
let best = null;
|
||||
for (const h of rows) {
|
||||
if (ENTRY_STATUS[h.status]) {
|
||||
const dead = h.status === 'rescued' && String(h.adopter || '').startsWith('dead:');
|
||||
best = { reason: dead ? 'sponsor_gone' : ENTRY_STATUS[h.status], at: Number(h.status === 'rescued' || h.status === 'released' ? h.ts : (h.closed || h.ts)) || 0, adopter: h.adopter, status: h.status };
|
||||
} else if (LATER.has(h.status) && best && (h.ts || 0) >= best.at) best = null;
|
||||
}
|
||||
// a move made on the other platform that left them with no sponsor here (sponsorfollow), when newer
|
||||
if (pv && !pv.sponsorEmail && FOLLOW_BY[pv.by] && Number(pv.at) > (best ? best.at : 0)) best = { reason: FOLLOW_BY[pv.by], at: Number(pv.at), adopter: pv.prevEmail || null, site: ({ instantadpay: 'iap', linkspin: 'linkspin' })[lc(pv.origin)] || null };
|
||||
if (best) {
|
||||
const from = best.reason === 'sponsor_gone' ? null : await nameOfEmail(best.adopter);
|
||||
const detail = {}; if (from) detail.from = from;
|
||||
if (best.reason === 'sponsor_gone') detail.note = 'their sponsor link no longer leads to a member';
|
||||
if (best.status === 'dropped') detail.note = 'released by the member who adopted them';
|
||||
return { reason: best.reason, at: best.at, site: best.site || undefined, detail };
|
||||
}
|
||||
const via = lc(a.joinedVia); const ref = lc(a.joinedRef);
|
||||
if (via === 'hub') return null; // made here for someone who joined elsewhere on the network: the hub knows their first door
|
||||
if ((via === 'linkspin' || via === 'instantadpay' || via === 'carried') && ref !== 'btc4hits') return null; // a copy of an account from the other platform (LinkSpin: 'carried'): same, the hub knows
|
||||
const leg = /^legacy:([a-z0-9]+)/.exec(ref);
|
||||
if (via === 'btc4hits' || ref === 'btc4hits') return { reason: 'imported', at: Number(a.created) || 0, detail: { oldSite: 'BTC4Hits' } };
|
||||
if (leg) return { reason: 'imported', at: Number(a.created) || 0, detail: { oldSite: IMPORTS[leg[1]] || leg[1] } };
|
||||
const detail = {}; if (via) detail.via = via; if (ref && !/^hub:/.test(ref)) detail.ref = ref.slice(0, 80);
|
||||
return { reason: 'joined', at: Number(a.created) || 0, detail };
|
||||
}
|
||||
|
||||
// one call for the whole waiting list (a few thousand rows at most)
|
||||
async function refresh() {
|
||||
if (!R || !on()) return null;
|
||||
if (busy) return busy;
|
||||
busy = (async () => {
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const list = await R.tank.waiting();
|
||||
const hist = R.tank.historyMap ? await R.tank.historyMap() : new Map();
|
||||
const accts = new Map();
|
||||
const rows = [];
|
||||
for (const w of list) {
|
||||
const a = (await R.accounts.byEmail(w.email)) || { email: w.email, created: w.joined };
|
||||
accts.set(w.email, a);
|
||||
let pv = null; try { pv = R.followGet ? R.followGet(w.email) : null; } catch (e) {}
|
||||
rows.push({ email: w.email, seenAt: w.lastSeen || 0, wallet: !!w.wallet, entry: await localEntry(a, hist.get(w.email), pv) || undefined });
|
||||
}
|
||||
const r = rows.length ? await hubPost('/v1/tank/readiness', { rows }, 30000) : { rows: [] };
|
||||
const by = new Map();
|
||||
for (const x of (r.rows || [])) { const src = rows[x.i]; if (src) by.set(src.email, { entry: x.entry, stage: x.stage, heat: x.heat, last: x.last, onHub: !!x.onHub }); }
|
||||
cache = { at: Date.now(), by };
|
||||
last = { at: Date.now(), ok: true, n: by.size, ms: Date.now() - t0, error: null, recorded: r.recorded || 0 };
|
||||
return cache;
|
||||
} catch (e) {
|
||||
downUntil = Date.now() + DOWN_MS; last = { at: Date.now(), ok: false, n: 0, ms: Date.now() - t0, error: e.message, recorded: 0 };
|
||||
console.error('tankready', e.message);
|
||||
return null;
|
||||
} finally { busy = null; }
|
||||
})();
|
||||
return busy;
|
||||
}
|
||||
|
||||
// the readiness for these waiting rows, as rows with `rd` added. Waits for the hub only when nothing usable is cached, and then
|
||||
// at most `waitMs`; otherwise answers from the cache and refreshes in the background.
|
||||
async function attach(list, waitMs) {
|
||||
if (!R || !on() || !Array.isArray(list)) return list;
|
||||
const age = Date.now() - cache.at;
|
||||
if (age > FRESH_MS && Date.now() > downUntil) {
|
||||
const p = refresh();
|
||||
if (age > STALE_MS && p) await Promise.race([p, new Promise(res => setTimeout(res, waitMs || 4000))]);
|
||||
}
|
||||
if (Date.now() - cache.at > STALE_MS) return list;
|
||||
return list.map(w => { const x = cache.by.get(w.email); return x ? Object.assign({}, w, { rd: x }) : w; });
|
||||
}
|
||||
|
||||
const status = () => Object.assign({ on: on(), cached: cache.by.size, cachedAt: cache.at || null }, last);
|
||||
// counts for the report: entry reasons and stages across the cached tank
|
||||
function counts() {
|
||||
const reasons = {}; const stages = {}; const bands = {};
|
||||
for (const x of cache.by.values()) { reasons[x.entry.reason] = (reasons[x.entry.reason] || 0) + 1; stages[x.stage] = (stages[x.stage] || 0) + 1; bands[x.heat.band] = (bands[x.heat.band] || 0) + 1; }
|
||||
return { at: cache.at, n: cache.by.size, reasons, stages, bands };
|
||||
}
|
||||
|
||||
module.exports = { init, refresh, attach, status, counts, localEntry, _reset: () => { cache = { at: 0, by: new Map() }; downUntil = 0; busy = null; } };
|
||||
@@ -92,7 +92,7 @@ async function status(email) {
|
||||
const u = usage()[email] || {}; const used = (u.months || {})[monthKey()] || 0;
|
||||
const allowance = allowanceFor(tier, sc); const cost = Number(sc.aiCreditsPerGen) || 10;
|
||||
let available = 0; try { const st = await R.ads.viewStatus(email); available = st.earnedAvailable != null ? st.earnedAvailable : (st.earned || 0); } catch (e) {}
|
||||
const link = 'https://instantadpay.com/join/' + (acct.username || acct.code);
|
||||
const link = SHARE() + '/join/' + (acct.username || acct.code);
|
||||
const partner = tier === 'nexus' ? await partnerStatus(email) : null;
|
||||
const handoutUrl = rank[tier] >= rank.spark && acct.username ? 'https://instantadpay.com/handout/' + acct.username : null;
|
||||
return { tier, badges, username: acct.username || null, partner, handoutUrl, videoMaker: !!(R.videomaker && R.videomaker.available()), unlocked: ['surge', 'circuit', 'nexus'].includes(tier), engine: !!key(), allowance, used, freeLeft: Math.max(0, allowance - used), cost, available, link,
|
||||
@@ -129,6 +129,9 @@ async function adminUsage() {
|
||||
// ---- the rest of the ladder (Marty, 2026-09-14): Spark templates + handout, Circuit split tester + Video
|
||||
// Maker, Nexus Leader Ops + team grants + a member-funded partner code ----
|
||||
const KIT = 'https://instantadpay.com';
|
||||
// member links that get pasted elsewhere go out on the share domain (2026-11-17, Spamhaus DBL: instantadpay.com is listed);
|
||||
// <share>/join/<user> passes through to the join page. shareDomain '' (admin settings) = the old instantadpay.com links.
|
||||
const SHARE = () => { const d = String((R && R.siteConfig && R.siteConfig().shareDomain) || '').trim().toLowerCase(); return /^[a-z0-9.-]+\.[a-z]{2,}$/.test(d) ? 'https://' + d : KIT; };
|
||||
async function tierOf(email) { return tierFor(await R.ads.milestonesOf(email)); }
|
||||
const rank = { free: 0, spark: 1, surge: 2, circuit: 3, nexus: 4 };
|
||||
const atLeast = (tier, need) => rank[tier] >= rank[need];
|
||||
@@ -154,7 +157,7 @@ async function template(email, memberId, ids, kind, budget) {
|
||||
async function handout(username) {
|
||||
const a = await R.accounts.byUsername(username); if (!a) return null;
|
||||
if (!atLeast(await tierOf(a.email), 'spark')) return null;
|
||||
const link = KIT + '/join/' + username; const qr = '/api/qr?d=' + encodeURIComponent(link);
|
||||
const link = SHARE() + '/join/' + username; const qr = '/api/qr?d=' + encodeURIComponent(link);
|
||||
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
return '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>InstantAdPay handout for @' + esc(username) + '</title><meta name="robots" content="noindex">'
|
||||
+ '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">'
|
||||
@@ -168,7 +171,7 @@ async function handout(username) {
|
||||
async function split(email) {
|
||||
const tier = await tierOf(email);
|
||||
const st = await R.coach.linkStats(email);
|
||||
const acct = await R.accounts.byEmail(email); const base = KIT + '/join/' + (acct.username || acct.code);
|
||||
const acct = await R.accounts.byEmail(email); const base = SHARE() + '/join/' + (acct.username || acct.code);
|
||||
const rows = (st.angles || []).map(a => ({ angle: a.angle, link: base + (a.angle && a.angle !== 'plain' ? '?v=' + a.angle : ''), views: a.views || 0, views30: a.views30 || 0, joins: a.joins || 0, buyers: a.buyers || 0, rate: a.views ? Math.round(1000 * (a.joins || 0) / a.views) / 10 : 0 }));
|
||||
const withData = rows.filter(r => r.views >= 10); const best = withData.length ? withData.slice().sort((x, y) => y.rate - x.rate || y.joins - x.joins)[0] : null;
|
||||
return { unlocked: atLeast(tier, 'circuit'), rows, best: best ? best.angle : null, sources: st.sources || [] };
|
||||
@@ -219,12 +222,12 @@ async function partnerCode(email, code, credits) {
|
||||
const r = await R.promos.create({ code, credits: n, funder: email, partner: 'member: ' + email, note: 'member-funded partner code', maxUses: 0, expires: null, active: true });
|
||||
if (r.error) return r;
|
||||
const acct = await R.accounts.byEmail(email);
|
||||
return { ok: true, code: r.code.code, credits: n, link: KIT + '/join/' + (acct.username || acct.code) + '?promo=' + r.code.code, kit: KIT + '/partners?ref=' + (acct.username || acct.code) + '&promo=' + r.code.code };
|
||||
return { ok: true, code: r.code.code, credits: n, link: SHARE() + '/join/' + (acct.username || acct.code) + '?promo=' + r.code.code, kit: SHARE() + '/partners?ref=' + (acct.username || acct.code) + '&promo=' + r.code.code };
|
||||
}
|
||||
async function partnerStatus(email) {
|
||||
const mine = await R.promos.byFunder(email); const acct = await R.accounts.byEmail(email);
|
||||
if (!mine.length) return null; const c = mine[0];
|
||||
return { code: c.code, credits: c.credits, uses: (await R.promos.adminView()).codes.find(x => x.code === c.code)?.uses || 0, link: KIT + '/join/' + (acct.username || acct.code) + '?promo=' + c.code, kit: KIT + '/partners?ref=' + (acct.username || acct.code) + '&promo=' + c.code };
|
||||
return { code: c.code, credits: c.credits, uses: (await R.promos.adminView()).codes.find(x => x.code === c.code)?.uses || 0, link: SHARE() + '/join/' + (acct.username || acct.code) + '?promo=' + c.code, kit: SHARE() + '/partners?ref=' + (acct.username || acct.code) + '&promo=' + c.code };
|
||||
}
|
||||
|
||||
module.exports = { init, status, generate, adminUsage, TIERS, KINDS, template, handout, split, videos, makeVideo, team, nudge, grant, partnerCode, partnerStatus };
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// Renders the 600x300 ("wide") and 250x250 ("small") promo kit cards (member request, Marty 2026-11-18) for each display
|
||||
// design the kit already has: the core "Advertise & earn" card, the advertise-and-earn globe art (small only: its 600x300
|
||||
// already exists), the ledger card, the team-build link card (also a 300x250 box), Wired Wednesday and Five Dollar Friday.
|
||||
// Run from the site dir with the qa-tester playwright: node tools/gen-card-banners.cjs
|
||||
// Output: public/banners/iap-<design>-<wide|small>.png (exact pixel sizes, DSF 1). Neutral names: no size tokens.
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { chromium } = require('D:/Projects/MarketingAgent/qa-tester/node_modules/playwright');
|
||||
|
||||
const PUB = path.join(__dirname, '..', 'public');
|
||||
const OUT = path.join(PUB, 'banners');
|
||||
const uri = (f, t) => 'data:image/' + t + ';base64,' + fs.readFileSync(path.join(PUB, f)).toString('base64');
|
||||
const LOGO = uri('logo.png', 'png'), ICON = uri('logo-icon.png', 'png');
|
||||
const GLOBE = uri('banners/iap-advertise-earn-600x300.png', 'png'); // the licensed globe art, right half of the existing wide card
|
||||
|
||||
const FONT = '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600;700;800&display=block">';
|
||||
const CSS = `*{box-sizing:border-box;margin:0}html,body{width:var(--w);height:var(--h);overflow:hidden}
|
||||
body{font-family:"Sora","Segoe UI",system-ui,sans-serif;color:#eef7f3;position:relative;
|
||||
background:radial-gradient(120% 90% at 8% 0%,#16352c 0%,#0b1512 58%,#07100d 100%)}
|
||||
.lines{position:absolute;inset:0;background:repeating-linear-gradient(0deg,rgba(67,232,195,.06) 0 1px,transparent 1px 26px)}
|
||||
.glow{position:absolute;right:-20%;top:-25%;width:75%;height:80%;border-radius:50%;background:radial-gradient(circle,rgba(67,232,195,.16),transparent 62%)}
|
||||
.wrap{position:absolute;inset:0;display:flex;flex-direction:column}
|
||||
h1{font-weight:800;letter-spacing:-.02em;line-height:1.04}h1 em{font-style:normal;color:#43e8c3}
|
||||
p{color:#a9c4ba;line-height:1.35}
|
||||
.cta{display:inline-block;background:#43e8c3;color:#03211a;font-weight:800;border-radius:999px;white-space:nowrap}
|
||||
.cta.amber{background:#ffb02e;color:#2a1700}
|
||||
.url{font-weight:700;color:#8ba69c;white-space:nowrap}
|
||||
.tag{display:inline-block;border:1px solid rgba(67,232,195,.45);color:#43e8c3;border-radius:999px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;white-space:nowrap}
|
||||
.disc{display:grid;place-items:center;border-radius:50%;background:linear-gradient(160deg,#43e8c3,#1fb894);color:#03211a;font-weight:800}
|
||||
.circuit{position:absolute;inset:0;opacity:.5}
|
||||
img.logo{display:block;mix-blend-mode:lighten}`;
|
||||
|
||||
const CIRCUIT = (w, h) => `<svg class="circuit" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none"><g stroke="#1f6b55" stroke-width="1.2" fill="none"><path d="M0 ${h * .78} H${w * .22} L${w * .3} ${h * .7} H${w * .5}"/><path d="M${w} ${h * .66} H${w * .8} L${w * .72} ${h * .74} H${w * .55}"/></g><g fill="#2a8a6d"><circle cx="${w * .5}" cy="${h * .7}" r="3"/><circle cx="${w * .55}" cy="${h * .74}" r="3"/></g></svg>`;
|
||||
const BOLT = s => `<svg width="${s * .46}" height="${s * .46}" viewBox="0 0 24 24"><path d="M13 2 4 14h7l-1 8 9-12h-7z" fill="#03211a"/></svg>`;
|
||||
|
||||
const D = {
|
||||
core: {
|
||||
wide: () => `<div class="lines"></div><div class="glow"></div><div class="wrap" style="padding:30px 34px;justify-content:space-between">
|
||||
<img class="logo" src="${LOGO}" style="height:44px;align-self:flex-start">
|
||||
<div><h1 style="font-size:46px">Advertise <em>& earn.</em></h1><p style="font-size:17px;margin-top:10px;max-width:440px">Paid on-chain, instantly. Every payout sits on a public ledger.</p></div>
|
||||
<div style="display:flex;align-items:center;gap:18px"><span class="cta" style="font-size:19px;padding:12px 28px">Join free →</span><span class="url" style="font-size:15px">instantadpay.com</span></div></div>
|
||||
<img src="${ICON}" style="position:absolute;right:34px;top:30px;width:92px;height:92px;border-radius:20px;opacity:.95">`,
|
||||
small: () => `<div class="lines"></div><div class="glow"></div><div class="wrap" style="padding:20px;align-items:center;text-align:center;justify-content:space-between">
|
||||
<img src="${ICON}" style="width:62px;height:62px;border-radius:14px">
|
||||
<div><h1 style="font-size:31px">Advertise<br><em>& earn.</em></h1><p style="font-size:13px;margin-top:6px">Paid on-chain, instantly.</p></div>
|
||||
<span class="cta" style="font-size:16px;padding:9px 24px">Join free →</span></div>`
|
||||
},
|
||||
earn: {
|
||||
small: () => `<div style="position:absolute;inset:0;background:url(${GLOBE}) right center/auto 100% no-repeat"></div>
|
||||
<div style="position:absolute;inset:0;background:linear-gradient(180deg,rgba(7,16,13,.92) 0%,rgba(7,16,13,.55) 48%,rgba(7,16,13,.9) 100%)"></div>
|
||||
<div class="wrap" style="padding:18px;justify-content:space-between">
|
||||
<img class="logo" src="${LOGO}" style="height:34px;align-self:flex-start">
|
||||
<h1 style="font-size:33px">Advertise<br><em>& earn.</em></h1>
|
||||
<div><p style="font-size:13px;color:#d6efe6;margin-bottom:10px">Paid on-chain, instantly.</p><span class="cta" style="font-size:16px;padding:9px 22px">Join free →</span></div></div>`
|
||||
},
|
||||
ledger: {
|
||||
wide: () => `<div class="lines"></div><div class="glow"></div>${CIRCUIT(600, 300)}<div class="wrap" style="padding:30px 34px;justify-content:space-between">
|
||||
<img class="logo" src="${LOGO}" style="height:42px;align-self:flex-start">
|
||||
<div><h1 style="font-size:40px">Advertising that<br><em>pays you on-chain.</em></h1><p style="font-size:15px;margin-top:8px">Every ad package splits to real wallets, on a public ledger.</p></div>
|
||||
<div style="display:flex;align-items:center;gap:18px"><span class="cta" style="font-size:18px;padding:11px 26px">See the ledger →</span><span class="url" style="font-size:15px">instantadpay.com</span></div></div>`,
|
||||
small: () => `<div class="lines"></div><div class="glow"></div>${CIRCUIT(250, 250)}<div class="wrap" style="padding:20px;justify-content:space-between">
|
||||
<img class="logo" src="${LOGO}" style="height:32px;align-self:flex-start">
|
||||
<h1 style="font-size:29px">Advertising that <em>pays you on-chain.</em></h1>
|
||||
<span class="cta" style="font-size:16px;padding:9px 20px;align-self:flex-start">See the ledger →</span></div>`
|
||||
},
|
||||
team: { // the team-build link card (Marty 2026-11-18: replaces the old 300x250 tiers infographic). Mechanic: whoever opens
|
||||
// a member's invite link is tagged to them, and the sponsor locks when the account is created (chatbot "sponsor" entry).
|
||||
wide: () => `<div class="lines"></div><div class="glow"></div>${CIRCUIT(600, 300)}<div class="wrap" style="padding:28px 34px;justify-content:space-between">
|
||||
<img class="logo" src="${LOGO}" style="height:42px;align-self:flex-start">
|
||||
<div><h1 style="font-size:42px">Build your team<br><em>with one link.</em></h1><p style="font-size:15px;margin-top:8px">Everyone who joins through your invite link is placed in your team line.</p></div>
|
||||
<div style="display:flex;align-items:center;gap:18px"><span class="cta" style="font-size:18px;padding:11px 26px">Join free →</span><span class="url" style="font-size:12.5px;white-space:nowrap">Ad credits buy advertising, not income.</span></div></div>`,
|
||||
box: () => `<div class="lines"></div><div class="glow"></div>${CIRCUIT(300, 250)}<div class="wrap" style="padding:20px 22px;justify-content:space-between">
|
||||
<img class="logo" src="${LOGO}" style="height:32px;align-self:flex-start">
|
||||
<div><h1 style="font-size:29px">Build your team <em>with one link.</em></h1><p style="font-size:12.5px;margin-top:7px">Everyone who joins through your link is placed in your team line.</p></div>
|
||||
<span class="cta" style="font-size:16px;padding:9px 22px;align-self:flex-start">Join free →</span></div>`,
|
||||
small: () => `<div class="lines"></div><div class="glow"></div>${CIRCUIT(250, 250)}<div class="wrap" style="padding:20px;justify-content:space-between">
|
||||
<img class="logo" src="${LOGO}" style="height:32px;align-self:flex-start">
|
||||
<h1 style="font-size:31px">One link.<br><em>Your team.</em></h1>
|
||||
<span class="cta" style="font-size:16px;padding:9px 22px;align-self:flex-start">Join free →</span></div>`
|
||||
},
|
||||
'wired-wednesday': {
|
||||
wide: () => `<div class="lines"></div><div class="glow"></div>${CIRCUIT(600, 300)}<div class="wrap" style="padding:30px 34px;justify-content:center;gap:16px">
|
||||
<div style="display:flex;align-items:center;gap:16px"><div class="disc" style="width:64px;height:64px">${BOLT(64)}</div><h1 style="font-size:46px">Wired <em>Wednesday</em></h1></div>
|
||||
<p style="font-size:19px;color:#d6efe6;max-width:500px">+25% credits on any $20+ ad pack, wired in the second it settles. Every Wednesday.</p>
|
||||
<div style="display:flex;align-items:center;gap:18px"><span class="cta amber" style="font-size:18px;padding:11px 28px">Join free</span><span class="url" style="font-size:15px">instantadpay.com</span></div></div>`,
|
||||
small: () => `<div class="lines"></div><div class="glow"></div>${CIRCUIT(250, 250)}<div class="wrap" style="padding:18px;align-items:center;text-align:center;justify-content:space-between">
|
||||
<div class="disc" style="width:50px;height:50px">${BOLT(50)}</div>
|
||||
<div><h1 style="font-size:28px">Wired <em>Wednesday</em></h1><p style="font-size:13px;color:#d6efe6;margin-top:6px">+25% credits on $20+ packs</p></div>
|
||||
<span class="cta amber" style="font-size:16px;padding:9px 24px">Join free</span></div>`
|
||||
},
|
||||
'five-dollar-friday': {
|
||||
wide: () => `<div class="lines"></div><div class="glow"></div><div class="wrap" style="padding:30px 34px;justify-content:center;gap:16px">
|
||||
<div style="display:flex;align-items:center;gap:16px"><div class="disc" style="width:66px;height:66px;font-size:30px">$5</div><h1 style="font-size:46px">Five Dollar <em>Friday</em></h1></div>
|
||||
<p style="font-size:19px;color:#d6efe6;max-width:500px">+20% credits on any $5+ ad pack, every Friday. Every pack pays its line on chain.</p>
|
||||
<div style="display:flex;align-items:center;gap:18px"><span class="cta" style="font-size:18px;padding:11px 28px">Join free</span><span class="url" style="font-size:15px">instantadpay.com</span></div></div>`,
|
||||
small: () => `<div class="lines"></div><div class="glow"></div><div class="wrap" style="padding:18px;align-items:center;text-align:center;justify-content:space-between">
|
||||
<div class="disc" style="width:52px;height:52px;font-size:23px">$5</div>
|
||||
<div><h1 style="font-size:27px">Five Dollar <em>Friday</em></h1><p style="font-size:13px;color:#d6efe6;margin-top:6px">+20% credits on $5+ packs</p></div>
|
||||
<span class="cta" style="font-size:16px;padding:9px 24px">Join free</span></div>`
|
||||
}
|
||||
};
|
||||
const SIZE = { wide: [600, 300], small: [250, 250], box: [300, 250] };
|
||||
|
||||
const ONLY = (process.argv[2] || '').split(',').filter(Boolean); // e.g. node tools/gen-card-banners.cjs team
|
||||
(async () => {
|
||||
const browser = await chromium.launch();
|
||||
for (const [design, shapes] of Object.entries(D)) if (!ONLY.length || ONLY.includes(design)) for (const [shape, body] of Object.entries(shapes)) {
|
||||
const [w, h] = SIZE[shape];
|
||||
const page = await browser.newPage({ viewport: { width: w, height: h }, deviceScaleFactor: 1 });
|
||||
await page.setContent(`<!doctype html><html><head><meta charset="utf-8">${FONT}<style>:root{--w:${w}px;--h:${h}px}${CSS}</style></head><body>${body()}</body></html>`, { waitUntil: 'networkidle' });
|
||||
await page.evaluate(async () => { await document.fonts.ready; await document.fonts.load('800 20px Sora'); await document.fonts.load('400 20px Sora'); });
|
||||
await page.waitForFunction(() => [...document.images].every(i => i.complete && i.naturalWidth > 0));
|
||||
await page.waitForTimeout(300);
|
||||
const file = path.join(OUT, `iap-${design}-${shape}.png`);
|
||||
await page.screenshot({ path: file, clip: { x: 0, y: 0, width: w, height: h } });
|
||||
console.log('wrote', file);
|
||||
await page.close();
|
||||
}
|
||||
await browser.close();
|
||||
})();
|
||||