Compare commits
43 Commits
dh-networksso
...
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 | |||
| 1a13f53b9c | |||
| ad533a0d56 | |||
| 3a00ddf3dc | |||
| 6ef7a023df | |||
| 84d566e784 | |||
| b925661eac | |||
| dd50674d96 | |||
| ea07861b36 |
@@ -160,7 +160,7 @@ const J = {
|
|||||||
return Object.values(this.db.byEmail)
|
return Object.values(this.db.byEmail)
|
||||||
.filter(a => set.has(String(a.sponsorRef || '')))
|
.filter(a => set.has(String(a.sponsorRef || '')))
|
||||||
.sort((a, b) => b.created - a.created)
|
.sort((a, b) => b.created - a.created)
|
||||||
.slice(0, 200).map(pub);
|
.slice(0, 2000).map(pub);
|
||||||
},
|
},
|
||||||
async linkWallet(e, a) {
|
async linkWallet(e, a) {
|
||||||
const acct = this.db.byEmail[e];
|
const acct = this.db.byEmail[e];
|
||||||
@@ -329,7 +329,7 @@ const D = {
|
|||||||
const clean = refs.filter(Boolean).map(String);
|
const clean = refs.filter(Boolean).map(String);
|
||||||
if (!clean.length) return [];
|
if (!clean.length) return [];
|
||||||
const rows = await db.q('SELECT * FROM accounts WHERE sponsor_ref IN (' + clean.map(() => '?').join(',')
|
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);
|
return rows.map(rowPub);
|
||||||
},
|
},
|
||||||
async linkWallet(e, a) {
|
async linkWallet(e, a) {
|
||||||
@@ -501,14 +501,20 @@ async function sponsorOf(email) {
|
|||||||
let s = null;
|
let s = null;
|
||||||
try { s = await byCode(ref); } catch (e) {}
|
try { s = await byCode(ref); } catch (e) {}
|
||||||
if (!s) { try { s = await byUsername(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;
|
return s || null;
|
||||||
}
|
}
|
||||||
// is `memberEmail` anywhere in `sponsorEmail`'s downline (to `depth` levels)?
|
// 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) {
|
async function isDownlineOf(sponsorEmail, memberEmail, depth = 3) {
|
||||||
const target = String(memberEmail || '').toLowerCase();
|
const want = String(sponsorEmail || '').toLowerCase(); let cur = String(memberEmail || '').toLowerCase();
|
||||||
const levels = await downline(sponsorEmail, depth);
|
if (!want || !cur || want === cur) return false;
|
||||||
return levels.some(L => L.members.some(m => String(m.email || '').toLowerCase() === target));
|
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) {
|
async function getChatSettings(email) {
|
||||||
const a = await byEmail(email);
|
const a = await byEmail(email);
|
||||||
|
|||||||
@@ -26,7 +26,10 @@ function rates() {
|
|||||||
try { saved = JSON.parse(fs.readFileSync(RATES_FILE(), 'utf8')); } catch (e) {}
|
try { saved = JSON.parse(fs.readFileSync(RATES_FILE(), 'utf8')); } catch (e) {}
|
||||||
return Object.assign({
|
return Object.assign({
|
||||||
bannerBatch: 10, bannerCreditsPerBatch: 2,
|
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
|
// 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
|
// 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.
|
// 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
|
// 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
|
// 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.
|
// 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);
|
}, saved);
|
||||||
}
|
}
|
||||||
function setRates(patch) {
|
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
|
// 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);
|
const creditsDue = Math.floor(st.served / ipc) - Math.floor(prev / ipc);
|
||||||
if (creditsDue > 0) {
|
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;
|
charged = res.charged || 0;
|
||||||
if (res.exhausted) { exhausted = true; await setNasServed(c.id, st.served); await stopNas(c.id, c.nasAdId); }
|
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.sessions.set(token, Object.assign({}, s, fields));
|
||||||
this.save();
|
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 ----
|
// ---- MySQL session mode ----
|
||||||
@@ -84,7 +86,9 @@ const D = {
|
|||||||
vals.push(token);
|
vals.push(token);
|
||||||
await db.q('UPDATE sessions SET ' + sets.join(',') + ' WHERE token=?', vals);
|
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;
|
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 mintSession(fields) { return impl().mint(fields || {}); }
|
||||||
async function updateSession(token, fields) { return impl().update(token, fields || {}); }
|
async function updateSession(token, fields) { return impl().update(token, fields || {}); }
|
||||||
function sessionCookie(token) {
|
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'; }
|
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
|
// 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 || '');
|
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
|
||||||
if (!m) return null;
|
if (!m) return null;
|
||||||
const s = await impl().get(decodeURIComponent(m[1]));
|
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) {} }
|
if (s && s.email && seenFn) { try { seenFn(s.email, req); } catch (e) {} }
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
@@ -177,4 +184,5 @@ async function logout(req) {
|
|||||||
if (s) await impl().drop(s.token);
|
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">';
|
+ '</head><body><div class="wrap bl">';
|
||||||
}
|
}
|
||||||
function tail() {
|
function tail() {
|
||||||
return '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20261101th"></script></body></html>';
|
return '</div><script src="/assets/common.js?v=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 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>';
|
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>';
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ const https = require('https');
|
|||||||
const http = require('http');
|
const http = require('http');
|
||||||
const kb = require('./kb');
|
const kb = require('./kb');
|
||||||
const kbSeed = require('./kb-seed');
|
const kbSeed = require('./kb-seed');
|
||||||
|
const netkb = require('./netkb'); // the shared network knowledge base on the hub (2026-11-15): publishes this site's entries, reads the other sites'
|
||||||
|
|
||||||
let DATA_DIR = null;
|
let DATA_DIR = null;
|
||||||
let chain = null;
|
let chain = null;
|
||||||
@@ -23,10 +24,25 @@ 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
|
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';
|
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) {
|
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.gameLive === 'function') GAME_LIVE = opts.gameLive;
|
||||||
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn;
|
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn;
|
||||||
if (opts && typeof opts.bixLive === 'function') BIX_LIVE = opts.bixLive; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; HERO_SALE = typeof opts.heroSale === 'function' ? opts.heroSale : null; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
|
if (opts && typeof opts.bixLive === 'function') BIX_LIVE = opts.bixLive; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; HERO_SALE = typeof opts.heroSale === 'function' ? opts.heroSale : null; const ready = kb.init({ dataDir: DATA_DIR, seeds: seeds() });
|
||||||
|
netkb.init({ dataDir: DATA_DIR, site: process.env.HUB_SITE || 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com', entries: () => kb.own(), linkFor: netLink });
|
||||||
|
return ready; }
|
||||||
|
// the link to another network site: its LinkSpin tracked link with ?src=iap (netsites.js), else its plain address
|
||||||
|
function netLink(url) {
|
||||||
|
try { const ns = require('./netsites'); const h = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||||
|
const m = ns.list().concat(ns.FALLBACK || []).find(x => h(x.url) === h(url)); return (m && m.id !== 'iap' && ns.tracked(m.id, 'iap')) || url; } catch (e) { return url; }
|
||||||
|
}
|
||||||
|
// the other network sites for the system prompt (from the hub's merged set)
|
||||||
|
function networkBlock() {
|
||||||
|
const l = netkb.sites(); if (!l.length) return '';
|
||||||
|
return '\n- OTHER NETWORK SITES (one network account works across them): ' + l.map(x => x.name + ' ' + x.go).join('; ') + '. A question about one of them: answer from its KNOWLEDGE BASE entries below, say which site it is about, give its link exactly as shown, and never mix two sites\' prices, splits or rules. Wallets: say "SafePal or any other crypto wallet". Ad credits buy advertising, not income. Never mention RM Circle.';
|
||||||
|
}
|
||||||
function key() {
|
function key() {
|
||||||
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
|
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
|
||||||
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
|
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
|
||||||
@@ -34,13 +50,13 @@ function key() {
|
|||||||
function enabled() { return !!key(); }
|
function enabled() { return !!key(); }
|
||||||
|
|
||||||
// ---- canned answers: instant, free, always in voice ----
|
// ---- canned answers: instant, free, always in voice ----
|
||||||
const KNOWLEDGE_DATE = '2026-11-14'; // bump whenever the canned answers / prompt are brought up to date
|
const KNOWLEDGE_DATE = '2026-11-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 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 = [
|
const CANNED = [
|
||||||
// network sign-in (2026-11-12): signed in on one of InstantAdPay / LinkSpin = signed in on the other, no code (networksso.js)
|
// 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'],
|
{ 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,
|
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
|
// 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)
|
// 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'],
|
{ 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'],
|
||||||
@@ -138,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.' },
|
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'],
|
{ 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,
|
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'],
|
{ 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,
|
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.' },
|
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.' },
|
||||||
@@ -159,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.' },
|
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
|
// 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.
|
// 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,
|
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'],
|
{ 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,
|
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.' },
|
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.' },
|
||||||
@@ -178,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.' },
|
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'],
|
{ 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,
|
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'],
|
{ 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,
|
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.' },
|
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.' },
|
||||||
@@ -198,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'],
|
{ 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,
|
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.' },
|
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'],
|
{ 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,
|
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.' },
|
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.' },
|
||||||
@@ -207,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'],
|
{ 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,
|
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.' },
|
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'],
|
{ 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,
|
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.' },
|
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.' },
|
||||||
@@ -230,10 +258,10 @@ 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.' },
|
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'],
|
{ 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,
|
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'],
|
{ 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,
|
re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
|
||||||
a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (MetaMask, Phantom, SafePal have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again. Phantom, SafePal and MetaMask do not have the hard block.' },
|
a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (SafePal and most other wallets have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again.' },
|
||||||
{ id: 'prohibited-content', title: 'What content is not allowed?', q: ['What content is not allowed?', 'Can I put a link in my bio?', 'Can I advertise a casino or CBD?'], tags: ['prohibited content', 'rules', 'bio links', 'gambling', 'adult', 'link farm'],
|
{ id: 'prohibited-content', title: 'What content is not allowed?', q: ['What content is not allowed?', 'Can I put a link in my bio?', 'Can I advertise a casino or CBD?'], tags: ['prohibited content', 'rules', 'bio links', 'gambling', 'adult', 'link farm'],
|
||||||
re: /(not allowed|prohibited|forbidden|banned (content|words|niches?)|content (rules|policy)|what (content|ads|niches?) (is|are) (not )?(allowed|ok|accepted)|can i (post|promote|advertise|run) .*(casino|gambling|betting|adult|porn|cbd|weed|pharma|guns?)|link ?farm|backlinks?|links? in (the |my |your )?bio|bio (link|url)|why was my (bio|profile|link) (refused|rejected|blocked))/i,
|
re: /(not allowed|prohibited|forbidden|banned (content|words|niches?)|content (rules|policy)|what (content|ads|niches?) (is|are) (not )?(allowed|ok|accepted)|can i (post|promote|advertise|run) .*(casino|gambling|betting|adult|porn|cbd|weed|pharma|guns?)|link ?farm|backlinks?|links? in (the |my |your )?bio|bio (link|url)|why was my (bio|profile|link) (refused|rejected|blocked))/i,
|
||||||
a: 'Not allowed anywhere on InstantAdPay (ads, campaigns, line banners, wall offers, bios and social links): gambling, casinos, betting, lotteries and sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing and counterfeit goods; misleading financial promises. The bio is text only: no links and no domain names, links go in the social fields in Profile. Your bio, avatar and social links show on your public wall once you have bought a package; free accounts show only their name and the line’s ads there. Accounts created just to place links in profile fields (link farming) are removed without notice, with their profile text. The full list is in the Terms, section 8: https://instantadpay.com/terms#prohibited' },
|
a: 'Not allowed anywhere on InstantAdPay (ads, campaigns, line banners, wall offers, bios and social links): gambling, casinos, betting, lotteries and sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing and counterfeit goods; misleading financial promises. The bio is text only: no links and no domain names, links go in the social fields in Profile. Your bio, avatar and social links show on your public wall once you have bought a package; free accounts show only their name and the line’s ads there. Accounts created just to place links in profile fields (link farming) are removed without notice, with their profile text. The full list is in the Terms, section 8: https://instantadpay.com/terms#prohibited' },
|
||||||
@@ -269,10 +297,10 @@ const CANNED = [
|
|||||||
a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' },
|
a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' },
|
||||||
{ id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Do you accept other coins?'], tags: ['pol', 'polygon', 'crypto', 'network'],
|
{ id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Do you accept other coins?'], tags: ['pol', 'polygon', 'crypto', 'network'],
|
||||||
re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
|
re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
|
||||||
a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Any Polygon wallet works (MetaMask, SafePal, Phantom, Coinbase Wallet), and you can buy POL with a card from Buy packages if you have never held crypto.' },
|
a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Use SafePal or any other crypto wallet on Polygon, and you can buy POL with a card from Buy packages if you have never held crypto.' },
|
||||||
{ id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'metamask', 'safepal', 'phantom', 'moonpay', 'buy pol'],
|
{ id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'metamask', 'safepal', 'phantom', 'moonpay', 'buy pol'],
|
||||||
re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i,
|
re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i,
|
||||||
a: 'Preferred wallets: MetaMask (recommended, and the one for Qualified Start extra accounts), Phantom (turn Polygon on first: Settings, Active Networks), SafePal or Coinbase Wallet. Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' },
|
a: 'Use SafePal or any other crypto wallet on Polygon (in Phantom, turn Polygon on first: Settings, Active Networks). Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' },
|
||||||
{ id: 'safe', title: 'Is it safe? What if the company disappears?', q: ['Is this safe?', 'Can you run away with the money?', 'What if the company disappears?'], tags: ['safe', 'contract', 'trust', 'custody'],
|
{ id: 'safe', title: 'Is it safe? What if the company disappears?', q: ['Is this safe?', 'Can you run away with the money?', 'What if the company disappears?'], tags: ['safe', 'contract', 'trust', 'custody'],
|
||||||
re: /(safe|trust|rug|run away|company disappear)/i,
|
re: /(safe|trust|rug|run away|company disappear)/i,
|
||||||
a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' }
|
a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' }
|
||||||
@@ -310,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
|
// 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 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.'
|
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.';
|
: '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 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); }
|
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)
|
// 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;
|
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
|
// POL Miner (2026-10-28) follows site config gamesLive: until 'polminer' is in it the assistant only says it is coming soon
|
||||||
@@ -356,31 +384,33 @@ function systemPrompt(kbBlock) {
|
|||||||
|
|
||||||
FACTS:
|
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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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).
|
- INVITE PAGES: a member's link instantadpay.com/join/<username> opens a lead-capture page (email first, wallet later); add ?v=instant|adspend|free|ledger|two|wide|play for an angle-matched headline (?v=wide: 'Width unlocks depth.', opens on the Build Wide video, vertical on phones). New free members get a short getting-started email series over the first week (unsubscribe link in every email; the admin edits the sequence in /admin > Settings).
|
||||||
- WALLET DRAIN WARNING: Trust Wallet hard-blocks any purchase that spends most of the wallet's POL ("this transaction will drain your wallet", only "Stop and go back"). It is a balance-proportion heuristic, not a contract issue (there are no token approvals; a buy is one native-POL payable call). Advice: smaller package first, or add POL so the buy is well under half the balance, or use MetaMask/Phantom/SafePal (no hard block). The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again.
|
- WALLET DRAIN WARNING: Trust Wallet hard-blocks any purchase that spends most of the wallet's POL ("this transaction will drain your wallet", only "Stop and go back"). It is a balance-proportion heuristic, not a contract issue (there are no token approvals; a buy is one native-POL payable call). Advice: smaller package first, or add POL so the buy is well under half the balance, or use SafePal or another wallet without the hard block. The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again.
|
||||||
- WALL OWNERSHIP LADDER: the public wall has 3 positions. Position 1 = the member's line banner. Positions 2 and 3 show upline banners (then house ads) UNTIL the member earns them: 2 qualifying buyers ($20+) unlock position 2, 5 unlock position 3; a fully qualified member's wall is 100% their own links/offers (set in Profile > Your wall: label, https link, optional banner image). Empty unlocked slots fall back to upline banners, then house ads.
|
- 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.
|
- 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.
|
- 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.
|
- Live formats: display banners (per impression), text ads (per impression), full-screen LOGIN ADS (per day: right after a member signs in they land on a sponsor interstitial — they click "Open Ad", the advertiser's page opens in a NEW tab, a countdown runs on the interstitial, and at zero a "Go to dashboard" button appears. Just a CTA link is enough; an optional banner image can be the clickable creative. No framing requirement since it opens in its own tab), WATCH-TO-EARN VIDEO ADS (advertiser uploads an MP4/WebM or gives a direct https .mp4/.webm link and picks a required watch length — 10s/30s/60s — which sets the per-view price; viewers watch in an escape-proof player under Earn credits > Watch videos, the watch time is enforced on the server clock, and they earn credits per completed watch; you never see your own videos), and solo ads. Banner ads also require a size (standard IAB sizes like 728x90, 300x250). Video watching is capped at 8 a day per member and pays 1, 2 or 4 credits for a 10, 30 or 60 second watch. FEATURED LINKS (live): a headline + link in the Featured strip at the top of every member's Overview, booked for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead, at most 10 links sharing any day; flat buy paid when booked; the row shows days left and 'runs through <date>', counts views (one per viewer per hour) and clicks, and offers Extend run. VERIFIED-VISIT PACKS (live): 3 credits per visit, minimum 20 visits, paid up front; each visit is a distinct member who opens the site in a new tab, stays 8 seconds and passes a check, at most 20 visits per member per day; the row shows 'N of M visits delivered' and Buy more visits adds to the pack; the visitor earns 1 credit.
|
||||||
- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): preferred MetaMask (recommended; extra accounts for Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase.
|
- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): say "SafePal or any other crypto wallet" and never recommend MetaMask by name (Marty 2026-11-13; a wallet app with several accounts serves Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase.
|
||||||
- PROHIBITED CONTENT (2026-10-30, Terms section 8, /terms#prohibited): gambling, casinos, betting, lotteries, sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing, counterfeit goods; misleading financial promises. Refused at save time in bios, social links, line banners, wall offers and every campaign field. A bio may not contain a URL or a domain (links go in the social fields). Profile text, avatar and social links appear on the public wall ONLY for members who have bought a package; a free account's wall shows the name, the line's ads and the join button. Link-farm accounts (created to plant links in profile fields) are removed without notice with their profile text.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
||||||
@@ -450,15 +480,17 @@ ${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.
|
- 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.
|
- 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.
|
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:
|
RULES:
|
||||||
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page, and only URLs from the PAGES list above.
|
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page, and only URLs from the PAGES list above or a network site's link from the KNOWLEDGE BASE.
|
||||||
- Never send someone to a warning, notice, guide, document or page section that is not named above. Saying "read the full warning on your training page" invents something that does not exist and the member will go looking for it. If the answer is not on a page in the PAGES list, give the answer here or say you are not sure and point to /contract, the ledger, or their sponsor.
|
- Never send someone to a warning, notice, guide, document or page section that is not named above. Saying "read the full warning on your training page" invents something that does not exist and the member will go looking for it. If the answer is not on a page in the PAGES list, give the answer here or say you are not sure and point to /contract, the ledger, or their sponsor.
|
||||||
- Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes.
|
- Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes.
|
||||||
- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen.
|
- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen.
|
||||||
- No em dashes. If you do not know, say so and point to /contract or the ledger.
|
- No em dashes. If you do not know, say so and point to /contract or the ledger.
|
||||||
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : '');
|
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.${networkBlock()}` + (kbBlock ? '\n\n' + kbBlock : '');
|
||||||
}
|
}
|
||||||
|
|
||||||
// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai
|
// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai
|
||||||
@@ -510,9 +542,23 @@ async function answer(message, historyText) { const r = await answerRaw(message,
|
|||||||
async function answerRaw(message, historyText) {
|
async function answerRaw(message, historyText) {
|
||||||
const msg = String(message || '').trim();
|
const msg = String(message || '').trim();
|
||||||
if (!msg) return { error: 'Say something first.' };
|
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
|
// 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 { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
try {
|
||||||
|
await kb.load();
|
||||||
|
// another network site named (and this one not): this site's instant answers stand aside, except a hand-off (2026-11-15)
|
||||||
|
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 === '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 === '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 };
|
if (hit && (hit.id === 'turkeydrop' || hit.id === 'c-turkeydrop') && !tdLive()) return { reply: tdAnswer(), canned: true, kb: hit.id };
|
||||||
@@ -521,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 && (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 && 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 && (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 } : {});
|
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)
|
// retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far)
|
||||||
let kbBlock = '', kbIds = [];
|
let kbBlock = '', kbIds = [];
|
||||||
try {
|
try {
|
||||||
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
|
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
|
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);
|
kbBlock = kb.promptBlock(hitsOk); kbIds = hitsOk.map(h => h.entry.id);
|
||||||
} catch (e) { console.error('kb search', e.message); }
|
} 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; }
|
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 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 COLUMN username VARCHAR(30) NULL');
|
||||||
await alterSafe('ALTER TABLE accounts ADD UNIQUE KEY uq_username (username)');
|
await alterSafe('ALTER TABLE accounts ADD UNIQUE KEY uq_username (username)');
|
||||||
await alterSafe('ALTER TABLE accounts ADD COLUMN member_id INT NULL');
|
await alterSafe('ALTER TABLE accounts ADD COLUMN member_id INT NULL');
|
||||||
|
|||||||
@@ -188,4 +188,5 @@ async function claim(key) {
|
|||||||
// SIGTERM during a deploy: write what is pending, then exit
|
// SIGTERM during a deploy: write what is pending, then exit
|
||||||
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
|
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
|
||||||
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
|
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
|
||||||
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };
|
const names = () => [...cache.keys()]; // every document name (the member erase walks them all, 2026-11-15)
|
||||||
|
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim, names };
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
// and someone on this contract in their line (tank.partnerEligibility); free members cannot adopt
|
// 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
|
// - 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
|
// 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
|
// - 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
|
// 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
|
// - 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
|
) 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 ----
|
// ---- signature ----
|
||||||
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('draft.v1.' + ts + '\n' + raw).digest('hex'); }
|
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('draft.v1.' + ts + '\n' + raw).digest('hex'); }
|
||||||
|
|||||||
@@ -0,0 +1,199 @@
|
|||||||
|
// Member erase (Marty 2026-11-15, ticket LS-1021: "I want delete my account data from all your sites"). One named admin action
|
||||||
|
// that takes a person out of InstantAdPay from INSIDE the running app, so the documents the modules keep in memory and the MySQL
|
||||||
|
// rows stay consistent (an edit straight in the database would be written back over by the next save).
|
||||||
|
// POST /api/admin/erase {email, dryRun (default true), force} (admin) and the hub's member.erased event (hubsync.js)
|
||||||
|
// Refused unless force: a linked main wallet, an on-chain member number, linked positions, anyone sponsored under them here,
|
||||||
|
// an ad still running or queued (stop it first: skill iap-kill-ad). What goes:
|
||||||
|
// - the account, sessions, signals, credits (unspent ad credits simply go away), credit log, views, visits, drips, nudges,
|
||||||
|
// digests, adoptions (as adoptee or adopter), marks, promo redemptions, prospects and pipeline notes, their ads with every
|
||||||
|
// row that hangs off them (hours, countries, clicks, inbox deliveries, visits, reports);
|
||||||
|
// - messages: everything they sent; notices and broadcasts to them; a CHAT message another member sent them stays for that
|
||||||
|
// member, its recipient replaced by a tombstone address;
|
||||||
|
// - help desk tickets stay as closed history: requester replaced by the tombstone, their own messages blanked;
|
||||||
|
// - every data document (docs table) that mentions them: their keys, list items and records (scrub.js), through the owning
|
||||||
|
// module's live state when a module keeps one in memory, else read and written through docstore.
|
||||||
|
// A tombstone (SHA-256 of the email, kept 30 days in erase.json) stops the LinkSpin and hub syncs from bringing them back while
|
||||||
|
// the other sites catch up. The log keeps hashes and counts, never the email. Dry run = the same counts, nothing changed.
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const db = require('./db');
|
||||||
|
const { scrubDeep, scrubText, mentions } = require('./scrub');
|
||||||
|
|
||||||
|
let R = null; // { dataDir, accounts, docstore, owners: {doc: {state, save}}, reload: {doc: fn}, forget: [fn(email)] }
|
||||||
|
const TOMB_MS = 30 * 86400000;
|
||||||
|
const REMOVED = '[removed: this member asked for their data to be erased]';
|
||||||
|
const norm = v => String(v || '').trim().toLowerCase();
|
||||||
|
const hashOf = email => crypto.createHash('sha256').update(norm(email)).digest('hex');
|
||||||
|
const tombAddr = hash => 'erased-' + hash.slice(0, 12) + '@erased.invalid';
|
||||||
|
const FILE = () => path.join(R.dataDir, 'erase.json');
|
||||||
|
let st = null;
|
||||||
|
function load() {
|
||||||
|
if (st) return st;
|
||||||
|
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
||||||
|
if (!st || typeof st !== 'object') st = {};
|
||||||
|
st.v = 1; st.tomb = st.tomb || {}; st.log = st.log || [];
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
function save() { try { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('erase save', e.message); } }
|
||||||
|
function init(deps) { R = deps; st = null; load(); }
|
||||||
|
function isErased(email) {
|
||||||
|
const s = load(); const h = hashOf(email); const t = s.tomb[h];
|
||||||
|
if (!t) return false;
|
||||||
|
if (Date.now() - t > TOMB_MS) { delete s.tomb[h]; save(); return false; }
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const like = t => '%' + String(t).replace(/[\\%_]/g, m => '\\' + m) + '%';
|
||||||
|
async function tables() { return new Set((await db.q('SELECT table_name t FROM information_schema.tables WHERE table_schema = DATABASE()')).map(r => r.t || r.TABLE_NAME)); }
|
||||||
|
|
||||||
|
// the SQL work, in order: deletes and the two updates that keep other members' side of a conversation / the desk history
|
||||||
|
function steps(E, h, campIds, ticketIds, memberMsgIds) {
|
||||||
|
const S = []; const tomb = tombAddr(h);
|
||||||
|
const del = (t, where, args) => S.push({ t, where, args, op: 'delete' });
|
||||||
|
const upd = (t, set, setArgs, where, args) => S.push({ t, where, args, op: 'update', set, setArgs });
|
||||||
|
del('accounts', 'email=?', [E]); del('sessions', 'email=?', [E]); // first: nothing can sign in or be synced as them while the rest runs
|
||||||
|
if (campIds.length) for (const t of ['camp_hours', 'camp_geo', 'click_sources', 'solo_inbox', 'visit_seen', 'visit_repeat', 'video_seen', 'ad_reports', 'ad_clicks']) del(t, 'campaign_id IN (?)', [campIds]);
|
||||||
|
del('campaigns', 'owner_email=?', [E]); del('ad_clicks', 'owner_email=?', [E]);
|
||||||
|
for (const t of ['account_signals', 'daily_views', 'digests', 'drips', 'earned_credits', 'nudges', 'solo_inbox', 'visit_seen', 'visit_repeat', 'video_seen', 'credit_log', 'promo_redemptions', 'positions']) del(t, 'email=?', [E]);
|
||||||
|
del('prospects', 'owner_email=?', [E]); del('pipeline_notes', 'owner_email=? OR person=?', [E, E]); del('lead_marks', '`lead`=? OR sponsor=?', [E, E]);
|
||||||
|
upd('ad_reports', "reporter=''", [], 'reporter=?', [E]); upd('promo_codes', 'funder=NULL', [], 'funder=?', [E]);
|
||||||
|
del('adoptions', 'adoptee=? OR adopter=?', [E, E]); del('tank_batch_picks', 'adoptee=? OR sponsor=?', [E, E]); // holding tank batches (2026-11-15)
|
||||||
|
del('event_marks', 'k LIKE ?', [like(E)]); del('doc_claims', 'k LIKE ?', [like(E)]);
|
||||||
|
del('sponsor_messages', 'from_email=?', [E]);
|
||||||
|
upd('sponsor_messages', 'to_email=?', [tomb], "to_email=? AND kind='chat'", [E]); // the other member's own words stay theirs
|
||||||
|
del('sponsor_messages', "to_email=? AND kind<>'chat'", [E]); // notices, alerts, broadcasts: copies made for them alone
|
||||||
|
if (memberMsgIds.length) del('ticket_translations', 'message_id IN (?)', [memberMsgIds]);
|
||||||
|
if (ticketIds.length) upd('ticket_messages', 'body=?, attachments=NULL, email_message_id=NULL', [REMOVED], "ticket_id IN (?) AND author='member'", [ticketIds]);
|
||||||
|
upd('tickets', 'email=?, name=NULL, username=NULL', [tomb], 'email=?', [E]);
|
||||||
|
return S;
|
||||||
|
}
|
||||||
|
|
||||||
|
// what still mentions them anywhere in the database (every text column of every table but docs); [] = clean
|
||||||
|
async function residue(E, exact) {
|
||||||
|
if (!db.enabled()) return [];
|
||||||
|
const cols = await db.q("SELECT table_name t, column_name c FROM information_schema.columns WHERE table_schema = DATABASE() AND data_type IN ('char','varchar','text','mediumtext','longtext','json') AND table_name NOT IN ('docs','docs_writer')");
|
||||||
|
const out = [];
|
||||||
|
for (const r of cols) {
|
||||||
|
const t = r.t || r.TABLE_NAME, c = r.c || r.COLUMN_NAME; const ex = exact.filter(Boolean); const words = ex.filter(x => x.length >= 5); // a long username inside text too
|
||||||
|
const where = '`' + c + '` LIKE ?' + ex.map(() => ' OR `' + c + '` = ?').join('') + words.map(() => ' OR `' + c + '` REGEXP ?').join('');
|
||||||
|
const wordRe = w => '(^|[^a-z0-9_])' + w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([^a-z0-9_]|$)'; // the whole word, not a longer name
|
||||||
|
try { const [x] = await db.q('SELECT COUNT(*) n FROM `' + t + '` WHERE ' + where, [like(E)].concat(ex, words.map(wordRe))); if (Number(x.n)) out.push({ table: t, column: c, n: Number(x.n) }); } catch (e) {}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function docNames() {
|
||||||
|
if (R.docstore && R.docstore.isOn && R.docstore.isOn()) return R.docstore.names();
|
||||||
|
const out = []; const walk = (d, pre) => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) {} for (const x of ents) { const p = path.join(d, x.name); if (x.isDirectory()) walk(p, pre + x.name + '/'); else if (/\.jsonl?$/i.test(x.name)) out.push(pre + x.name); } };
|
||||||
|
walk(R.dataDir, ''); return out;
|
||||||
|
}
|
||||||
|
// every data document that mentions them: counted (dry run) or scrubbed, through the module that holds it in memory if any
|
||||||
|
function docs(needles, dryRun) {
|
||||||
|
const out = {};
|
||||||
|
for (const name of docNames()) {
|
||||||
|
if (name === 'erase.json') continue; // hashes only
|
||||||
|
const file = path.join(R.dataDir, name); let body;
|
||||||
|
try { body = fs.readFileSync(file, 'utf8'); } catch (e) { continue; }
|
||||||
|
if (!mentions(body, needles)) continue;
|
||||||
|
const own = R.owners[name];
|
||||||
|
try {
|
||||||
|
if (own) {
|
||||||
|
const live = own.state(); const n = scrubDeep(dryRun ? JSON.parse(JSON.stringify(live)) : live, needles);
|
||||||
|
if (!dryRun && n) own.save(); out[name] = n;
|
||||||
|
} else {
|
||||||
|
const r = scrubText(body, needles, /\.jsonl$/i.test(name));
|
||||||
|
if (!dryRun && r.removed) { fs.writeFileSync(file, r.body); if (R.reload && R.reload[name]) R.reload[name](); }
|
||||||
|
out[name] = r.removed;
|
||||||
|
}
|
||||||
|
} catch (e) { out[name] = 'error: ' + String(e.message).slice(0, 80); }
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
function docResidue(needles) { return docNames().filter(n => n !== 'erase.json').filter(n => { try { return mentions(fs.readFileSync(path.join(R.dataDir, n), 'utf8'), needles); } catch (e) { return false; } }); }
|
||||||
|
|
||||||
|
async function blockersOf(acct, E) {
|
||||||
|
const out = [];
|
||||||
|
if (acct.address) out.push('main wallet linked');
|
||||||
|
if (Number(acct.memberId) > 0) out.push('on-chain member #' + acct.memberId);
|
||||||
|
try { const pos = await R.accounts.positions(E); if (pos && pos.length) out.push('linked positions: ' + pos.length); } catch (e) {}
|
||||||
|
const refs = [acct.username, acct.code].filter(Boolean).map(norm);
|
||||||
|
if (refs.length) { const team = (await R.accounts.listByReferrer(refs)).filter(a => norm(a.email) !== E); if (team.length) out.push('sponsored under them here: ' + team.length); }
|
||||||
|
if (db.enabled()) { const [r] = await db.q("SELECT COUNT(*) n FROM campaigns WHERE owner_email=? AND status IN ('active','queued','paused')", [E]); if (Number(r.n)) out.push('ads still running or queued: ' + r.n + ' (stop them first, skill iap-kill-ad)'); }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// email -> {ok, dryRun, emailHash, found, blockers, sql: {table: rows}, docs: {doc: removed}, residue, docResidue}
|
||||||
|
async function erase(email, opts) {
|
||||||
|
const o = Object.assign({ dryRun: true, force: false, by: 'admin', sweep: true }, opts || {});
|
||||||
|
const E = norm(email); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)) return { error: 'A valid email is required.' };
|
||||||
|
const h = hashOf(E); const acct = await R.accounts.byEmail(E);
|
||||||
|
// names: usernames of an account already erased (a second pass after the code learned something new), e.g. ['oldname']
|
||||||
|
const names = (Array.isArray(o.names) ? o.names : []).map(norm).filter(x => /^[a-z0-9_.-]{5,30}$/.test(x));
|
||||||
|
const exact = (acct ? [acct.username, acct.code].filter(Boolean).map(norm) : []).concat(names);
|
||||||
|
const needles = { emails: [E], exact };
|
||||||
|
const blockers = acct ? await blockersOf(acct, E) : [];
|
||||||
|
const res = { dryRun: !!o.dryRun, emailHash: h, found: !!acct, blockers, forced: !!o.force && blockers.length > 0, sql: {}, docs: {} };
|
||||||
|
if (blockers.length && !o.force && !o.dryRun) return Object.assign(res, { error: 'Not erased: ' + blockers.join('; ') + '. Send force: true to erase anyway.' });
|
||||||
|
let campIds = [], ticketIds = [], memberMsgIds = [], have = new Set();
|
||||||
|
if (db.enabled()) {
|
||||||
|
have = await tables();
|
||||||
|
campIds = (await db.q('SELECT id FROM campaigns WHERE owner_email=?', [E])).map(r => r.id);
|
||||||
|
ticketIds = have.has('tickets') ? (await db.q('SELECT id FROM tickets WHERE email=?', [E])).map(r => r.id) : [];
|
||||||
|
memberMsgIds = ticketIds.length ? (await db.q("SELECT id FROM ticket_messages WHERE ticket_id IN (?) AND author='member'", [ticketIds])).map(r => r.id) : [];
|
||||||
|
}
|
||||||
|
if (!o.dryRun) { load().tomb[h] = Date.now(); save(); } // before anything goes: the syncs refuse them from here on
|
||||||
|
if (db.enabled()) {
|
||||||
|
for (const s of steps(E, h, campIds, ticketIds, memberMsgIds)) {
|
||||||
|
if (!have.has(s.t)) continue;
|
||||||
|
const key = s.t + (s.op === 'update' ? ' (kept, scrubbed)' : '');
|
||||||
|
if (o.dryRun) { const [r] = await db.q('SELECT COUNT(*) n FROM `' + s.t + '` WHERE ' + s.where, s.args); res.sql[key] = (res.sql[key] || 0) + Number(r.n); continue; }
|
||||||
|
const r = s.op === 'delete' ? await db.q('DELETE FROM `' + s.t + '` WHERE ' + s.where, s.args) : await db.q('UPDATE `' + s.t + '` SET ' + s.set + ' WHERE ' + s.where, s.setArgs.concat(s.args));
|
||||||
|
res.sql[key] = (res.sql[key] || 0) + Number(r.affectedRows || 0);
|
||||||
|
}
|
||||||
|
// other members' chat mute lists that name them
|
||||||
|
const mutes = await db.q('SELECT email, chat_mutes FROM accounts WHERE chat_mutes LIKE ?', [like(E)]);
|
||||||
|
let mu = 0; for (const m of mutes) { let list = []; try { list = JSON.parse(m.chat_mutes || '[]'); } catch (e) {} const keep = list.filter(x => norm(x) !== E); if (keep.length !== list.length) { mu++; if (!o.dryRun) await db.q('UPDATE accounts SET chat_mutes=? WHERE email=?', [JSON.stringify(keep), m.email]); } }
|
||||||
|
if (mu) res.sql['accounts.chat_mutes (others, scrubbed)'] = mu;
|
||||||
|
// their username inside messages that stay (another member's chat to them, a notice to their sponsor about them): the name
|
||||||
|
// goes, the message stays. Whole words only, usernames of 5+ characters (a short one could be an ordinary word).
|
||||||
|
let rd = 0;
|
||||||
|
for (const u of exact.filter(x => x.length >= 5 && ((acct && norm(acct.username) === x) || names.includes(x)))) {
|
||||||
|
const re = new RegExp('(^|[^a-z0-9_])@?' + u.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![a-z0-9_])', 'gi');
|
||||||
|
for (const m of await db.q('SELECT id, subject, body FROM sponsor_messages WHERE subject LIKE ? OR body LIKE ?', [like(u), like(u)])) {
|
||||||
|
const sub = String(m.subject || '').replace(re, '$1[erased member]'), body = m.body == null ? null : String(m.body).replace(re, '$1[erased member]');
|
||||||
|
if (sub === m.subject && body === m.body) continue;
|
||||||
|
rd++; if (!o.dryRun) await db.q('UPDATE sponsor_messages SET subject=?, body=? WHERE id=?', [sub, body, m.id]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rd) res.sql['sponsor_messages (others, name removed)'] = rd;
|
||||||
|
} else if (acct && !o.dryRun) { const r = await R.accounts.removeAccount(E); res.sql.accounts = r && r.ok ? 1 : 0; }
|
||||||
|
else if (acct) res.sql.accounts = 1;
|
||||||
|
res.docs = docs(needles, o.dryRun);
|
||||||
|
if (!o.dryRun) for (const f of R.forget || []) { try { f(E); } catch (e) {} } // caches that are not documents (hub lookups, pending pushes)
|
||||||
|
for (const k of Object.keys(res.sql)) if (!res.sql[k]) delete res.sql[k];
|
||||||
|
for (const k of Object.keys(res.docs)) if (!res.docs[k]) delete res.docs[k];
|
||||||
|
if (o.sweep) { res.residue = await residue(E, exact); res.docResidue = o.dryRun ? [] : docResidue(needles); }
|
||||||
|
if (!o.dryRun) {
|
||||||
|
const s = load(); s.log.push({ at: Date.now(), by: String(o.by).slice(0, 20), hash: h.slice(0, 16), forced: res.forced, found: res.found,
|
||||||
|
sql: Object.values(res.sql).reduce((a, b) => a + b, 0), docs: Object.keys(res.docs).length, residue: (res.residue || []).length });
|
||||||
|
if (s.log.length > 500) s.log = s.log.slice(-500); save();
|
||||||
|
console.log('member erase', h.slice(0, 16), 'by', o.by, 'sql rows', JSON.stringify(res.sql), 'docs', JSON.stringify(res.docs));
|
||||||
|
}
|
||||||
|
res.ok = true; return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the hub's member.erased event carries only the SHA-256 of the email: find who here has it (accounts, then the help desk)
|
||||||
|
async function byHash(hash, by) {
|
||||||
|
const h = norm(hash); if (!/^[0-9a-f]{64}$/.test(h)) return { result: 'bad-hash' };
|
||||||
|
let email = null;
|
||||||
|
for (const a of await R.accounts.identities()) if (hashOf(a.email) === h) { email = norm(a.email); break; }
|
||||||
|
if (!email && db.enabled()) { try { for (const r of await db.q('SELECT DISTINCT email FROM tickets')) if (hashOf(r.email) === h) { email = norm(r.email); break; } } catch (e) {} }
|
||||||
|
if (!email) { const s = load(); s.tomb[h] = Date.now(); save(); return { result: 'not-here' }; }
|
||||||
|
const r = await erase(email, { dryRun: false, by: by || 'hub', sweep: false });
|
||||||
|
return { result: r.error ? 'refused' : 'erased', error: r.error || null, sql: r.sql, docs: r.docs };
|
||||||
|
}
|
||||||
|
function view() { const s = load(); return { tombstones: Object.keys(s.tomb).length, recent: s.log.slice(-20).reverse() }; }
|
||||||
|
|
||||||
|
module.exports = { init, erase, byHash, isErased, hashOf, view, _reset: () => { st = null; } };
|
||||||
@@ -7,6 +7,8 @@
|
|||||||
//
|
//
|
||||||
// Settings (siteConfig): fridayPromo '1'|'0', fridayBonusPct (20), fridayStart 'YYYY-MM-DD' (first
|
// 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.
|
// 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';
|
'use strict';
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
@@ -17,6 +19,11 @@ 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 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 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 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: {} }; } }
|
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
|
// public view
|
||||||
function view() {
|
function view() {
|
||||||
const c = cfg(); const now = Date.now(); const live = liveNow(now); const next = nextFriday(now);
|
const c = cfg(); const now = clock(); 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 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
|
// the bonus: once per purchase tx, on a Friday on or after the start
|
||||||
async function onEvent(ev) {
|
async function onEvent(ev) {
|
||||||
if (!ev || ev.type !== 'Purchase' || !liveNow(ev.ts) || ev.priceCents < 500) return null;
|
if (!ev || ev.type !== 'Purchase' || !liveNow(ev.ts) || ev.priceCents < 500) return null;
|
||||||
if (S.granted[ev.tx]) 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;
|
if (bonus <= 0) return null;
|
||||||
const a = await X.accounts.byMemberId(ev.buyerId); if (!a || !a.email) 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$/, '');
|
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();
|
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
|
// the wave, every ten packs
|
||||||
const st = stats(dayOf(ev.ts));
|
const st = stats(dayOf(ev.ts));
|
||||||
if (st.packs > 0 && st.packs % 10 === 0 && !S.posts[st.day + ':' + st.packs]) {
|
if (st.packs > 0 && st.packs % 10 === 0 && !S.posts[st.day + ':' + st.packs]) {
|
||||||
S.posts[st.day + ':' + st.packs] = Date.now(); save();
|
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;
|
return bonus;
|
||||||
}
|
}
|
||||||
@@ -107,25 +117,28 @@ function earnedBadge(memberId) {
|
|||||||
// Saturday 00:xx CT wrap-up of the Friday that just ended
|
// Saturday 00:xx CT wrap-up of the Friday that just ended
|
||||||
async function tick() {
|
async function tick() {
|
||||||
const c = cfg(); if (!c.on) return;
|
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);
|
const next = nextFriday(now);
|
||||||
if (wd === 'Thu' && h >= 18 && next && !S.sent['thu:' + next] && await claimOnce('fri:thu:' + next)) {
|
if (wd === 'Thu' && h >= 18 && next && !S.sent['thu:' + next] && await claimOnce('fri:thu:' + next)) {
|
||||||
S.sent['thu:' + next] = now; save();
|
S.sent['thu:' + next] = now; save();
|
||||||
const subject = 'Tomorrow is Five Dollar Friday';
|
const promo = X.promodays && X.promodays.thursdayCopy(next); // Thanksgiving 11-26: the Black Friday copy instead, one message
|
||||||
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 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);
|
await broadcast(subject, text);
|
||||||
}
|
}
|
||||||
if (wd === 'Fri' && h >= c.kickHour && day >= c.start && !S.sent['kick:' + day] && await claimOnce('fri:kick:' + day)) {
|
if (wd === 'Fri' && h >= c.kickHour && day >= c.start && !S.sent['kick:' + day] && await claimOnce('fri:kick:' + day)) {
|
||||||
S.sent['kick:' + day] = now; save();
|
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) {
|
if (wd === 'Sat' && h < 3) {
|
||||||
const fri = dayOf(now - 86400000);
|
const fri = dayOf(now - 86400000);
|
||||||
if (isFriday(now - 86400000) && fri >= c.start && !S.sent['wrap:' + fri] && await claimOnce('fri:wrap:' + fri)) {
|
if (isFriday(now - 86400000) && fri >= c.start && !S.sent['wrap:' + fri] && await claimOnce('fri:wrap:' + fri)) {
|
||||||
S.sent['wrap:' + fri] = now; save();
|
S.sent['wrap:' + fri] = now; save();
|
||||||
const st = stats(fri); const top = await topLines(fri);
|
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'
|
const wn = nameAt(now - 86400000); const promoFri = wn !== 'Five Dollar Friday';
|
||||||
+ (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(() => {});
|
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)
|
// on-site notice + email to every active member (quiet 45+ days skipped, drip unsubscribes honoured)
|
||||||
async function broadcast(subject, text) {
|
async function broadcast(subject, text) {
|
||||||
let all = []; try { all = await X.accounts.listAll(5000); } catch (e) { return; }
|
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) {
|
for (const a of all) {
|
||||||
if (!a.email) continue;
|
if (!a.email) continue;
|
||||||
if (now - (a.lastSeen || a.created || 0) > 45 * 86400000) 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';
|
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 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 T = tiersOf(cur);
|
||||||
const until = Math.max(t, T[tier]) + tc.days * 86400000; T[tier] = until; // renewing early loses nothing: from max(now, until)
|
// 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
|
||||||
const bought = [Object.assign({ ts: t, via, tier, usd: tc.price / 100, days: tc.days }, extra || {})].concat(cur.bought || []).slice(0, 200);
|
// 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 }));
|
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 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; }
|
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
|
// 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)
|
// 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 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) };
|
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');
|
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 } }; } };
|
||||||
@@ -16,6 +16,8 @@
|
|||||||
// Rule 2 (2026-11-14): the sponsor written for an arrival is person.locks.iap's sponsor when that lock exists, never the
|
// Rule 2 (2026-11-14): the sponsor written for an arrival is person.locks.iap's sponsor when that lock exists, never the
|
||||||
// plain network sponsor. QUIET: nothing on this path sends mail, a notice or a post, and lssync.js never
|
// plain network sponsor. QUIET: nothing on this path sends mail, a notice or a post, and lssync.js never
|
||||||
// pushes a hub waiting account to LinkSpin (qa/hubsync.test.cjs, mail audit).
|
// pushes a hub waiting account to LinkSpin (qa/hubsync.test.cjs, mail audit).
|
||||||
|
// member.erased (2026-11-15) the hub erased someone: erase.js finds them by the SHA-256 of the email and takes them out
|
||||||
|
// here too; refused (wallet, member number, team) = a log note, never retried.
|
||||||
// anything else ignored.
|
// anything else ignored.
|
||||||
// Each seq is applied once (done map). A failing event answers 503 so the hub retries it; after 5 tries it is set aside
|
// Each seq is applied once (done map). A failing event answers 503 so the hub retries it; after 5 tries it is set aside
|
||||||
// in the log so one bad row cannot hold every later event back.
|
// in the log so one bad row cannot hold every later event back.
|
||||||
@@ -130,9 +132,27 @@ async function walletConnected(ev) {
|
|||||||
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
|
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
|
||||||
return 'applied';
|
return 'applied';
|
||||||
}
|
}
|
||||||
|
// member.erased (2026-11-15): the hub erased someone; erase.js takes them out here too, found by the SHA-256 of the email
|
||||||
|
// (the event carries nothing else). Refused here (a wallet, a member number, a team) = noted for Marty, never retried.
|
||||||
|
async function memberErased(ev) {
|
||||||
|
if (!R.erase) return 'ignored';
|
||||||
|
const r = await R.erase.byHash(ev.data && ev.data.emailHash, 'hub');
|
||||||
|
if (r.result === 'refused') note({ type: 'erase-refused', hash: String(ev.data.emailHash).slice(0, 16), error: String(r.error || '').slice(0, 200) });
|
||||||
|
else note({ type: 'erased', hash: String((ev.data && ev.data.emailHash) || '').slice(0, 16), result: r.result });
|
||||||
|
return r.result === 'erased' ? 'applied' : 'ignored';
|
||||||
|
}
|
||||||
async function apply(ev) {
|
async function apply(ev) {
|
||||||
if (ev.type === 'member.joined') return memberJoined(ev);
|
if (ev.type === 'member.joined') return memberJoined(ev);
|
||||||
if (ev.type === 'wallet.connected') return walletConnected(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
|
// 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
|
// 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.
|
// must never move anyway (the contract pays whoever it holds). qa/hubsync.test.cjs proves a locked member stays put.
|
||||||
@@ -359,4 +379,4 @@ function adminView() {
|
|||||||
return Object.assign({ enabled: enabled(), on: on(), site: SITE(), url: URL_(), since: s.since, outbox: s.outbox.length, retrying: Object.keys(s.tries).length,
|
return Object.assign({ enabled: enabled(), on: on(), site: SITE(), url: URL_(), since: s.since, outbox: s.outbox.length, retrying: Object.keys(s.tries).length,
|
||||||
disagree: Object.keys(s.disagree).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() });
|
disagree: Object.keys(s.disagree).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() });
|
||||||
}
|
}
|
||||||
module.exports = { _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
|
module.exports = { _state: load, _save: save, _forgetHeld: email => held.delete(norm(email)), _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ const FAQ = [
|
|||||||
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
|
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
|
||||||
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
|
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
|
||||||
tags: ['wallet', 'position', 'qualified start', 'metamask'],
|
tags: ['wallet', 'position', 'qualified start', 'metamask'],
|
||||||
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.' },
|
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside your wallet app, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.' },
|
||||||
{ id: 'f-exchange-withdraw', title: 'Sending POL from an exchange', source: 'faq',
|
{ id: 'f-exchange-withdraw', title: 'Sending POL from an exchange', source: 'faq',
|
||||||
questions: ['How do I send POL from Binance or Kraken?', 'Which network do I pick when withdrawing from an exchange?', 'I sent POL on the wrong network'],
|
questions: ['How do I send POL from Binance or Kraken?', 'Which network do I pick when withdrawing from an exchange?', 'I sent POL on the wrong network'],
|
||||||
tags: ['exchange', 'withdraw', 'network', 'polygon', 'binance', 'kraken'],
|
tags: ['exchange', 'withdraw', 'network', 'polygon', 'binance', 'kraken'],
|
||||||
|
|||||||
@@ -9,6 +9,12 @@
|
|||||||
// path serves the new text.
|
// path serves the new text.
|
||||||
// source canned | faq | ticket | admin
|
// source canned | faq | ticket | admin
|
||||||
//
|
//
|
||||||
|
// NETWORK (2026-11-15, netkb.js): the other network sites' entries, read from the hub, sit in the same index. This site's own
|
||||||
|
// entries are boosted first (HOME_BOOST); a question that names another site boosts that site's entries (NAMED_BOOST) and
|
||||||
|
// skips this site's instant answers (namesOther, chatbot.js). Other sites' entries never take the fast path; they ride along as
|
||||||
|
// context labelled with the site and the link to send people to. This site's own entries are published to the hub. The same
|
||||||
|
// merge code is in InstantAdPay, LinkSpin and the rebuilt sites' kb.js.
|
||||||
|
//
|
||||||
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
|
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
|
||||||
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
|
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
|
||||||
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
|
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
|
||||||
@@ -22,10 +28,11 @@
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
|
let netkb = null; try { netkb = require('./netkb'); } catch (e) {}
|
||||||
const db = require('./db');
|
const db = require('./db');
|
||||||
|
|
||||||
let DATA_DIR = null, SEEDS = [], ready = null;
|
let DATA_DIR = null, SEEDS = [], ready = null;
|
||||||
let cache = null, cacheAt = 0, index = null;
|
let cache = null, cacheAt = 0, index = null, netVer = '';
|
||||||
const TTL = 30000; // two app copies run during a deploy, and MySQL is shared: re-read now and then
|
const TTL = 30000; // two app copies run during a deploy, and MySQL is shared: re-read now and then
|
||||||
|
|
||||||
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
|
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
|
||||||
@@ -82,10 +89,38 @@ function buildIndex(entries) {
|
|||||||
}
|
}
|
||||||
return { docs, df, avg, n: docs.length };
|
return { docs, df, avg, n: docs.length };
|
||||||
}
|
}
|
||||||
|
const HOME_BOOST = 2, NAMED_BOOST = 3;
|
||||||
|
// which network sites a question names, by the site name or a short alias ("dlb", "vbb", "iap", ...)
|
||||||
|
const ALIASES = { iap: ['iap', 'instant ad pay'], linkspin: ['link spin'], bannerline: ['dlb', 'downline banner', 'downline banners'], vbb: ['vbb', 'viral banner'],
|
||||||
|
viraladblitz: ['vab', 'viral ad blitz'], downlinehydra: ['hydra', 'dh'], fivex: ['5x', '5x your team', 'five x', 'the draft'], stackpol: ['stack pol', 'stackpol'] };
|
||||||
|
const norm = s => ' ' + String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim() + ' ';
|
||||||
|
function namedSites(query, idx) {
|
||||||
|
const q = norm(query); const out = new Set();
|
||||||
|
for (const s of (idx && idx.sites) || []) {
|
||||||
|
const names = [s.name, s.site].concat(ALIASES[s.site] || []).map(norm);
|
||||||
|
if (names.some(n => n.trim() && q.includes(n))) out.add(s.site);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// does the question name a network site other than this one (hub site id `self`)? Then the home fast path stands aside.
|
||||||
|
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz',
|
||||||
|
downlinehydra: 'DownlineHydra', fivex: '5xYourTeam', stackpol: 'Stack POL', earnerscorner: 'Earners Corner' };
|
||||||
|
function namesOther(query, self) {
|
||||||
|
const q = norm(query); const out = [];
|
||||||
|
const ids = new Set(Object.keys(NAMES).concat(((index && index.sites) || []).map(s => s.site)));
|
||||||
|
for (const id of ids) {
|
||||||
|
if (id === self) continue;
|
||||||
|
const s = ((index && index.sites) || []).find(x => x.site === id) || {};
|
||||||
|
const names = [s.name, NAMES[id], id.length > 3 ? id : ''].concat(ALIASES[id] || []).filter(Boolean).map(norm);
|
||||||
|
if (names.some(n => n.trim() && q.includes(n))) out.push(id);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
function rank(idx, query, k) {
|
function rank(idx, query, k) {
|
||||||
if (!idx || !idx.n) return [];
|
if (!idx || !idx.n) return [];
|
||||||
const qt = [...new Set(terms(query))];
|
const qt = [...new Set(terms(query))];
|
||||||
if (!qt.length) return [];
|
if (!qt.length) return [];
|
||||||
|
const named = namedSites(query, idx);
|
||||||
const out = [];
|
const out = [];
|
||||||
for (const d of idx.docs) {
|
for (const d of idx.docs) {
|
||||||
let s = 0;
|
let s = 0;
|
||||||
@@ -97,6 +132,8 @@ function rank(idx, query, k) {
|
|||||||
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
|
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (s > 0 && d.e.site) s *= named.has(d.e.site) ? NAMED_BOOST : 1;
|
||||||
|
else if (s > 0) s *= named.size ? 1 : HOME_BOOST;
|
||||||
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
|
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
|
||||||
}
|
}
|
||||||
out.sort((a, b) => b.score - a.score);
|
out.sort((a, b) => b.score - a.score);
|
||||||
@@ -188,9 +225,10 @@ function init(opts) {
|
|||||||
}
|
}
|
||||||
async function load(force) {
|
async function load(force) {
|
||||||
if (ready) await ready;
|
if (ready) await ready;
|
||||||
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
|
if (!force && cache && Date.now() - cacheAt < TTL && (!netkb || netkb.version() === netVer)) return cache; // a new network set rebuilds at once
|
||||||
const all = await store().all();
|
const all = await store().all();
|
||||||
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); index = buildIndex(cache); rx.clear();
|
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); rx.clear(); netVer = netkb ? netkb.version() : '';
|
||||||
|
index = buildIndex(cache.concat(netkb ? netkb.remote() : [])); index.sites = netkb ? netkb.sites() : [];
|
||||||
return cache;
|
return cache;
|
||||||
}
|
}
|
||||||
const rx = new Map();
|
const rx = new Map();
|
||||||
@@ -208,13 +246,16 @@ async function fastPath(msg) {
|
|||||||
}
|
}
|
||||||
async function search(query, k) { await load(); return rank(index, query, k || 5); }
|
async function search(query, k) { await load(); return rank(index, query, k || 5); }
|
||||||
async function context(query, k) { return relevant(await search(query, k || 5)); }
|
async function context(query, k) { return relevant(await search(query, k || 5)); }
|
||||||
|
// this site's own entries, for netkb.publish
|
||||||
|
async function own() { await load(); return cache.slice(); }
|
||||||
|
const label = e => e.site ? ' (about ' + e.siteName + ', another network site; send people to ' + e.go + ')' : '';
|
||||||
const HELP = 'Help (https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out)';
|
const HELP = 'Help (https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out)';
|
||||||
function promptBlock(hits) {
|
function promptBlock(hits) {
|
||||||
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
|
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
|
||||||
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
|
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
|
||||||
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
|
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
|
||||||
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
|
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
|
||||||
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
|
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + label(h.entry) + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- the admin side
|
// ---------------------------------------------------------------- the admin side
|
||||||
@@ -235,7 +276,7 @@ function validate(o, cur) {
|
|||||||
async function list(q) {
|
async function list(q) {
|
||||||
const all = (await load(true)).slice();
|
const all = (await load(true)).slice();
|
||||||
if (!q) return all.sort((a, b) => b.updated - a.updated);
|
if (!q) return all.sort((a, b) => b.updated - a.updated);
|
||||||
const ranked = rank(index, q, 50).map(h => Object.assign({ score: h.score }, h.entry));
|
const ranked = rank(index, q, 50).filter(h => !h.entry.site).map(h => Object.assign({ score: h.score }, h.entry));
|
||||||
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
|
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
|
||||||
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
|
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
|
||||||
return ranked.concat(plain);
|
return ranked.concat(plain);
|
||||||
@@ -246,19 +287,19 @@ async function create(o) {
|
|||||||
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
|
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
|
||||||
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
|
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
|
||||||
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
|
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
|
||||||
await store().put(e); await load(true);
|
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
|
||||||
return { ok: true, entry: e };
|
return { ok: true, entry: e };
|
||||||
}
|
}
|
||||||
async function update(id, o) {
|
async function update(id, o) {
|
||||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||||
const v = validate(o, cur); if (v.error) return v;
|
const v = validate(o, cur); if (v.error) return v;
|
||||||
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
|
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
|
||||||
await store().put(e); await load(true);
|
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
|
||||||
return { ok: true, entry: e };
|
return { ok: true, entry: e };
|
||||||
}
|
}
|
||||||
async function remove(id) {
|
async function remove(id) {
|
||||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||||
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true);
|
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true); if (netkb) netkb.publishSoon();
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
|
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
|
||||||
@@ -273,8 +314,8 @@ async function stamp() {
|
|||||||
async function test(question) {
|
async function test(question) {
|
||||||
const fast = await fastPath(String(question || ''));
|
const fast = await fastPath(String(question || ''));
|
||||||
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
|
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
|
||||||
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
|
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, site: h.entry.site || '', title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, load, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
|
module.exports = { init, load, own, namesOther, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
|
||||||
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };
|
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, namedSites, MIN_SCORE, HOME_BOOST, NAMED_BOOST } };
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ async function renderPage() {
|
|||||||
const w = winners();
|
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('');
|
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 += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
|
||||||
h += '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
h += '</div><script src="/assets/common.js?v=20261117nw"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
|
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// Login-ad clock (Marty 2026-11-15): "I definitely don't want somebody to not look at a login ad for 7 days... if login ads are
|
||||||
|
// available on those sites, they need to be seen several times a day." The SAME file ships in InstantAdPay and LinkSpin.
|
||||||
|
//
|
||||||
|
// A member sees the login ad on their next member-area page load whenever their last finished login-ad view on THIS site is more
|
||||||
|
// than loginAdEveryHours old (site setting, default 3), whether or not they just signed in. One row per member in MySQL
|
||||||
|
// (table login_ad_views: k = lowercased email, or 'w:' + wallet for a wallet-only session; seen_at; served_at).
|
||||||
|
// due(k) true when the member should get the login ad now (no row, or seen_at older than the setting)
|
||||||
|
// served(k) the login ad was handed to this member (the countdown starts on their screen)
|
||||||
|
// seen(k, s) the countdown ended: counts only when a serve to this member happened at least s - 2 seconds ago and within the
|
||||||
|
// last 30 minutes, so reloading during the countdown never skips the ad
|
||||||
|
// forget(k) member erase
|
||||||
|
// No database (local QA): the same rules in memory. A failed database read answers "due": when in doubt the ad shows.
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
let pool = null, tableReady = null, hours = () => 3;
|
||||||
|
const mem = new Map(); // k -> { seen, served }
|
||||||
|
const SERVE_WINDOW = 30 * 60 * 1000;
|
||||||
|
|
||||||
|
const keyOf = s => {
|
||||||
|
if (!s) return '';
|
||||||
|
const e = String(s.email || '').trim().toLowerCase();
|
||||||
|
if (e) return e.slice(0, 190);
|
||||||
|
const a = String(s.address || '').trim().toLowerCase();
|
||||||
|
return /^0x[0-9a-f]{40}$/.test(a) ? 'w:' + a : '';
|
||||||
|
};
|
||||||
|
const everyMs = () => { const h = Number(hours()); return (Number.isFinite(h) && h > 0 ? Math.min(h, 24 * 30) : 3) * 3600 * 1000; };
|
||||||
|
|
||||||
|
function init(opts) {
|
||||||
|
const o = opts || {};
|
||||||
|
if (typeof o.hours === 'function') hours = o.hours;
|
||||||
|
const url = String(o.url || '').trim();
|
||||||
|
pool = null; tableReady = null; mem.clear();
|
||||||
|
if (url) { const mysql = require('mysql2/promise'); pool = mysql.createPool({ uri: url, connectionLimit: 3, charset: 'utf8mb4' }); }
|
||||||
|
}
|
||||||
|
async function table() {
|
||||||
|
if (!tableReady) tableReady = pool.query('CREATE TABLE IF NOT EXISTS login_ad_views (k VARCHAR(200) PRIMARY KEY, seen_at BIGINT NOT NULL DEFAULT 0, served_at BIGINT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').catch(e => { tableReady = null; throw e; });
|
||||||
|
return tableReady;
|
||||||
|
}
|
||||||
|
async function row(k) {
|
||||||
|
if (!pool) return mem.get(k) || null;
|
||||||
|
await table();
|
||||||
|
const [r] = await pool.query('SELECT seen_at, served_at FROM login_ad_views WHERE k = ?', [k]);
|
||||||
|
return r[0] ? { seen: Number(r[0].seen_at) || 0, served: Number(r[0].served_at) || 0 } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function due(k, now) {
|
||||||
|
if (!k) return false;
|
||||||
|
const t = now || Date.now();
|
||||||
|
try { const r = await row(k); return !r || !r.seen || t - r.seen >= everyMs(); } catch (e) { console.error('login-ad clock read', e.message); return true; }
|
||||||
|
}
|
||||||
|
async function served(k, now) {
|
||||||
|
if (!k) return;
|
||||||
|
const t = now || Date.now();
|
||||||
|
if (!pool) { const r = mem.get(k) || { seen: 0, served: 0 }; r.served = t; mem.set(k, r); return; }
|
||||||
|
try { await table(); await pool.query('INSERT INTO login_ad_views (k, served_at) VALUES (?, ?) ON DUPLICATE KEY UPDATE served_at = VALUES(served_at)', [k, t]); }
|
||||||
|
catch (e) { console.error('login-ad clock serve', e.message); }
|
||||||
|
}
|
||||||
|
// -> { ok: true } or { ok: false, reason }
|
||||||
|
async function seen(k, dwellSec, now) {
|
||||||
|
if (!k) return { ok: false, reason: 'signed out' };
|
||||||
|
const t = now || Date.now();
|
||||||
|
const need = Math.max(0, (Number(dwellSec) || 10) - 2) * 1000;
|
||||||
|
let r = null; try { r = await row(k); } catch (e) { console.error('login-ad clock read', e.message); return { ok: false, reason: 'store' }; }
|
||||||
|
if (!r || !r.served || t - r.served > SERVE_WINDOW) return { ok: false, reason: 'not served' };
|
||||||
|
if (t - r.served < need) return { ok: false, reason: 'too soon' };
|
||||||
|
if (!pool) { r.seen = t; mem.set(k, r); return { ok: true }; }
|
||||||
|
try { await pool.query('UPDATE login_ad_views SET seen_at = ? WHERE k = ?', [t, k]); return { ok: true }; }
|
||||||
|
catch (e) { console.error('login-ad clock seen', e.message); return { ok: false, reason: 'store' }; }
|
||||||
|
}
|
||||||
|
async function forget(k) {
|
||||||
|
if (!k) return;
|
||||||
|
mem.delete(k);
|
||||||
|
if (pool) { try { await table(); await pool.query('DELETE FROM login_ad_views WHERE k = ?', [k]); } catch (e) { console.error('login-ad clock forget', e.message); } }
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, keyOf, due, served, seen, forget, everyMs };
|
||||||
@@ -160,7 +160,7 @@ async function handle(rows, opts) {
|
|||||||
const s = load(); s.stats.batches++;
|
const s = load(); s.stats.batches++;
|
||||||
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
|
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
|
||||||
const ctx = { sum, done: new Set(), via: opts && opts.via, refOf: opts && opts.refOf }; const batch = [];
|
const ctx = { sum, done: new Set(), via: opts && opts.via, refOf: opts && opts.refOf }; const batch = [];
|
||||||
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
|
for (const x of rows || []) { const r = clean(x); if (!r) continue; if (R.erased && R.erased(r.email)) { sum.erased = (sum.erased || 0) + 1; continue; } sum.rows++; s.rows[r.email] = r; batch.push(r); } // erased here (erase.js): never brought back by a sync
|
||||||
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
|
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
|
||||||
try {
|
try {
|
||||||
for (const r of batch) {
|
for (const r of batch) {
|
||||||
@@ -192,4 +192,4 @@ function networkSponsor(email, address) {
|
|||||||
if (/^0x[0-9a-f]{40}$/.test(w)) for (const x of Object.values(s.rows)) if (x.wallet === w && x.sponsorEmail && x.sponsorEmail !== e && x.email !== e) return { sponsorEmail: x.sponsorEmail, via: 'same wallet' };
|
if (/^0x[0-9a-f]{40}$/.test(w)) for (const x of Object.values(s.rows)) if (x.wallet === w && x.sponsorEmail && x.sponsorEmail !== e && x.email !== e) return { sponsorEmail: x.sponsorEmail, via: 'same wallet' };
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
module.exports = { init, receive, adminView, networkSponsor };
|
module.exports = { init, receive, adminView, networkSponsor, _state: load, _save: save }; // _state/_save: the member erase (erase.js)
|
||||||
|
|||||||
@@ -120,4 +120,4 @@ async function release(email, sent) {
|
|||||||
// does LinkSpin know this email? (its row was pushed and recorded) - used by the link-farm admin list, never for a cascade
|
// does LinkSpin know this email? (its row was pushed and recorded) - used by the link-farm admin list, never for a cascade
|
||||||
function knows(email) { const st = load(); return Object.prototype.hasOwnProperty.call(st.hashes || {}, String(email || '').toLowerCase()); }
|
function knows(email) { const st = load(); return Object.prototype.hasOwnProperty.call(st.hashes || {}, String(email || '').toLowerCase()); }
|
||||||
function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, last: st.last, errors: st.errors, pendingTouches: pending.size }; }
|
function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, last: st.last, errors: st.errors, pendingTouches: pending.size }; }
|
||||||
module.exports = { init, touch, tick, adminView, on, mute, release, knows };
|
module.exports = { _state: load, _save: save, _forget: e => { pending.delete(String(e || '').toLowerCase()); muted.delete(String(e || '').toLowerCase()); }, init, touch, tick, adminView, on, mute, release, knows };
|
||||||
|
|||||||
@@ -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.
|
// Key sources: SENDGRID_KEY env, else DATA_DIR/sendgrid.key in the volume.
|
||||||
// No key = email sign-in stays feature-flagged off in production.
|
// No key = email sign-in stays feature-flagged off in production.
|
||||||
const fs = require('fs');
|
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
|
// 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
|
// the signed unsubscribe link (appended unless the body already has one) and
|
||||||
// RFC 8058 one-click List-Unsubscribe headers. New senders inherit this.
|
// 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; }
|
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
|
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 { 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); }
|
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 && !String(text).includes('/unsubscribe?')) text = text + '\n\n--\nStop these emails: ' + unsub;
|
||||||
if (unsub && html && !String(html).includes('/unsubscribe?')) {
|
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>';
|
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 });
|
if (html) content.push({ type: 'text/html', value: html });
|
||||||
const msg = {
|
const msg = {
|
||||||
personalizations: [{ to: [{ email: to }] }],
|
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,
|
subject,
|
||||||
content
|
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 });
|
+ '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
|
// 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.
|
// on its own surfaces at these same rates, so NAS delivery draws the same pool.
|
||||||
function impressionsPerCredit(type) {
|
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) {
|
function nasKind(type) {
|
||||||
// pid encodes text(1)/banner(2); adtype is a separate small int — 1 is the
|
// 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)
|
Name, Email, PaymentDetails, EDate, sp, width, height, BannerURL, pid, ref_by, catid)
|
||||||
VALUES (?,?,?,?,?,?,0,1,?,?,?,?,?,?,'',?,?,?,?,0,?)`,
|
VALUES (?,?,?,?,?,?,0,1,?,?,?,?,?,?,'',?,?,?,?,0,?)`,
|
||||||
// clicks route through our redirect so they count and carry the network site as the referrer
|
// 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,
|
assigned, assigned, now, kind.adtype,
|
||||||
opts.name || 'InstantAdPay member', opts.email || 'ads@instantadpay.com',
|
opts.name || 'InstantAdPay member', opts.email || 'ads@instantadpay.com',
|
||||||
'InstantAdPay campaign #' + c.id, edate,
|
'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)
|
// point an existing NAS ad at our click redirect (migration for rows pushed before 2026-09-10)
|
||||||
async function setClickUrl(nasAdId, campaignId) {
|
async function setClickUrl(nasAdId, campaignId) {
|
||||||
if (!enabled()) return { skipped: 'flag-off' };
|
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 };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
async function topUp(nasAdId, addImpressions, days) {
|
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: [] } }; } };
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
// Shared network knowledge, site side (Marty 2026-11-15: every network site's chatbot answers about the whole network, with its
|
||||||
|
// own site first). This site publishes its own knowledge-base entries to the network hub and reads the merged set back:
|
||||||
|
// PUT HUB_URL/v1/kb {name, url, entries} replaces this site's set (the hub skips a set it already holds)
|
||||||
|
// GET HUB_URL/v1/kb signed over an empty body, If-None-Match: the last version -> 304 when nothing changed
|
||||||
|
// Signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + "\n" + raw body)), like hubreport.js.
|
||||||
|
// The merged set is kept in memory and in DATA_DIR/netkb-cache.json (a MySQL document through docstore where the site has
|
||||||
|
// DOCSTORE_URL; written only when the version changes), so a hub outage at boot still answers about the other sites.
|
||||||
|
// Off when HUB_URL or a 32+ character HUB_SECRET is missing, or NETKB=0: the chatbot then answers about this site only.
|
||||||
|
//
|
||||||
|
// 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';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const REFRESH_MS = 10 * 60 * 1000;
|
||||||
|
let O = null; // { dataDir, site, name, url, netId, entries: async () => [...], linkFor: (url) => link }
|
||||||
|
let merged = { version: '', sites: {}, entries: [] }, loadedAt = 0, publishedHash = '', pubTimer = null, timer = null;
|
||||||
|
const stats = { published: 0, publishErrors: 0, reads: 0, notModified: 0, readErrors: 0, lastError: null, lastPublishAt: 0, lastReadAt: 0 };
|
||||||
|
|
||||||
|
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||||
|
const secret = () => String(process.env.HUB_SECRET || '').trim();
|
||||||
|
const siteName = () => String(process.env.HUB_SITE || (O && O.site) || '').trim();
|
||||||
|
const enabled = () => process.env.NETKB !== '0' && !!hubUrl() && secret().length >= 32 && !!siteName();
|
||||||
|
const cacheFile = () => (O && O.dataDir ? path.join(O.dataDir, 'netkb-cache.json') : null);
|
||||||
|
|
||||||
|
async function call(method, route, body, headers, 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(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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// the entries this site shares: what the chatbot's knowledge base holds, minus the instant-answer patterns (those stay home)
|
||||||
|
const shape = e => ({ id: String(e.id), title: e.title, questions: (e.questions || []).slice(0, 15), answer: e.answer, tags: (e.tags || []).slice(0, 15), link: e.link || (O && O.url) || undefined });
|
||||||
|
async function publish() {
|
||||||
|
if (!enabled() || !O || typeof O.entries !== 'function') return { skipped: true };
|
||||||
|
const entries = (await O.entries()).filter(e => e && e.id && e.answer && !e.deleted).map(shape);
|
||||||
|
const body = { name: O.name, url: O.url, entries };
|
||||||
|
const h = crypto.createHash('sha1').update(JSON.stringify(body)).digest('hex');
|
||||||
|
if (h === publishedHash) return { same: true };
|
||||||
|
try {
|
||||||
|
const r = await call('PUT', '/v1/kb', body);
|
||||||
|
if (r.status !== 200) { stats.publishErrors++; stats.lastError = 'publish ' + r.status + ' ' + ((r.body && r.body.error) || ''); return { error: stats.lastError }; }
|
||||||
|
publishedHash = h; stats.published++; stats.lastPublishAt = Date.now();
|
||||||
|
return r.body;
|
||||||
|
} catch (e) { stats.publishErrors++; stats.lastError = 'publish ' + e.message; return { error: e.message }; }
|
||||||
|
}
|
||||||
|
// an admin edit: publish a few seconds later (several quick edits go as one)
|
||||||
|
function publishSoon() { if (pubTimer) return; pubTimer = setTimeout(() => { pubTimer = null; publish().catch(() => {}); }, 5000); if (pubTimer.unref) pubTimer.unref(); }
|
||||||
|
|
||||||
|
function readCache() {
|
||||||
|
const f = cacheFile(); if (!f) return;
|
||||||
|
try { const d = JSON.parse(fs.readFileSync(f, 'utf8')); if (d && Array.isArray(d.entries)) { merged = d; loadedAt = 0; } } catch (e) {}
|
||||||
|
}
|
||||||
|
function writeCache() {
|
||||||
|
const f = cacheFile(); if (!f) return;
|
||||||
|
try { fs.writeFileSync(f + '.tmp', JSON.stringify(merged)); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('netkb cache', e.message); }
|
||||||
|
}
|
||||||
|
async function refresh() {
|
||||||
|
if (!enabled()) return { skipped: true };
|
||||||
|
try {
|
||||||
|
const r = await call('GET', '/v1/kb', undefined, merged.version ? { 'If-None-Match': '"' + merged.version + '"' } : {});
|
||||||
|
stats.lastReadAt = Date.now();
|
||||||
|
if (r.status === 304) { stats.notModified++; loadedAt = Date.now(); return { same: true }; }
|
||||||
|
if (r.status !== 200 || !r.body || !Array.isArray(r.body.entries)) { stats.readErrors++; stats.lastError = 'read ' + r.status; return { error: stats.lastError }; }
|
||||||
|
merged = { version: String(r.body.version || ''), sites: r.body.sites || {}, entries: r.body.entries }; loadedAt = Date.now(); stats.reads++;
|
||||||
|
writeCache();
|
||||||
|
return { version: merged.version, count: merged.entries.length };
|
||||||
|
} catch (e) { stats.readErrors++; stats.lastError = 'read ' + e.message; return { error: e.message }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// other sites' entries, ready for the chatbot's index: id "<site>:<id>", plus where they come from and the link to send people to
|
||||||
|
function remote() {
|
||||||
|
const me = siteName(); const out = [];
|
||||||
|
for (const e of merged.entries || []) {
|
||||||
|
if (!e || e.site === me) continue;
|
||||||
|
const s = (merged.sites || {})[e.site] || {};
|
||||||
|
const url = s.url || e.link || '';
|
||||||
|
out.push({ id: e.site + ':' + e.id, title: e.title, questions: e.questions || [], answer: e.answer, tags: e.tags || [],
|
||||||
|
site: e.site, siteName: s.name || e.site, siteUrl: url, go: (O && typeof O.linkFor === 'function' && url ? O.linkFor(url) : '') || url });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// the network's sites as the hub knows them (name, link), this one left out
|
||||||
|
function sites() {
|
||||||
|
const me = siteName();
|
||||||
|
return Object.entries(merged.sites || {}).filter(([k]) => k !== me).map(([k, s]) => ({ site: k, name: s.name || k, url: s.url || '', go: (O && typeof O.linkFor === 'function' && s.url ? O.linkFor(s.url) : '') || s.url || '', count: s.count || 0 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 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();
|
||||||
|
if (!enabled()) return;
|
||||||
|
const first = setTimeout(async () => { await publish().catch(() => {}); await refresh().catch(() => {}); }, Math.max(0, Number(process.env.NETKB_FIRST_MS) || 8000));
|
||||||
|
if (first.unref) first.unref();
|
||||||
|
timer = setInterval(async () => { await refresh().catch(() => {}); if (!publishedHash) await publish().catch(() => {}); }, Math.max(1000, Number(process.env.NETKB_REFRESH_MS) || REFRESH_MS));
|
||||||
|
if (timer.unref) timer.unref();
|
||||||
|
}
|
||||||
|
function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt, semantic: matchOn(), sem: SEM }, stats, mstats); }
|
||||||
|
function _set(m) { merged = m; } // tests
|
||||||
|
|
||||||
|
const version = () => merged.version || '';
|
||||||
|
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
|
// 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.
|
// 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.
|
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
|
||||||
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', viraladblitz: 'nwvab', 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 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 ''; } };
|
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||||
function selfId(req, l) {
|
function selfId(req, l) {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
//
|
//
|
||||||
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
|
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
|
||||||
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
|
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
|
||||||
// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P.
|
// sets the loop guard (nsso.tried, 2 minutes) and sends the browser to P.
|
||||||
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
|
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
|
||||||
// P mints a token bound to R, the state and the email, and sends the browser
|
// P mints a token bound to R, the state and the email, and sends the browser
|
||||||
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
|
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
|
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
|
||||||
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
|
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
|
||||||
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
|
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
|
||||||
// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
|
// stops a second bounce for 2 minutes (30 until 2026-11-15, when it blocked Marty's silent sign-in on LinkSpin), signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
|
||||||
// bots and non-page fetches never bounce.
|
// bots and non-page fetches never bounce.
|
||||||
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
|
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
|
||||||
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
|
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
|
||||||
@@ -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
|
// 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
|
// 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.
|
// 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';
|
'use strict';
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
@@ -34,16 +58,53 @@ const enabled = () => SECRET().length >= 32;
|
|||||||
const TTL = 60 * 1000; // token life
|
const TTL = 60 * 1000; // token life
|
||||||
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
||||||
const STATE_AGE = 300; // seconds: the state cookie
|
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 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 = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in
|
const BACK_AGE = 3600; // seconds: the provider remembers an unfinished deliberate check while the member signs in (20 minutes until 2026-11-17)
|
||||||
const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes
|
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 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 HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
||||||
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15)
|
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', fivex: '5xYourTeam' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15); fivex = 5xYourTeam (2026-11-15)
|
||||||
const WALLET_RE = /^0x[0-9a-f]{40}$/;
|
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,
|
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 b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||||
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
const 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) };
|
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),
|
// 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).
|
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
|
||||||
const used = new Map(); let fileLoaded = false, tableReady = null;
|
const 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 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; };
|
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)
|
// 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);
|
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) {
|
async function handle(req, res, u) {
|
||||||
if (!C || req.method !== 'GET') return false;
|
if (!C || req.method !== 'GET') return false;
|
||||||
const p = u.pathname;
|
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 peerName = NAMES[C.peer] || C.peer;
|
||||||
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
|
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))) {
|
if (goTo && (goTo === C.peer || walletBase(goTo))) {
|
||||||
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
|
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
|
||||||
const to = safePath(u.searchParams.get('to'), '/');
|
const to = safePath(u.searchParams.get('to'), '/');
|
||||||
@@ -156,28 +321,43 @@ async function handle(req, res, u) {
|
|||||||
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
|
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
|
||||||
const via = String(u.searchParams.get('via') || '');
|
const via = String(u.searchParams.get('via') || '');
|
||||||
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
|
const 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) {}
|
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
|
if (s && (s.email || s.address)) return go(res, to); // already signed in here
|
||||||
const c = cookies(req);
|
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');
|
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)];
|
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));
|
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);
|
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)
|
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 q = new URLSearchParams(cookies(req)['nsso.back'] || '');
|
||||||
const clear = [ck('nsso.back', '', 0, true)];
|
const clear = [ck('nsso.back', '', 0, true), ck('nsso.wait', '', 0, true)];
|
||||||
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
|
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) { // no deliberate tap waiting: a ?return=<site> link may be (2026-11-17)
|
||||||
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 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') {
|
if (p === '/sso/check') {
|
||||||
const st = String(u.searchParams.get('st') || '');
|
const st = String(u.searchParams.get('st') || '');
|
||||||
const to = safePath(u.searchParams.get('to'), '/');
|
const to = safePath(u.searchParams.get('to'), '/');
|
||||||
const r = String(u.searchParams.get('r') || '');
|
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)
|
||||||
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud;
|
if (r && r !== C.peer && !wb) { log('check: unknown site asking, nothing sent', null, r.slice(0, 20)); return go(res, C.defaultPath); } // never answer an unknown site as if the peer asked (2026-11-15: 5xYourTeam was sent to LinkSpin)
|
||||||
|
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = siteName(aud);
|
||||||
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
||||||
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
||||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
@@ -190,15 +370,30 @@ async function handle(req, res, u) {
|
|||||||
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
|
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
|
||||||
}
|
}
|
||||||
let w = null;
|
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);
|
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 }));
|
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') {
|
if (p === '/sso/in') {
|
||||||
const c = cookies(req);
|
const c = cookies(req);
|
||||||
const set = [ck('nsso.st', '', 0, true)];
|
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); }
|
if (u.searchParams.get('none')) {
|
||||||
const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
|
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 (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); }
|
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 }; }
|
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
|
||||||
@@ -210,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); }
|
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); }
|
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));
|
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)
|
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') {
|
if (p === '/api/sso/status') {
|
||||||
const c = cookies(req); const set = [];
|
const c = cookies(req); const set = [];
|
||||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
const signedIn = !!(s && (s.email || s.address));
|
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)); }
|
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
|
||||||
return sendJson(res, out, set);
|
return sendJson(res, out, set);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
|
// 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,
|
||||||
const pendingBack = req => !!cookies(req)['nsso.back'];
|
// 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
|
// 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 +
|
// cap (max uses) and expiry; codes can be switched off. Storage: MySQL promo_codes +
|
||||||
// promo_redemptions, or DATA_DIR/promos.json.
|
// 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 fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const db = require('./db');
|
const db = require('./db');
|
||||||
@@ -15,6 +17,7 @@ const norm = c => String(c || '').trim().toUpperCase().replace(/[^A-Z0-9_-]/g, '
|
|||||||
const STEPS = 5;
|
const STEPS = 5;
|
||||||
const WINDOW_DAYS = 30;
|
const WINDOW_DAYS = 30;
|
||||||
const stepOf = credits => Math.ceil(Number(credits) / STEPS);
|
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 = {
|
const J = {
|
||||||
db: { v: 1, codes: {}, redemptions: [] },
|
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 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 list() { return (await db.q('SELECT * FROM promo_codes ORDER BY created DESC')).map(row); },
|
||||||
async put(c) {
|
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)',
|
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.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);
|
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); },
|
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 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) })); }
|
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;
|
const impl = () => db.enabled() ? D : J;
|
||||||
|
|
||||||
function init(opts) { DATA_DIR = opts.dataDir; if (!db.enabled()) J.load(); }
|
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 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 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 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 };
|
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 }; }
|
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) {
|
async function check(code, email) {
|
||||||
const k = norm(code); if (!k) return { error: 'Enter a promo code.' };
|
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.' };
|
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 (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.' };
|
if (c.maxUses && (await impl().uses(k)) >= c.maxUses) return { error: 'That promo code has been fully redeemed.' };
|
||||||
return null;
|
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-->
|
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
<link rel="stylesheet" href="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="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>
|
<style>
|
||||||
.adm-table{width:100%;table-layout:auto}
|
.adm-table{width:100%;table-layout:auto}
|
||||||
.adm-table th{cursor:pointer;user-select:none;white-space:nowrap}
|
.adm-table th{cursor:pointer;user-select:none;white-space:nowrap}
|
||||||
@@ -652,8 +652,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||||
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
||||||
<script src="/assets/admin.js?v=20261112txt"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-kits.js?v=20261101th"></script>
|
<script src="/assets/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>
|
</body>
|
||||||
</html>
|
</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)
|
// 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 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>' : '');
|
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('') : '');
|
+ ((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>');
|
$('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) {}
|
} catch (e) {}
|
||||||
@@ -1146,7 +1152,7 @@
|
|||||||
loginDwellSeconds: ['Login ad: seconds shown', 'full-screen interstitial after sign-in'],
|
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'],
|
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'],
|
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'],
|
welcomeCredits: ['Welcome credits', 'granted after the welcome tour'],
|
||||||
dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'],
|
dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'],
|
||||||
dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'],
|
dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'],
|
||||||
@@ -1202,7 +1208,7 @@
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
// site settings: key / value rows; booleans as checkboxes, numbers stay numbers
|
// site settings: key / value rows; booleans as checkboxes, numbers stay numbers
|
||||||
const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Targets for milestones + daily snapshot: feed = main group, support = IAP support topic, echo = shared payments topic (comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramSupportChatId: 'Telegram support topic: chat id (milestones + daily snapshot)', telegramSupportTopicId: 'Telegram support topic: topic id', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)' };
|
const SITE_META = { loginAdEveryHours: 'Login ad: show again on the next member page once the last finished view is this many hours old (default 3)', noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Targets for milestones + daily snapshot: feed = main group, support = IAP support topic, echo = shared payments topic (comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramSupportChatId: 'Telegram support topic: chat id (milestones + daily snapshot)', telegramSupportTopicId: 'Telegram support topic: topic id', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)' };
|
||||||
function drawSite() {
|
function drawSite() {
|
||||||
const wrap = $('siteForm');
|
const wrap = $('siteForm');
|
||||||
wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '<div class="kv-row"><span class="k" title="' + esc(k) + '">' + esc(SITE_META[k] || humanize(k)) + '</span>'
|
wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '<div class="kv-row"><span class="k" title="' + esc(k) + '">' + esc(SITE_META[k] || humanize(k)) + '</span>'
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ window.IAP = (function () {
|
|||||||
+ '<div style="margin-top:8px;display:flex;gap:16px;justify-content:center;flex-wrap:wrap">'
|
+ '<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="/">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>'
|
+ '<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);
|
document.body.appendChild(f);
|
||||||
renderNetworkLine(f);
|
renderNetworkLine(f);
|
||||||
}
|
}
|
||||||
@@ -70,23 +70,46 @@ window.IAP = (function () {
|
|||||||
if (!netList) netList = fetch('/api/network-sites').then(r => r.json()).then(l => (Array.isArray(l) && l.length ? l : NET_FALLBACK)).catch(() => NET_FALLBACK);
|
if (!netList) netList = fetch('/api/network-sites').then(r => r.json()).then(l => (Array.isArray(l) && l.length ? l : NET_FALLBACK)).catch(() => NET_FALLBACK);
|
||||||
return netList;
|
return netList;
|
||||||
}
|
}
|
||||||
|
// the footer links carry a referral username (Marty 2026-11-15): the signed-in member's own, else the sponsor this visitor came in on
|
||||||
|
// (iap.sponsor cookie, usernames only, never a member number or wallet). Tracked links get it as s1 (LinkSpin sends it on as ?ref=),
|
||||||
|
// plain links as ?ref=. Earners Corner takes none.
|
||||||
|
const REF_RE = /^[A-Za-z0-9_.-]{1,40}$/;
|
||||||
|
const okRef = v => REF_RE.test(v) && !/^\d+$/.test(v) && !/^0x[0-9a-f]{40}$/i.test(v) && v !== 'company' && v !== 'top';
|
||||||
|
const refCookie = () => { const m = document.cookie.match(/(?:^|;\s*)iap\.sponsor=([^;]*)/); try { const v = m ? decodeURIComponent(m[1]) : ''; return okRef(v) ? v : ''; } catch (e) { return ''; } };
|
||||||
|
let netRef = null;
|
||||||
|
function networkRef() {
|
||||||
|
if (!netRef) netRef = fetch('/api/me', { credentials: 'same-origin' }).then(r => r.json()).then(m => (m && m.signedIn && m.username && okRef(m.username) ? m.username : refCookie())).catch(() => refCookie());
|
||||||
|
return netRef;
|
||||||
|
}
|
||||||
|
function withRef(s, ref) {
|
||||||
|
const href = s.go || s.url; if (!ref || s.id === 'earnerscorner') return href;
|
||||||
|
try { const u = new URL(href); u.searchParams.set(s.go ? 's1' : 'ref', ref); return u.toString(); } catch (e) { return href; }
|
||||||
|
}
|
||||||
function renderNetworkLine(host) {
|
function renderNetworkLine(host) {
|
||||||
if (!host || host.querySelector('.netline')) return;
|
if (!host || host.querySelector('.netline')) return;
|
||||||
const d = document.createElement('div'); d.className = 'netline';
|
const d = document.createElement('div'); d.className = 'netline';
|
||||||
d.style.cssText = 'margin-top:10px;display:flex;gap:6px 14px;justify-content:center;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
|
d.style.cssText = 'margin-top:10px;display:flex;gap:6px 14px;justify-content:center;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
|
||||||
host.appendChild(d);
|
host.appendChild(d);
|
||||||
const esc = s => String(s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[ch]);
|
const esc = s => String(s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[ch]);
|
||||||
const paint = list => {
|
let list = NET_FALLBACK, ref = refCookie();
|
||||||
|
const paint = () => {
|
||||||
d.innerHTML = '<b>Part of the network</b><span>One account across the network:</span>' + list.map(s => (s.id === 'iap' || /instantadpay\.com/.test(s.url))
|
d.innerHTML = '<b>Part of the network</b><span>One account across the network:</span>' + list.map(s => (s.id === 'iap' || /instantadpay\.com/.test(s.url))
|
||||||
? '<span aria-current="page" style="font-weight:700;color:var(--ink)">' + esc(s.name) + ' (you are here)</span>'
|
? '<span aria-current="page" style="font-weight:700;color:var(--ink)">' + esc(s.name) + ' (you are here)</span>'
|
||||||
: '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>').join('');
|
: '<a href="' + esc(withRef(s, ref)) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>').join('');
|
||||||
};
|
};
|
||||||
paint(NET_FALLBACK);
|
paint();
|
||||||
networkSites().then(paint);
|
networkSites().then(l => { list = l; paint(); });
|
||||||
|
networkRef().then(r => { if (r !== ref) { ref = r; paint(); } });
|
||||||
}
|
}
|
||||||
// pages with their own footer (the members area) get the network line too
|
// 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); }); }
|
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();
|
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() {
|
async function refreshNavWallet() {
|
||||||
try {
|
try {
|
||||||
const me = await (await fetch('/api/me')).json();
|
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: 'earned', label: 'Surf earnings', v: m => m.earned || 0 },
|
||||||
{ k: 'balance', label: 'Earned balance', v: m => m.balance || 0 },
|
{ k: 'balance', label: 'Earned balance', v: m => m.balance || 0 },
|
||||||
{ k: 'name', label: 'Name', v: m => String(m.name || '').toLowerCase(), str: true },
|
{ 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 = [
|
const LIST_FILTERS = [
|
||||||
{ k: 'today', label: 'Active today', t: m => activeToday(m) },
|
{ 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: 'nopay', label: 'Wallet, payouts off', t: m => !!m.wallet && !m.activated },
|
||||||
{ k: 'payouts', label: 'Payouts on', t: m => !!m.activated },
|
{ k: 'payouts', label: 'Payouts on', t: m => !!m.activated },
|
||||||
{ k: 'nowallet', label: 'No wallet', t: m => !m.wallet },
|
{ 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
|
// 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();
|
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) {
|
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 st = listState(key); const hide = (opts && opts.hide) || [];
|
||||||
const bar = document.createElement('div'); bar.className = 'lst-bar';
|
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">'
|
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>'
|
+ '<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>';
|
+ '<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
|
// 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 || '';
|
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 === 'profile') loadLineBanner();
|
||||||
if (name === 'line') { buildLineJump(); loadLineage(); loadUplineMessages(); loadCoach(); loadLinkStats(); loadProspects(); }
|
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') ['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 === 'training') { if (/(^|&)g=leader/.test(paneQ)) loadTraining.filter = 'Leader tools'; loadTraining(); }
|
||||||
if (name === 'pipeline') loadPipeline();
|
if (name === 'pipeline') loadPipeline();
|
||||||
if (name === 'promo') { const ps = /(^|&)s=([a-z]+)/.exec(paneQ || ''); if (ps) setPromoSub(ps[2]); }
|
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 === '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 === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13)
|
||||||
if (me.returnTo === 'nsso' && !render.toGame) { render.toGame = true; location.href = '/sso/resume'; return; } // tapped "Sign in with InstantAdPay" on another network site while signed out here (2026-11-14)
|
if (me.returnTo === '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 === '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 === '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)
|
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)
|
||||||
@@ -1009,15 +1014,17 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
render.welcomed = true;
|
render.welcomed = true;
|
||||||
history.replaceState(null, '', '/my' + (location.hash || ''));
|
history.replaceState(null, '', '/my' + (location.hash || ''));
|
||||||
(async () => {
|
(async () => {
|
||||||
try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {}
|
try { if (await showGauntlet()) showLoginAd.asked = true; else await showLoginAd(); } catch (e) {}
|
||||||
await render();
|
await render();
|
||||||
})();
|
})();
|
||||||
|
} else if (!showLoginAd.asked) { // login ad on the member's clock (Marty 2026-11-15): any page load, signed in just now or not; the server says when it is due
|
||||||
|
(async () => { try { await showLoginAd(); } catch (e) {} if (me.nssoBack && me.username) location.href = '/sso/resume'; })();
|
||||||
}
|
}
|
||||||
starterBanner(me).catch(() => {});
|
starterBanner(me).catch(() => {});
|
||||||
setPane(location.hash.slice(1) || 'overview');
|
setPane(location.hash.slice(1) || 'overview');
|
||||||
$('campGate').hidden = !!me.memberId;
|
$('campGate').hidden = !!me.memberId;
|
||||||
$('earnGate').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();
|
loadDashboard();
|
||||||
if (window.IAPSupport) IAPSupport.badge(); // Help badge: Marty replied to a ticket
|
if (window.IAPSupport) IAPSupport.badge(); // Help badge: Marty replied to a ticket
|
||||||
|
|
||||||
@@ -1341,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>' : '')
|
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>'
|
: (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>';
|
: '<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>'
|
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>'
|
+ '<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>'
|
+ 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>'
|
||||||
@@ -1540,6 +1547,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
$('cSizeRow').hidden = t !== 'banner';
|
$('cSizeRow').hidden = t !== 'banner';
|
||||||
$('cTitleRow').hidden = t !== 'text' && t !== 'solo';
|
$('cTitleRow').hidden = t !== 'text' && t !== 'solo';
|
||||||
$('cBodyRow').hidden = t !== 'text';
|
$('cBodyRow').hidden = t !== 'text';
|
||||||
|
if ($('cAiRow')) $('cAiRow').hidden = t !== 'text' || !aiWriterOn;
|
||||||
$('cSoloRow').hidden = t !== 'solo';
|
$('cSoloRow').hidden = t !== 'solo';
|
||||||
$('cSoloHint').hidden = t !== 'solo';
|
$('cSoloHint').hidden = t !== 'solo';
|
||||||
$('cVideoRow').hidden = t !== 'video';
|
$('cVideoRow').hidden = t !== 'video';
|
||||||
@@ -1560,6 +1568,28 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
if (t === 'featured') featHint();
|
if (t === 'featured') featHint();
|
||||||
}
|
}
|
||||||
$('cType').addEventListener('change', applyType);
|
$('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)
|
let featStartDay = 0; // selected start-day offset (0 = today)
|
||||||
async function featHint() {
|
async function featHint() {
|
||||||
if (!lastRates || !lastRates.featuredDurations) return;
|
if (!lastRates || !lastRates.featuredDurations) return;
|
||||||
@@ -1780,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;
|
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() {
|
function showVidOrient() {
|
||||||
const el = $('cVideoInfo'); if (!el) return;
|
const el = $('cVideoInfo'); if (!el) return;
|
||||||
if (!cVidDims) return;
|
if (!cVidDims) return;
|
||||||
@@ -1970,8 +2016,10 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
el.innerHTML = '';
|
el.innerHTML = '';
|
||||||
el.appendChild(listBar('tank', r.waiting.length, rows.length, () => renderTank(el, r), { hide: ['payouts'] })); // nobody in the tank has payouts on
|
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>' : '';
|
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>'
|
// readiness (2026-11-18, network hub): stage, heat, last action and how they got here under each lead; none when the hub is down
|
||||||
+ '<span class="em">joined ' + ago(w.joined) + '<span class="sp wrap">' + memberChips(w) + '</span></span>'
|
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>'
|
+ '<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('')
|
+ (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>');
|
: '<p class="muted small">Nobody in the tank matches your search or filters.</p>');
|
||||||
@@ -2973,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-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-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-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: [
|
{ 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-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' },
|
{ file: 'iap-five-dollar-friday-october-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · October porch, square' },
|
||||||
@@ -2981,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-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' } ] },
|
{ 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: [
|
{ 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: [
|
{ 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-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' },
|
{ file: 'iap-advertise-earn-1200x630.jpg', size: '1200×630 · advertise and earn instantly, locked in code' },
|
||||||
@@ -2998,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-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-1080x1080.jpg', size: '1080×1080 · Instagram, Facebook, Telegram' },
|
||||||
{ file: 'iap-five-dollar-friday-728x90.png', size: '728×90 · leaderboard' },
|
{ 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: [
|
{ title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [
|
||||||
{ file: 'iap-1080x1080.png', size: '1080×1080 · square' },
|
{ file: 'iap-1080x1080.png', size: '1080×1080 · square' },
|
||||||
{ file: 'iap-1080x1920.png', size: '1080×1920 · story / reel' } ] },
|
{ file: 'iap-1080x1920.png', size: '1080×1920 · story / reel' } ] },
|
||||||
@@ -3017,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-advertise-earn-v2-336x280.png', size: '336×280 · advertise and earn · variant 2' },
|
||||||
{ file: 'iap-300x250.png', size: '300×250 · rectangle' },
|
{ file: 'iap-300x250.png', size: '300×250 · rectangle' },
|
||||||
{ file: 'iap-advertise-earn-300x250.png', size: '300×250 · advertise and earn instantly' },
|
{ 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' } ] },
|
{ file: 'iap-125x125.png', size: '125×125 · square button' } ] },
|
||||||
{ title: 'Skyscrapers · 160×600, 120×600', items: [
|
{ title: 'Skyscrapers · 160×600, 120×600', items: [
|
||||||
{ file: 'iap-160x600.png', size: '160×600 · wide skyscraper' },
|
{ file: 'iap-160x600.png', size: '160×600 · wide skyscraper' },
|
||||||
@@ -3033,7 +3093,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
if (bridge) {
|
if (bridge) {
|
||||||
// the bridge page with this member's referral: any public page + ?ref sets the sponsor cookie
|
// the bridge page with this member's referral: any public page + ?ref sets the sponsor cookie
|
||||||
const inv = (document.getElementById('inviteLine') || {}).textContent || '';
|
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');
|
const note = document.createElement('div');
|
||||||
note.className = 'pb-note';
|
note.className = 'pb-note';
|
||||||
note.innerHTML = '<span>Post any of these with your ' + esc(bridge.name) + ' link: <b class="mono"></b></span>';
|
note.innerHTML = '<span>Post any of these with your ' + esc(bridge.name) + ' link: <b class="mono"></b></span>';
|
||||||
@@ -3044,7 +3106,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
grid.before(note);
|
grid.before(note);
|
||||||
}
|
}
|
||||||
for (const b of g.items) {
|
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');
|
const d = document.createElement('div');
|
||||||
d.className = 'pb-item';
|
d.className = 'pb-item';
|
||||||
d.innerHTML = '<img src="/banners/' + b.file + '?v=4" alt="InstantAdPay banner ' + b.size + '" loading="lazy">'
|
d.innerHTML = '<img src="/banners/' + b.file + '?v=4" alt="InstantAdPay banner ' + b.size + '" loading="lazy">'
|
||||||
@@ -3381,9 +3443,10 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
$('mcVerifyBtn').addEventListener('click', busy($('mcVerifyBtn'), async () => {
|
$('mcVerifyBtn').addEventListener('click', busy($('mcVerifyBtn'), async () => {
|
||||||
const r = await api('/api/auth/email/verify', { email: $('mcEmail').value, code: $('mcCode').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) });
|
const r = await api('/api/auth/email/verify', { email: $('mcEmail').value, code: $('mcCode').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) });
|
||||||
IAP.status('You are in.', 'ok');
|
IAP.status('You are in.', 'ok');
|
||||||
|
if (r.next === '/sso/resume' && !r.created) { try { await showLoginAd(); } catch (e) {} location.href = r.next; return; } // another network site asked: login ad if due, then straight back there (2026-11-15)
|
||||||
if (r.next && !r.created) { location.href = r.next; return; } // came from Drip Runner: straight back into the game
|
if (r.next && !r.created) { location.href = r.next; return; } // came from Drip Runner: straight back into the game
|
||||||
if (r.created && !(r.account && r.account.username)) await showOnboard(); // pick a username first
|
if (r.created && !(r.account && r.account.username)) await showOnboard(); // pick a username first
|
||||||
if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad
|
if (await showGauntlet()) showLoginAd.asked = true; else await showLoginAd(); // welcome tour outranks the login ad
|
||||||
await render();
|
await render();
|
||||||
}));
|
}));
|
||||||
})();
|
})();
|
||||||
@@ -3424,13 +3487,13 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
$('loginBtn').addEventListener('click', busy($('loginBtn'), async () => {
|
$('loginBtn').addEventListener('click', busy($('loginBtn'), async () => {
|
||||||
await api('/api/login', { email: $('liEmail').value, password: $('liPass').value });
|
await api('/api/login', { email: $('liEmail').value, password: $('liPass').value });
|
||||||
IAP.status('Logged in.', 'ok');
|
IAP.status('Logged in.', 'ok');
|
||||||
if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad
|
if (await showGauntlet()) showLoginAd.asked = true; else await showLoginAd(); // welcome tour outranks the login ad
|
||||||
await render();
|
await render();
|
||||||
}));
|
}));
|
||||||
$('linkBtn').addEventListener('click', busy($('linkBtn'), async () => {
|
$('linkBtn').addEventListener('click', busy($('linkBtn'), async () => {
|
||||||
IAP.status('Check your wallet for the free link signature…');
|
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
|
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');
|
IAP.status('Wallet linked. Earnings pay there from now on.', 'ok');
|
||||||
await render();
|
await render();
|
||||||
}));
|
}));
|
||||||
@@ -3474,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'); }
|
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'); }
|
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 => {
|
$('logoutLink').addEventListener('click', async e => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
await fetch('/api/auth/logout', { method: 'POST' });
|
await fetch('/api/auth/logout', { method: 'POST' });
|
||||||
@@ -3649,10 +3718,15 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
// out sit on the ad itself (Brian Holland, 2026-10-09: "no timer, no X").
|
// out sit on the ad itself (Brian Holland, 2026-10-09: "no timer, no X").
|
||||||
// Sites that refuse framing open in a new tab instead, with the bar saying
|
// Sites that refuse framing open in a new tab instead, with the bar saying
|
||||||
// so; the timer is not paused, the member is expected to be on the ad.
|
// so; the timer is not paused, the member is expected to be on the ad.
|
||||||
|
// 2026-11-15: shown on the member's clock (loginadclock.js, site setting loginAdEveryHours), asked once per page load; the end of
|
||||||
|
// the countdown tells the server (POST /api/ads/login/seen). back = a network sign-in hop waiting (another site asked): the
|
||||||
|
// finish button continues it, back to the site and page it came from, never the dashboard (Marty was stranded here from 5xYourTeam).
|
||||||
async function showLoginAd() {
|
async function showLoginAd() {
|
||||||
|
if (showLoginAd.asked) return; showLoginAd.asked = true;
|
||||||
try {
|
try {
|
||||||
const { ad } = await (await fetch('/api/ads/slot?type=login')).json();
|
const { ad, back } = await (await fetch('/api/ads/slot?type=login')).json();
|
||||||
if (!ad || !ad.targetUrl) return;
|
if (!ad || !ad.targetUrl) return;
|
||||||
|
$('lgContinue').textContent = back ? 'Continue' : 'Go to dashboard';
|
||||||
const gate = $('loginGate');
|
const gate = $('loginGate');
|
||||||
const openBtn = $('lgOpen');
|
const openBtn = $('lgOpen');
|
||||||
const goBtn = $('lgContinue');
|
const goBtn = $('lgContinue');
|
||||||
@@ -3675,6 +3749,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
if (frame) { frame.hidden = true; frame.src = 'about:blank'; }
|
if (frame) { frame.hidden = true; frame.src = 'about:blank'; }
|
||||||
if (body) body.hidden = false;
|
if (body) body.hidden = false;
|
||||||
openBtn.disabled = false;
|
openBtn.disabled = false;
|
||||||
|
const pop = document.querySelector('.iap-welcome'); if (pop) pop.style.display = 'none'; // the session pop-up waits until the login ad is done (welcome.js holds new ones back too)
|
||||||
gate.hidden = false;
|
gate.hidden = false;
|
||||||
await new Promise(done => {
|
await new Promise(done => {
|
||||||
openBtn.onclick = () => {
|
openBtn.onclick = () => {
|
||||||
@@ -3698,13 +3773,15 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
clearInterval(t);
|
clearInterval(t);
|
||||||
timer.textContent = 'Time is up';
|
timer.textContent = 'Time is up';
|
||||||
timer.classList.add('done');
|
timer.classList.add('done');
|
||||||
$('lgStatus').textContent = 'Thanks for the look. Your dashboard is ready.';
|
fetch('/api/ads/login/seen', { method: 'POST' }).catch(() => {});
|
||||||
|
$('lgStatus').textContent = back ? 'Thanks for the look. Continue to finish signing in where you came from.' : 'Thanks for the look. Your dashboard is ready.';
|
||||||
goBtn.hidden = false;
|
goBtn.hidden = false;
|
||||||
}, 1000);
|
}, 1000);
|
||||||
goBtn.onclick = () => done();
|
goBtn.onclick = () => { if (back) { goBtn.disabled = true; location.href = back; return; } done(); };
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
gate.hidden = true;
|
gate.hidden = true;
|
||||||
|
if (pop) pop.style.display = '';
|
||||||
if (frame) { frame.src = 'about:blank'; frame.hidden = true; }
|
if (frame) { frame.src = 'about:blank'; frame.hidden = true; }
|
||||||
if (body) body.hidden = false;
|
if (body) body.hidden = false;
|
||||||
$('lgTimer').classList.remove('done');
|
$('lgTimer').classList.remove('done');
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
// Promo tools > Network sites (Marty 2026-11-14): the promo kits of the other network sites, read live from each site's own public
|
// Promo tools > Network sites (Marty 2026-11-14): the promo kits of the other network sites, read live from each site's own public
|
||||||
// feed (GET <site>/api/promo-kit?u=<username>), so a creative or line changed on Downline Banners or Viral Banner Blitz shows here
|
// feed (GET <site>/api/promo-kit?u=<username>), so a creative or line changed on any of those sites shows here (ViralAdBlitz, DownlineHydra and 5xYourTeam added 2026-11-15, 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
|
// 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.
|
// visited them. Nothing is stored here.
|
||||||
window.IAPNetKits = (function () {
|
window.IAPNetKits = (function () {
|
||||||
const SITES = [
|
const SITES = [
|
||||||
{ key: 'dlb', name: 'Downline Banners', feed: 'https://downlinebanners.com/api/promo-kit', blurb: 'One global line of $5 banner spots on Polygon. A spot buys 300 guaranteed views on the board and a place in the line; every sale is split on-chain in the same transaction. Nothing is promised: a spot is paid only when spots sell after it.' },
|
{ key: 'dlb', name: 'Downline Banners', feed: 'https://downlinebanners.com/api/promo-kit', blurb: 'One global line of $5 banner spots on Polygon. A spot buys 300 guaranteed views on the board and a place in the line; every sale is split on-chain in the same transaction. Nothing is promised: a spot is paid only when spots sell after it.' },
|
||||||
{ key: 'vbb', name: 'Viral Banner Blitz', feed: 'https://viralbannerblitz.com/api/promo-kit', blurb: 'One shared loop of 125x125 banners. Network members post free once a day, real visitors push the loop, and a banner that rides out earns network ad views. Weekly leaderboards for visitors sent. Advertising, not income.' }
|
{ key: 'vbb', name: 'Viral Banner Blitz', feed: 'https://viralbannerblitz.com/api/promo-kit', blurb: 'One shared loop of 125x125 banners. Network members post free once a day, real visitors push the loop, and a banner that rides out earns network ad views. Weekly leaderboards for visitors sent. Advertising, not income.' },
|
||||||
|
{ key: 'vab', name: 'ViralAdBlitz', feed: 'https://viraladblitz.com/api/promo-kit', blurb: 'Your free text ad shows on your whole team\'s pages, five levels deep. A $5 Boost adds 500 views; every Boost is split on-chain in the same transaction. Nothing is promised.' },
|
||||||
|
{ key: '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]));
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
const $ = id => document.getElementById(id);
|
const $ = id => document.getElementById(id);
|
||||||
@@ -31,21 +37,21 @@ window.IAPNetKits = (function () {
|
|||||||
let h = '<p class="muted small" style="margin:0 0 12px">' + esc(site.blurb) + '</p>';
|
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
|
// 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 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('');
|
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>';
|
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>';
|
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 => {
|
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">'
|
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>'
|
+ 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>';
|
+ '</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>'
|
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>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>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(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>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.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>';
|
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;
|
return h;
|
||||||
|
|||||||
@@ -4,6 +4,14 @@
|
|||||||
var me = (document.currentScript && document.currentScript.getAttribute('data-site')) || 'iap';
|
var me = (document.currentScript && document.currentScript.getAttribute('data-site')) || 'iap';
|
||||||
var FALLBACK = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
|
var FALLBACK = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
|
||||||
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(function (a) { return { id: a[0], name: a[1], url: a[2] }; });
|
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(function (a) { return { id: a[0], name: a[1], url: a[2] }; });
|
||||||
|
// the links carry a referral username (Marty 2026-11-15): the signed-in member's own, else the sponsor this visitor came in on
|
||||||
|
// (iap.sponsor cookie, usernames only). Tracked links get it as s1 (LinkSpin sends it on as ?ref=), plain links as ?ref=; Earners Corner none.
|
||||||
|
function okRef(v) { return /^[A-Za-z0-9_.-]{1,40}$/.test(v) && !/^\d+$/.test(v) && !/^0x[0-9a-f]{40}$/i.test(v) && v !== 'company' && v !== 'top'; }
|
||||||
|
function refCookie() { var m = document.cookie.match(/(?:^|;\s*)iap\.sponsor=([^;]*)/); try { var v = m ? decodeURIComponent(m[1]) : ''; return okRef(v) ? v : ''; } catch (e) { return ''; } }
|
||||||
|
function withRef(s, ref) {
|
||||||
|
var href = s.go || s.url; if (!ref || s.id === 'earnerscorner') return href;
|
||||||
|
try { var u = new URL(href); u.searchParams.set(s.go ? 's1' : 'ref', ref); return u.toString(); } catch (e) { return href; }
|
||||||
|
}
|
||||||
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
||||||
function run() {
|
function run() {
|
||||||
var f = document.querySelector('footer'); if (!f || f.querySelector('.netline')) return;
|
var f = document.querySelector('footer'); if (!f || f.querySelector('.netline')) return;
|
||||||
@@ -12,13 +20,17 @@
|
|||||||
var box = document.createElement('div'); box.className = 'netline';
|
var box = document.createElement('div'); box.className = 'netline';
|
||||||
box.style.cssText = 'flex-basis:100%;width:100%;margin-top:10px;display:flex;gap:6px 14px;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
|
box.style.cssText = 'flex-basis:100%;width:100%;margin-top:10px;display:flex;gap:6px 14px;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
|
||||||
host.appendChild(box);
|
host.appendChild(box);
|
||||||
var paint = function (list) {
|
var list = FALLBACK, ref = refCookie();
|
||||||
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) {
|
var paint = function () {
|
||||||
return s.id === me ? '<span aria-current="page" style="font-weight:700">' + esc(s.name) + ' (you are here)</span>' : '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>';
|
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('');
|
}).join('');
|
||||||
};
|
};
|
||||||
paint(FALLBACK);
|
paint();
|
||||||
fetch('/api/network-sites').then(function (r) { return r.json(); }).then(function (l) { if (Array.isArray(l) && l.length) paint(l); }).catch(function () {});
|
fetch('/api/network-sites').then(function (r) { return r.json(); }).then(function (l) { if (Array.isArray(l) && l.length) { list = l; paint(); } }).catch(function () {});
|
||||||
|
fetch('/api/me', { credentials: 'same-origin' }).then(function (r) { return r.json(); }).then(function (m) { if (m && m.signedIn && m.username && okRef(m.username)) { ref = m.username; paint(); } }).catch(function () {});
|
||||||
}
|
}
|
||||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
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{display:grid;gap:6px}
|
||||||
.pipe-due .pipe-card{margin:0}
|
.pipe-due .pipe-card{margin:0}
|
||||||
@media (max-width:640px){.pipe-form{grid-template-columns:1fr !important}.pipe-col{flex-basis:200px}}
|
@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) */
|
/* 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}
|
.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}
|
.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"] .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"] .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)}
|
: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{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-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-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);
|
document.head.appendChild(st);
|
||||||
})();
|
})();
|
||||||
const catOptions = sel => CATS.map(c => '<option' + (c === sel ? ' selected' : '') + '>' + esc(c) + '</option>').join('');
|
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="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="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>'
|
+ '<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')
|
+ 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>';
|
+ '<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');
|
const atts = wireAttach('hn');
|
||||||
|
wireSuggest();
|
||||||
document.getElementById('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; });
|
document.getElementById('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; });
|
||||||
const send = document.getElementById('hnSend');
|
const send = document.getElementById('hnSend');
|
||||||
send.addEventListener('click', async () => {
|
send.addEventListener('click', async () => {
|
||||||
@@ -107,6 +110,27 @@ window.IAPSupport = (function () {
|
|||||||
});
|
});
|
||||||
document.getElementById('hnSubject').focus();
|
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) {
|
async function openMine(ref) {
|
||||||
const host = document.getElementById('helpBody'); if (!host) return;
|
const host = document.getElementById('helpBody'); if (!host) return;
|
||||||
helpState.open = ref;
|
helpState.open = ref;
|
||||||
@@ -148,6 +172,14 @@ window.IAPSupport = (function () {
|
|||||||
+ '<div id="supCheck" hidden style="margin-top:12px"></div>'
|
+ '<div id="supCheck" hidden style="margin-top:12px"></div>'
|
||||||
+ '<div class="sup-actions"><button class="btn" type="submit" id="supSend">Send to support</button><span class="small muted" id="supMsg"></span></div>'
|
+ '<div class="sup-actions"><button class="btn" type="submit" id="supSend">Send to support</button><span class="small muted" id="supMsg"></span></div>'
|
||||||
+ '</form></div>';
|
+ '</form></div>';
|
||||||
|
// hand-off from a network site's chat assistant (2026-11-15): ?from=<site id>&subject=<question> prefills the subject and names
|
||||||
|
// the site in the message, so the ticket says where it came from. Plain text only (value / textContent), never HTML.
|
||||||
|
try {
|
||||||
|
const qs = new URLSearchParams(location.search); const SITES = { viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', fivex: '5xYourTeam', vbb: 'Viral Banner Blitz', bannerline: 'Downline Banners', stackpol: 'Stack POL' };
|
||||||
|
const from = SITES[String(qs.get('from') || '').toLowerCase()]; const subj = String(qs.get('subject') || '').replace(/[\u0000-\u001f<>]/g, ' ').trim().slice(0, 140);
|
||||||
|
if (subj) document.getElementById('supSubject').value = subj;
|
||||||
|
if (from) document.getElementById('supBody').value = 'About ' + from + ': ';
|
||||||
|
} catch (e) {}
|
||||||
const f = document.getElementById('supForm');
|
const f = document.getElementById('supForm');
|
||||||
f.addEventListener('submit', async e => {
|
f.addEventListener('submit', async e => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -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,13 +26,15 @@
|
|||||||
|
|
||||||
function fridayLine(f) {
|
function fridayLine(f) {
|
||||||
if (!f || !f.on) return null;
|
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.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: '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.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;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function show(f) {
|
function show(f) {
|
||||||
if (document.querySelector('.iap-welcome')) return;
|
if (document.querySelector('.iap-welcome')) return;
|
||||||
|
// the login ad has the screen (2026-11-15: it now shows on any dashboard load): wait until it closes, never on top of it
|
||||||
|
var lg = document.getElementById('loginGate'); if (lg && !lg.hidden) { setTimeout(function () { show(f); }, 1000); return; }
|
||||||
var fri = fridayLine(f);
|
var fri = fridayLine(f);
|
||||||
|
|
||||||
var back = document.createElement('div');
|
var back = document.createElement('div');
|
||||||
|
|||||||
|
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>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/bixpay-guide.js?v=20261029bz"></script>
|
<script src="/assets/bixpay-guide.js?v=20261029bz"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</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>
|
<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>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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/contract.js?v=20260908p"></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></script>
|
<script src="/assets/chat.js?v=20261016n"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -265,8 +265,8 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
|
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
|
||||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</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>
|
<p class="muted small">You decide whether, and how much, to spend. Never spend more than you can afford to lose.</p>
|
||||||
</div>
|
</div>
|
||||||
</div></section>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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/legal.js?v=20260908a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -97,7 +97,7 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -127,7 +127,7 @@
|
|||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div></section>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/legal.js?v=20260908a"></script>
|
<script src="/assets/legal.js?v=20260908a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -72,7 +72,7 @@
|
|||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/friday.js?v=20260925a"></script>
|
<script src="/assets/friday.js?v=20260925a"></script>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -79,7 +79,7 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/games-page.js?v=20261012b"></script>
|
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/games-page.js?v=20261012b"></script>
|
||||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -506,7 +506,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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/wallet.js?v=20260909c"></script>
|
||||||
<script src="/assets/home.js?v=20261027tb"></script>
|
<script src="/assets/home.js?v=20261027tb"></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></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>
|
InstantAdPay · <a href="/contract">Contract</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a> · <a href="/disclaimer">Disclaimer</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||||
<script src="/assets/join.js?v=20261107nc"></script>
|
<script src="/assets/join.js?v=20261107nc"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -106,7 +106,7 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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>
|
<script src="/assets/launch.js?v=20260915b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</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>
|
<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>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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="/assets/ledger.js?v=20260906m"></script>
|
||||||
<script src="https://polhunter.com/embed.js" data-slots="1" async></script>
|
<script src="https://polhunter.com/embed.js" data-slots="1" async></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></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-->
|
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
<link rel="stylesheet" href="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="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>
|
</head>
|
||||||
<body class="bo-body">
|
<body class="bo-body">
|
||||||
|
|
||||||
@@ -168,6 +168,7 @@
|
|||||||
<div class="bo-foot">
|
<div class="bo-foot">
|
||||||
<span id="navWallet" class="small muted">…</span>
|
<span id="navWallet" class="small muted">…</span>
|
||||||
<a href="#" id="logoutLink" class="small">Log out</a>
|
<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>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
@@ -576,6 +577,7 @@
|
|||||||
<p id="cSizeRow" hidden><select id="cSize" style="width:100%"></select></p>
|
<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="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>
|
<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 id="cSoloRow" hidden>
|
||||||
<div class="ed-bar" aria-label="Formatting">
|
<div class="ed-bar" aria-label="Formatting">
|
||||||
<button type="button" data-cmd="bold" title="Bold"><b>B</b></button>
|
<button type="button" data-cmd="bold" title="Bold"><b>B</b></button>
|
||||||
@@ -1282,7 +1284,7 @@
|
|||||||
<a href="/disclaimer">Earnings Disclaimer</a>
|
<a href="/disclaimer">Earnings Disclaimer</a>
|
||||||
<a href="/privacy">Privacy</a>
|
<a href="/privacy">Privacy</a>
|
||||||
<a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</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>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1306,13 +1308,14 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
<script src="/assets/common.js?v=20261117nw"></script><script src="/assets/welcome.js?v=20261117nw"></script>
|
||||||
<script src="/assets/wallet.js?v=20260911a"></script>
|
<script src="/assets/wallet.js?v=20260911a"></script>
|
||||||
<script src="/assets/promo.js?v=20261103gp"></script>
|
<script src="/assets/promo.js?v=20261103gp"></script>
|
||||||
<script src="/assets/support.js?v=20261101th"></script>
|
<script src="/assets/support.js?v=20261116sg"></script>
|
||||||
<script src="/assets/netkits.js?v=20261114ns"></script>
|
<script src="/assets/netkits.js?v=20261123vai"></script>
|
||||||
<script src="/assets/my.js?v=20261114kes"></script>
|
<script src="/assets/tankready.js?v=20261118rd"></script>
|
||||||
<script src="/assets/fuel.js?v=20261113sso"></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/engine-room.js?v=20261113sso"></script>
|
||||||
<script src="/assets/netsso.js?v=20261113sso"></script>
|
<script src="/assets/netsso.js?v=20261113sso"></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></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>
|
<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>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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/partners.js?v=20260914a"></script>
|
||||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</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>
|
<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>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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>
|
<script src="/assets/plays.js?v=20260910b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</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>
|
<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>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></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>
|
</body>
|
||||||
</html>
|
</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>
|
<p class="muted small">We use reasonable safeguards, but no system is perfectly secure. Protect your email and your wallet.</p>
|
||||||
</div>
|
</div>
|
||||||
</div></section>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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/legal.js?v=20260908a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -261,6 +261,6 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -20,9 +20,9 @@
|
|||||||
<div id="supMain"><div class="card"><p class="muted small">Loading…</p></div></div>
|
<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>
|
<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>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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/legal.js?v=20260908a"></script>
|
||||||
<script src="/assets/support.js?v=20261101th"></script>
|
<script src="/assets/support.js?v=20261116sg"></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></script>
|
<script src="/assets/chat.js?v=20261016n"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</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>
|
<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>
|
||||||
</div></section>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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/legal.js?v=20260908a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -35,7 +35,7 @@
|
|||||||
<p><a href="/ledger">← Back to the live ledger</a> · <a href="/contract">Read the contract review</a></p>
|
<p><a href="/ledger">← Back to the live ledger</a> · <a href="/contract">Read the contract review</a></p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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>
|
<script src="/assets/tx.js?v=20260906m"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -48,7 +48,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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>
|
<script src="/assets/wall.js?v=20261030pp"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</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>
|
<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>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></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>
|
<script src="/assets/wallets.js?v=20260911b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -65,7 +65,7 @@
|
|||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/wednesday.js?v=20260929c"></script>
|
<script src="/assets/wednesday.js?v=20260929c"></script>
|
||||||
<script src="/assets/common.js?v=20261114ns"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="iap"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</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,77 @@
|
|||||||
|
// Member erase (erase.js) against a REAL, disposable MySQL: the SQL half (deletes, the chat message another member keeps,
|
||||||
|
// the help-desk ticket kept as scrubbed history, other members' mute lists, the residue sweep). Skipped without
|
||||||
|
// TEST_DATABASE_URL. Synthetic members only; NEVER point it at a live database (it creates and fills tables).
|
||||||
|
// TEST_DATABASE_URL=mysql://root:pw@127.0.0.1:3306/scratch node qa/erase.mysql.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs'); const os = require('os'); const path = require('path'); const assert = require('assert');
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
const URL_ = process.env.TEST_DATABASE_URL;
|
||||||
|
if (!URL_) { console.log('erase mysql: TEST_DATABASE_URL not set, skipped'); process.exit(0); }
|
||||||
|
process.env.DATABASE_URL = URL_; delete process.env.DOCSTORE_URL;
|
||||||
|
const db = require(path.join(ROOT, 'db.js')); const accounts = require(path.join(ROOT, 'accounts.js')); const erase = require(path.join(ROOT, 'erase.js'));
|
||||||
|
const E = 'gone9@example.test', O = 'other9@example.test';
|
||||||
|
(async () => {
|
||||||
|
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'erase-sql-'));
|
||||||
|
{ // db.js alters promo_codes and visit_seen before it creates them (fine on the live database, not on an empty one)
|
||||||
|
const c0 = await require('mysql2/promise').createConnection(URL_);
|
||||||
|
await c0.query(`CREATE TABLE IF NOT EXISTS promo_codes (code VARCHAR(24) NOT NULL PRIMARY KEY, credits INT NOT NULL, partner VARCHAR(80) NULL, note VARCHAR(200) NULL,
|
||||||
|
max_uses INT NOT NULL DEFAULT 0, expires BIGINT NOT NULL DEFAULT 0, active TINYINT NOT NULL DEFAULT 1, created BIGINT NOT NULL)`);
|
||||||
|
await c0.query('CREATE TABLE IF NOT EXISTS visit_seen (campaign_id INT NOT NULL, email VARCHAR(190) NOT NULL, day CHAR(10) NOT NULL, ts BIGINT NOT NULL, UNIQUE KEY uq_visit (campaign_id, email), INDEX (email, day))');
|
||||||
|
await c0.end();
|
||||||
|
}
|
||||||
|
await db.init({ dataDir: DIR }); accounts.init({ dataDir: DIR });
|
||||||
|
const q = db.q;
|
||||||
|
await q('CREATE TABLE IF NOT EXISTS account_signals (email VARCHAR(190) PRIMARY KEY, signup_ip VARCHAR(45) NULL)');
|
||||||
|
await q('CREATE TABLE IF NOT EXISTS ad_clicks (id VARCHAR(16) PRIMARY KEY, campaign_id INT NOT NULL, owner_email VARCHAR(190) NOT NULL, ts BIGINT NOT NULL)');
|
||||||
|
await q('CREATE TABLE IF NOT EXISTS event_marks (k VARCHAR(160) PRIMARY KEY, ts BIGINT NOT NULL)');
|
||||||
|
const now = Date.now();
|
||||||
|
await q("INSERT INTO accounts (email, sponsor_ref, code, created, username) VALUES (?, 'akuwhite', 'gonec01', ?, 'goneuser9'), (?, '', 'othc01', ?, 'other9')", [E, now, O, now]);
|
||||||
|
await q('UPDATE accounts SET chat_mutes=? WHERE email=?', [JSON.stringify([E, 'x@example.test']), O]);
|
||||||
|
await q("INSERT INTO sessions (token, email, member_id, expires) VALUES ('t1', ?, 0, ?)", [E, now + 1e6]);
|
||||||
|
const c = await q("INSERT INTO campaigns (owner_email, member_id, type, name, target_url, budget, status, created) VALUES (?, 0, 'visits', 'x', 'https://x.test', 60, 'out', ?)", [E, now]);
|
||||||
|
const cid = c.insertId;
|
||||||
|
await q("INSERT INTO camp_hours (campaign_id, day, hour, n) VALUES (?, '2026-11-01', 1, 3)", [cid]);
|
||||||
|
await q("INSERT INTO visit_seen (campaign_id, email, day, ts) VALUES (?, ?, '2026-11-01', 1)", [cid, O]); // another member's visit to THEIR ad
|
||||||
|
await q("INSERT INTO visit_seen (campaign_id, email, day, ts) VALUES (999, ?, '2026-11-01', 1)", [E]);
|
||||||
|
await q("INSERT INTO ad_clicks (id, campaign_id, owner_email, ts) VALUES ('c1', ?, ?, 1)", [cid, E]);
|
||||||
|
await q('INSERT INTO earned_credits (email, balance, updated) VALUES (?, 551, 1), (?, 10, 1)', [E, O]);
|
||||||
|
await q("INSERT INTO credit_log (email, ts, day, delta, kind, note) VALUES (?, 1, '2026-11-01', 5, 'x', 'n')", [E]);
|
||||||
|
await q("INSERT INTO account_signals (email, signup_ip) VALUES (?, '1.2.3.4')", [E]);
|
||||||
|
await q("INSERT INTO adoptions (adoptee, adopter, ts, expires) VALUES (?, ?, 1, 2)", [E, O]);
|
||||||
|
await q("INSERT INTO event_marks (k, ts) VALUES (?, 1), ('keep:other', 1)", ['tankpay1:' + E + ':17']);
|
||||||
|
await q("INSERT INTO sponsor_messages (from_member, from_email, to_email, subject, body, sent, kind) VALUES (0, ?, ?, '', 'their words', 1, 'chat'), (0, ?, ?, '', 'my words', 2, 'chat'), (1, 'admin@example.test', ?, 'Your ad', 'n', 3, 'notice'), (1, 'admin@example.test', ?, '@goneuser9 has not switched on payouts', '<p>@goneuser9 needs a nudge; goneuser99 is someone else</p>', 4, 'notice')", [E, O, O, E, E, O]);
|
||||||
|
const tk = await q("INSERT INTO tickets (ref, platform, email, name, username, subject, category, created, updated) VALUES ('LS-9001', 'linkspin', ?, 'Gone Person', 'goneuser9', 'delete me', 'account', 1, 1)", [E]);
|
||||||
|
await q("INSERT INTO ticket_messages (ticket_id, author, body, created) VALUES (?, 'member', 'please delete gone9@example.test', 1), (?, 'admin', 'Done.', 2)", [tk.insertId, tk.insertId]);
|
||||||
|
let fails = 0;
|
||||||
|
const t = async (name, fn) => { try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.stack.split('\n').slice(0, 3).join(' | ')); } };
|
||||||
|
erase.init({ dataDir: DIR, accounts, docstore: null, owners: {}, reload: {}, forget: [] });
|
||||||
|
await t('dry run counts every table and changes nothing', async () => {
|
||||||
|
const r = await erase.erase(E);
|
||||||
|
assert.strictEqual(r.sql.accounts, 1); assert.strictEqual(r.sql.campaigns, 1); assert.strictEqual(r.sql.camp_hours, 1); assert.strictEqual(r.sql.visit_seen, 2);
|
||||||
|
assert.strictEqual(r.sql.sponsor_messages, 2, 'sent by them + the notice to them'); assert.strictEqual(r.sql['sponsor_messages (kept, scrubbed)'], 1);
|
||||||
|
assert.strictEqual(r.sql['tickets (kept, scrubbed)'], 1); assert.strictEqual(r.sql['ticket_messages (kept, scrubbed)'], 1);
|
||||||
|
assert.strictEqual(r.sql['accounts.chat_mutes (others, scrubbed)'], 1);
|
||||||
|
assert.ok(r.residue.length > 0); assert.strictEqual((await q('SELECT COUNT(*) n FROM accounts WHERE email=?', [E]))[0].n, 1);
|
||||||
|
});
|
||||||
|
await t('erase: rows gone, the other member keeps their message (recipient tombstoned), the ticket stays scrubbed, residue empty', async () => {
|
||||||
|
const r = await erase.erase(E, { dryRun: false });
|
||||||
|
assert.strictEqual(r.ok, true); assert.deepStrictEqual(r.residue, [], JSON.stringify(r.residue));
|
||||||
|
const one = async (sql, a) => Number((await q(sql, a))[0].n);
|
||||||
|
assert.strictEqual(await one('SELECT COUNT(*) n FROM accounts WHERE email=?', [E]), 0); assert.strictEqual(await one('SELECT COUNT(*) n FROM accounts WHERE email=?', [O]), 1);
|
||||||
|
assert.strictEqual(await one('SELECT COUNT(*) n FROM campaigns WHERE id=?', [cid]), 0); assert.strictEqual(await one('SELECT COUNT(*) n FROM visit_seen WHERE campaign_id=?', [cid]), 0);
|
||||||
|
assert.strictEqual(await one('SELECT COUNT(*) n FROM earned_credits WHERE email=?', [O]), 1); assert.strictEqual(await one("SELECT COUNT(*) n FROM event_marks WHERE k='keep:other'"), 1);
|
||||||
|
const msgs = await q('SELECT from_email, to_email, subject, body FROM sponsor_messages ORDER BY sent');
|
||||||
|
assert.deepStrictEqual(msgs.map(m => [m.from_email, m.body]), [[O, 'my words'], ['admin@example.test', '<p>[erased member] needs a nudge; goneuser99 is someone else</p>']]); assert.ok(/^erased-[0-9a-f]{12}@erased\.invalid$/.test(msgs[0].to_email));
|
||||||
|
assert.strictEqual(msgs[1].subject, '[erased member] has not switched on payouts', 'a notice to someone else about them keeps its text, not their name'); assert.strictEqual(r.sql['sponsor_messages (others, name removed)'], 1);
|
||||||
|
const [tkt] = await q("SELECT email, name, username FROM tickets WHERE ref='LS-9001'"); assert.ok(/@erased\.invalid$/.test(tkt.email)); assert.strictEqual(tkt.name, null);
|
||||||
|
const tm = await q('SELECT author, body FROM ticket_messages ORDER BY id'); assert.ok(/removed/.test(tm[0].body)); assert.strictEqual(tm[1].body, 'Done.');
|
||||||
|
assert.deepStrictEqual(JSON.parse((await q('SELECT chat_mutes FROM accounts WHERE email=?', [O]))[0].chat_mutes), ['x@example.test']);
|
||||||
|
});
|
||||||
|
await t('a second pass with names cleans a username left in a kept message after the account is gone', async () => {
|
||||||
|
await q("INSERT INTO sponsor_messages (from_member, from_email, to_email, subject, body, sent, kind) VALUES (0, ?, ?, '', 'Hey goneuser9, welcome', 9, 'chat')", [O, 'x@example.test']);
|
||||||
|
const r = await erase.erase(E, { dryRun: false, names: ['goneuser9'] });
|
||||||
|
assert.strictEqual(r.found, false); assert.strictEqual(r.sql['sponsor_messages (others, name removed)'], 1); assert.deepStrictEqual(r.residue, []);
|
||||||
|
assert.strictEqual((await q('SELECT body FROM sponsor_messages WHERE sent=9'))[0].body, 'Hey [erased member], welcome');
|
||||||
|
});
|
||||||
|
console.log(fails ? fails + ' FAILED' : 'erase mysql: all passed'); process.exit(fails ? 1 : 0);
|
||||||
|
})().catch(e => { console.error(e); process.exit(1); });
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
// Member erase (erase.js + scrub.js, 2026-11-15, ticket LS-1021) in JSON mode on a throwaway DATA_DIR, synthetic members only:
|
||||||
|
// scrub rules, dry run changes nothing, a module's live copy is scrubbed and saved (not overwritten later), plain documents
|
||||||
|
// and JSON Lines through the fs layer, a reload hook, the tombstone, blockers + force, the hub's member.erased event through
|
||||||
|
// hubsync.receive, and scrub.js being the same file in the sibling LinkSpin / InstantAdPay checkout.
|
||||||
|
// node qa/erase.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs'); const os = require('os'); const path = require('path'); const crypto = require('crypto'); const assert = require('assert');
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
let fails = 0, n = 0;
|
||||||
|
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e && e.stack ? e.stack.split('\n').slice(0, 3).join(' | ') : e); } }
|
||||||
|
delete process.env.DATABASE_URL; delete process.env.DOCSTORE_URL;
|
||||||
|
const { scrubDeep, scrubText, mentions } = require(path.join(ROOT, 'scrub.js'));
|
||||||
|
const E = 'gone.person9@example.test', OTHER = 'stay@example.test';
|
||||||
|
const needles = { emails: [E], exact: ['goneuser', 'abc1234'] };
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await t('scrub: keys, list items, records and map values go; other people and look-alikes stay', () => {
|
||||||
|
const doc = { byEmail: { [E]: { u: 'goneuser' }, [OTHER]: { u: 'stay', sponsorEmail: 'x@example.test' } }, byCode: { abc1234: E, zzz9999: OTHER },
|
||||||
|
sends: [{ subject: 'Hi', recipients: [OTHER, E, 'xgone.person9@example.test'], delivered: [E] }],
|
||||||
|
log: [{ ts: 1, email: E, action: 'adopt' }, { ts: 2, email: OTHER }, { ts: 3, note: 'tankpay1:' + E + ':17' }],
|
||||||
|
clicks: { a1: { owner: E, n: 3 }, a2: { owner: OTHER, n: 1 } }, own: { 's:1': { [E]: 5, [OTHER]: 6 } }, nums: [1, 2, 3],
|
||||||
|
names: ['goneuserx', 'goneuser'], text: 'goneuser is a word here, kept',
|
||||||
|
prov: { [OTHER]: { sponsorEmail: E, at: 1 } }, team: [{ email: OTHER, sponsorEmail: E, ts: 4 }] };
|
||||||
|
const removed = scrubDeep(doc, needles);
|
||||||
|
assert.ok(removed >= 9, 'removed ' + removed);
|
||||||
|
assert.deepStrictEqual(Object.keys(doc.byEmail), [OTHER]); assert.deepStrictEqual(doc.byCode, { zzz9999: OTHER });
|
||||||
|
assert.deepStrictEqual(doc.sends[0].recipients, [OTHER, 'xgone.person9@example.test'], 'a longer address that contains it is someone else');
|
||||||
|
assert.deepStrictEqual(doc.sends[0].delivered, []); assert.deepStrictEqual(doc.log.map(x => x.ts), [2]);
|
||||||
|
assert.deepStrictEqual(Object.keys(doc.clicks), ['a2']); assert.deepStrictEqual(doc.own, { 's:1': { [OTHER]: 6 } });
|
||||||
|
assert.deepStrictEqual(doc.names, ['goneuserx'], 'a username only matches a whole string'); assert.strictEqual(doc.text, 'goneuser is a word here, kept');
|
||||||
|
assert.deepStrictEqual(doc.nums, [1, 2, 3]);
|
||||||
|
assert.deepStrictEqual(doc.prov, { [OTHER]: { sponsorEmail: null, at: 1 } }, "another member's record only loses the pointer");
|
||||||
|
assert.deepStrictEqual(doc.team, [{ email: OTHER, sponsorEmail: null, ts: 4 }]);
|
||||||
|
const lines = [JSON.stringify({ e: OTHER }), JSON.stringify({ e: E }), JSON.stringify({ u: 'goneuser' })].join('\n');
|
||||||
|
const r = scrubText(lines, needles, true); assert.strictEqual(r.removed, 2); assert.strictEqual(r.body, JSON.stringify({ e: OTHER }));
|
||||||
|
assert.strictEqual(mentions('{"a":"' + OTHER + '"}', needles), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- erase.js on a throwaway data dir ----
|
||||||
|
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'erase-iap-'));
|
||||||
|
const W = (f, o) => fs.writeFileSync(path.join(DIR, f), typeof o === 'string' ? o : JSON.stringify(o));
|
||||||
|
const Rd = f => JSON.parse(fs.readFileSync(path.join(DIR, f), 'utf8'));
|
||||||
|
W('updates-log.json', { sends: [{ subject: 'S', recipients: [OTHER, E], delivered: [E] }] });
|
||||||
|
W('legacy.json', { [E]: { b: 'faucetwave', s: 'e' }, [OTHER]: { b: 'tier1ads', s: 'a' } });
|
||||||
|
W('events.jsonl', JSON.stringify({ e: E }) + '\n' + JSON.stringify({ e: OTHER }));
|
||||||
|
W('unrelated.json', { a: OTHER });
|
||||||
|
// a module that keeps its document in memory and writes it back later (the reason erase works through the live copy)
|
||||||
|
let live = { rows: { [E]: { email: E, username: 'goneuser' }, [OTHER]: { email: OTHER } }, log: [{ email: E }] }; let saves = 0;
|
||||||
|
W('lsinbound.json', live);
|
||||||
|
const owner = { state: () => live, save: () => { saves++; W('lsinbound.json', live); } };
|
||||||
|
let reloads = 0;
|
||||||
|
const accts = { [E]: { email: E, username: 'goneuser', code: 'abc1234', address: null, memberId: 0 }, [OTHER]: { email: OTHER, username: 'stay', code: 'zzz9999', sponsorRef: '' },
|
||||||
|
'walleted@example.test': { email: 'walleted@example.test', username: 'wal', code: 'w1', address: '0x' + '1'.repeat(40), memberId: 0 } };
|
||||||
|
const accounts = { byEmail: async e => accts[e] || null, positions: async () => [], identities: async () => Object.values(accts),
|
||||||
|
listByReferrer: async refs => Object.values(accts).filter(a => refs.includes(a.sponsorRef)), removeAccount: async e => { if (!accts[e]) return { error: 'none' }; delete accts[e]; return { ok: true }; } };
|
||||||
|
const erase = require(path.join(ROOT, 'erase.js'));
|
||||||
|
let forgot = [];
|
||||||
|
erase.init({ dataDir: DIR, accounts, docstore: null, owners: { 'lsinbound.json': owner }, reload: { 'legacy.json': () => reloads++ }, forget: [e => forgot.push(e)] });
|
||||||
|
const before = fs.readFileSync(path.join(DIR, 'updates-log.json'), 'utf8');
|
||||||
|
|
||||||
|
await t('dry run (the default) counts and changes nothing', async () => {
|
||||||
|
const r = await erase.erase(E);
|
||||||
|
assert.strictEqual(r.dryRun, true); assert.strictEqual(r.found, true); assert.deepStrictEqual(r.blockers, []);
|
||||||
|
assert.deepStrictEqual(Object.keys(r.docs).sort(), ['events.jsonl', 'legacy.json', 'lsinbound.json', 'updates-log.json']);
|
||||||
|
assert.strictEqual(fs.readFileSync(path.join(DIR, 'updates-log.json'), 'utf8'), before); assert.ok(live.rows[E], 'live copy untouched');
|
||||||
|
assert.ok(accts[E]); assert.strictEqual(erase.isErased(E), false); assert.strictEqual(saves, 0);
|
||||||
|
});
|
||||||
|
await t('a linked wallet blocks it, force overrides', async () => {
|
||||||
|
const r = await erase.erase('walleted@example.test', { dryRun: false }); assert.ok(/main wallet/.test(r.error)); assert.ok(accts['walleted@example.test']);
|
||||||
|
const f = await erase.erase('walleted@example.test', { dryRun: false, force: true }); assert.strictEqual(f.forced, true); assert.ok(!accts['walleted@example.test']);
|
||||||
|
});
|
||||||
|
await t('erase: the account, the live copy (saved), plain docs, JSON Lines; reload hook; caches; tombstone; others intact', async () => {
|
||||||
|
const r = await erase.erase(E, { dryRun: false });
|
||||||
|
assert.strictEqual(r.ok, true); assert.ok(!accts[E]); assert.ok(accts[OTHER]);
|
||||||
|
assert.deepStrictEqual(Object.keys(live.rows), [OTHER]); assert.deepStrictEqual(live.log, []); assert.strictEqual(saves, 1);
|
||||||
|
assert.deepStrictEqual(Rd('lsinbound.json').rows[E], undefined);
|
||||||
|
assert.deepStrictEqual(Rd('updates-log.json').sends[0], { subject: 'S', recipients: [OTHER], delivered: [] });
|
||||||
|
assert.deepStrictEqual(Object.keys(Rd('legacy.json')), [OTHER]); assert.strictEqual(reloads, 1);
|
||||||
|
assert.strictEqual(fs.readFileSync(path.join(DIR, 'events.jsonl'), 'utf8'), JSON.stringify({ e: OTHER }));
|
||||||
|
assert.deepStrictEqual(r.docResidue, []); assert.deepStrictEqual(forgot.slice(-1), [E]);
|
||||||
|
assert.strictEqual(erase.isErased(E), true); assert.strictEqual(erase.isErased(OTHER), false);
|
||||||
|
const log = fs.readFileSync(path.join(DIR, 'erase.json'), 'utf8'); assert.ok(!log.includes(E), 'the erase log keeps no email'); assert.ok(log.includes(erase.hashOf(E).slice(0, 16)));
|
||||||
|
const again = await erase.erase(E, { dryRun: false }); assert.strictEqual(again.found, false); assert.deepStrictEqual(again.docs, {}, 'a second run finds nothing');
|
||||||
|
});
|
||||||
|
await t('hub member.erased: found by the email hash through hubsync.receive, answered 200', async () => {
|
||||||
|
accts['hubgone@example.test'] = { email: 'hubgone@example.test', username: 'hg', code: 'hg12345', address: null, memberId: 0 };
|
||||||
|
process.env.HUB_ENABLED = '1'; process.env.HUB_URL = 'http://127.0.0.1:9'; process.env.HUB_SECRET = 's'.repeat(40);
|
||||||
|
const hubsync = require(path.join(ROOT, 'hubsync.js'));
|
||||||
|
hubsync.init({ dataDir: DIR, accounts, lsinbound: { receive: async () => ({}) }, erase });
|
||||||
|
const raw = JSON.stringify({ events: [{ seq: 9001, at: Date.now(), type: 'member.erased', personId: 'h_' + '0'.repeat(16), data: { emailHash: erase.hashOf('HubGone@example.test') } }] });
|
||||||
|
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', 's'.repeat(40)).update(ts + '\n' + raw).digest('hex');
|
||||||
|
const r = await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': sig }, raw);
|
||||||
|
assert.strictEqual(r.status, 200); assert.ok(!accts['hubgone@example.test'], 'erased'); assert.strictEqual(erase.isErased('hubgone@example.test'), true);
|
||||||
|
const r2 = await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': sig }, raw); assert.strictEqual(r2.status, 200, 'delivered twice is fine');
|
||||||
|
});
|
||||||
|
await t('scrub.js is the same file in the sibling checkout (InstantAdPay <-> LinkSpin)', () => {
|
||||||
|
const sib = [path.join(ROOT, '..', '..', 'linkspin', 'site'), path.join(ROOT, '..', '..', 'onchain-ad-membership', 'site'), path.join(ROOT, '..', 'ls-erase'), path.join(ROOT, '..', 'iap-erase')]
|
||||||
|
.map(d => path.join(d, 'scrub.js')).find(f => fs.existsSync(f) && path.resolve(f) !== path.resolve(path.join(ROOT, 'scrub.js')));
|
||||||
|
if (!sib) { console.log(' (sibling scrub.js not found, skipped)'); return; }
|
||||||
|
const h = f => crypto.createHash('sha1').update(fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n')).digest('hex');
|
||||||
|
assert.strictEqual(h(path.join(ROOT, 'scrub.js')), h(sib), 'scrub.js differs from ' + sib);
|
||||||
|
});
|
||||||
|
console.log(fails ? fails + ' of ' + n + ' FAILED' : 'erase: all ' + n + ' passed');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -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,34 @@
|
|||||||
|
// The shared network knowledge base in this site's chatbot (2026-11-15): node qa/netkb-merge.test.cjs
|
||||||
|
// No network: netkb's merged set is set by hand. Checks: this site's entries rank first for a general question, a named site's
|
||||||
|
// entries rank first when it is named, other sites never take the fast path, the prompt labels them with the site and link,
|
||||||
|
// a question naming another site skips this site's instant answers (a hand-off still wins), and own() is this site only.
|
||||||
|
// The SAME file ships in InstantAdPay and LinkSpin.
|
||||||
|
const fs = require('fs'); const os = require('os'); const path = require('path');
|
||||||
|
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'netkb-'));
|
||||||
|
delete process.env.DATABASE_URL; delete process.env.OPENROUTER_API_KEY; process.env.NETKB = '0';
|
||||||
|
const kb = require('../kb'); const netkb = require('../netkb'); const bot = require('../chatbot');
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const ok = (c, m) => { if (c) { pass++; console.log('PASS', m); } else { fail++; console.log('FAIL', m); } };
|
||||||
|
(async () => {
|
||||||
|
await bot.init({ dataDir: DIR, chain: null });
|
||||||
|
const self = fs.existsSync(path.join(__dirname, '..', 'tickets.js')) ? 'iap' : 'linkspin';
|
||||||
|
netkb._set({ version: 'v1', sites: { downlinehydra: { name: 'DownlineHydra', url: 'https://downlinehydra.com' }, [self]: { name: 'Me', url: 'https://me.example' } },
|
||||||
|
entries: [
|
||||||
|
{ site: 'downlinehydra', id: 'c-pro', title: 'Pro: what it costs', questions: ['How much is Pro?', 'What do I get with Pro?'], answer: 'Pro is $30 one time.', tags: ['pro', 'price'] },
|
||||||
|
{ site: 'downlinehydra', id: 'c-withdraw', title: 'Withdrawals', questions: ['How do I withdraw?'], answer: 'Nothing to withdraw on DownlineHydra.', tags: ['withdraw'] },
|
||||||
|
{ site: self, id: 'c-own', title: 'Own entry from the hub', questions: ['x'], answer: 'never in remote', tags: [] }] });
|
||||||
|
await kb.load(true);
|
||||||
|
const top = async q => { const h = await kb.search(q, 8); return h[0] && h[0].entry; };
|
||||||
|
{ const t = await top('How do I withdraw?'); ok(t && !t.site, 'a general question ranks this site first (' + (t && t.id) + ')'); }
|
||||||
|
{ const t = await top('How do I withdraw on DownlineHydra?'); ok(t && t.site === 'downlinehydra', 'a named site ranks its own entry first (' + (t && t.id) + ')'); }
|
||||||
|
ok(!(await kb.search('Own entry from the hub', 8)).some(h => h.entry.site === self), 'this site\'s own copy on the hub is not read back as another site');
|
||||||
|
{ const b = kb.promptBlock(await kb.context('How much is Pro on DownlineHydra', 6)); ok(/about DownlineHydra, another network site; send people to /.test(b), 'remote entries labelled with site and link'); }
|
||||||
|
{ const r = await bot.answer('How much is Pro on DownlineHydra?'); ok(!r.canned, 'naming another site skips this site\'s instant answers (' + r.kb + ')'); }
|
||||||
|
{ const r = await bot.answer('How do I withdraw?'); ok(r.canned, 'this site\'s own question keeps its instant answer'); }
|
||||||
|
{ const r = await bot.answer('I need a real person, my DownlineHydra pro is missing'); ok(r.handoff === true, 'a hand-off still wins when another site is named'); }
|
||||||
|
{ const own = await kb.own(); ok(own.length > 10 && own.every(e => !e.site), 'own(): this site\'s entries only (' + own.length + ')'); }
|
||||||
|
ok(kb.namesOther('what is 5xYourTeam', self).includes('fivex') && !kb.namesOther('what is this site', self).length, 'namesOther finds a network site by name');
|
||||||
|
for (const e of await kb.own()) ok(!/\bmetamask\b/i.test(e.answer.replace(/never recommend MetaMask/gi, '')), e.id + ': no MetaMask recommendation in a shared answer');
|
||||||
|
console.log((fail ? 'FAILED ' : 'all network KB checks passed: ') + pass + ' passed, ' + fail + ' failed');
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
|
})().catch(e => { console.error(e); process.exit(1); });
|
||||||
@@ -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);
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
// Network sign-in from a partner wallet site (5xYourTeam pattern) through InstantAdPay, with the login ad on its clock (2026-11-15).
|
||||||
|
// Same file in InstantAdPay and LinkSpin. node qa/networksso-partner.e2e.mjs
|
||||||
|
// Marty was stranded: 5xYourTeam's "get a position" sent him to sign in through InstantAdPay; IAP answered r=fivex as if LinkSpin
|
||||||
|
// asked, and after a fresh sign-in the login ad's "Go to dashboard" left him on the IAP dashboard. This boots IAP and LinkSpin on
|
||||||
|
// throwaway DATA_DIRs plus a stand-in partner (the same networksso.js as a wallet receiver, self 'fivex', on 127.0.0.2: its own
|
||||||
|
// cookie host) and drives a real browser. Proves:
|
||||||
|
// A. signed in on IAP (wallet linked): partner /sso/start -> straight back to the partner page with a session, no IAP page, no ad
|
||||||
|
// B. signed out: partner -> IAP sign-in -> code -> the login ad -> its finish button says Continue -> back on the partner page,
|
||||||
|
// signed in; the countdown restarted the member's clock (the next ask answers notDue)
|
||||||
|
// C. the login-ad clock on a plain dashboard load: due -> the gate shows, after the countdown it does not show again on reload
|
||||||
|
// D. signed in on LinkSpin (wallet linked): partner via=linkspin -> straight back with a session
|
||||||
|
// No mail key, JSON stores, devCode. Skips when the other repo is not beside this one.
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import http from 'node:http';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
|
||||||
|
const peerGuess = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean);
|
||||||
|
const PEER = peerGuess.find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||||
|
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
|
||||||
|
if (!PEER) { console.log('SKIP partner sign-in e2e: the other repo was not found. Set NSSO_PEER_DIR.'); process.exit(0); }
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||||
|
const { ethers } = require(path.join(IAP_DIR, 'node_modules', 'ethers'));
|
||||||
|
const SECRET = crypto.randomBytes(24).toString('hex');
|
||||||
|
const IP = Number(process.env.NSSO_IAP_PORT || 8831), LP = IP + 1, PP = IP + 2;
|
||||||
|
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP, P = 'http://127.0.0.2:' + PP;
|
||||||
|
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||||
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
// an idle keep-alive socket the server closed (5 s default) while the browser launched: the request never reached it, send again
|
||||||
|
const fetch0 = globalThis.fetch;
|
||||||
|
const fetch = async (...a) => { for (let i = 0; ; i++) { try { return await fetch0(...a); } catch (e) { if (i >= 3 || !/ECONNRESET|UND_ERR_SOCKET/.test(String((e.cause && (e.cause.code || e.cause.message)) || ''))) throw e; await sleep(300); } } };
|
||||||
|
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-partner-'));
|
||||||
|
const logs = { iap: '', ls: '' };
|
||||||
|
function boot(name, dir, port, extra) {
|
||||||
|
const data = path.join(TMP, name); fs.mkdirSync(path.join(data, 'uploads'), { recursive: true });
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: data, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DEV_POL_USD: '0.10',
|
||||||
|
NETWORK_SSO_SECRET: SECRET, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', DOCSTORE_URL: '', LS_SYNC_SECRET: '', HUB_ENABLED: '', FIVEX_URL: P }, extra);
|
||||||
|
const p = spawn(process.execPath, ['server.js'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env });
|
||||||
|
p.stdout.on('data', d => logs[name] += d); p.stderr.on('data', d => logs[name] += d); return p;
|
||||||
|
}
|
||||||
|
const srvI = boot('iap', IAP_DIR, IP, { LS_URL: LS });
|
||||||
|
const srvL = boot('ls', LS_DIR, LP, { IAP_URL: IAP });
|
||||||
|
|
||||||
|
// the stand-in partner: a wallet receiver exactly like 5xYourTeam (self fivex, asks IAP or LinkSpin, sessions by wallet)
|
||||||
|
process.env.NETWORK_SSO_SECRET = SECRET;
|
||||||
|
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||||
|
const PS = new Map(); const sidOf = req => (/(?:^|;\s*)fx\.sid=([a-f0-9]{32})/.exec(req.headers.cookie || '') || [])[1];
|
||||||
|
N.init({ self: 'fivex', peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: path.join(TMP), defaultPath: '/team',
|
||||||
|
member: async req => { const s = PS.get(sidOf(req)); return s ? { address: s.address } : null; },
|
||||||
|
accept: async (e, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
||||||
|
signIn: async (e, req, v) => { const id = crypto.randomBytes(16).toString('hex'); PS.set(id, { address: v.wallet, via: v.iss }); return 'fx.sid=' + id + '; Path=/; HttpOnly; SameSite=Lax'; },
|
||||||
|
landing: to => to, signinPath: to => '/signin?to=' + encodeURIComponent(to) });
|
||||||
|
const partner = http.createServer(async (req, res) => {
|
||||||
|
const u = new URL(req.url, 'http://x');
|
||||||
|
if (await N.handle(req, res, u)) return;
|
||||||
|
if (u.pathname === '/api/whoami') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(PS.get(sidOf(req)) || {})); }
|
||||||
|
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>partner</title><p id="pg">' + u.pathname + '</p>');
|
||||||
|
});
|
||||||
|
await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); });
|
||||||
|
|
||||||
|
let ipN = 30;
|
||||||
|
const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.8.0.' + (ipN++), 'User-Agent': UA });
|
||||||
|
const sidFrom = r => ((r.headers.getSetCookie ? r.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid=')) || '').slice('iap.sid='.length);
|
||||||
|
async function codeSignIn(base, email) {
|
||||||
|
const h = H();
|
||||||
|
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
|
||||||
|
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
|
||||||
|
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
|
||||||
|
const sid = sidFrom(v); if (!sid) throw new Error('code sign-in failed on ' + base + ': ' + JSON.stringify(sj) + ' ' + v.status);
|
||||||
|
// members have a username (the dashboard asks for one before anything else)
|
||||||
|
const un = 'p' + email.split('@')[0].replace(/[^a-z0-9]/g, '').slice(0, 14) + crypto.randomBytes(2).toString('hex');
|
||||||
|
const pr = await fetch(base + '/api/my/profile', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: JSON.stringify({ username: un }) });
|
||||||
|
if (!pr.ok) throw new Error('username on ' + base + ': ' + pr.status + ' ' + (await pr.text()).slice(0, 120));
|
||||||
|
return sid;
|
||||||
|
}
|
||||||
|
// link a throwaway wallet to the signed-in account (the dashboard's Link wallet: challenge, personal_sign, verify)
|
||||||
|
async function linkWallet(base, sid) {
|
||||||
|
const w = ethers.Wallet.createRandom(); const h = Object.assign(H(), { Cookie: 'iap.sid=' + sid });
|
||||||
|
const ch = await (await fetch(base + '/api/auth/challenge', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address }) })).json();
|
||||||
|
const v = await fetch(base + '/api/auth/verify', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address, signature: await w.signMessage(ch.message) }) });
|
||||||
|
const j = await v.json(); if (j.error) throw new Error('wallet link on ' + base + ': ' + j.error);
|
||||||
|
return { address: w.address.toLowerCase(), sid: sidFrom(v) || sid };
|
||||||
|
}
|
||||||
|
const host = base => new URL(base).hostname;
|
||||||
|
let browser = null;
|
||||||
|
async function newCtx(sessions) {
|
||||||
|
const ctx = await browser.newContext({ userAgent: UA });
|
||||||
|
const add = Object.entries(sessions || {}).map(([base, sid]) => ({ name: 'iap.sid', value: sid, domain: host(base), path: '/' }));
|
||||||
|
if (add.length) await ctx.addCookies(add);
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
const whoami = async ctx => (await (await ctx.request.get(P + '/api/whoami')).json());
|
||||||
|
const mainNavs = page => { const n = []; page.on('framenavigated', f => { if (f === page.mainFrame()) n.push(f.url()); }); return n; };
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < 240; i++) { let a = false, b = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} if (a && b) break; if (i === 239) throw new Error('servers not up: iap ' + a + ', linkspin ' + b); await sleep(500); }
|
||||||
|
browser = await chromium.launch();
|
||||||
|
// a house login ad on IAP (the admin path), so the gate has something to show
|
||||||
|
const hc = await fetch(IAP + '/api/admin/campaigns', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer localtest' }, body: JSON.stringify({ type: 'login', name: 'QA login sponsor', targetUrl: 'https://example.com/' }) });
|
||||||
|
const hj = await hc.json().catch(() => ({}));
|
||||||
|
ok(hc.ok && !hj.error, 'setup: a house login ad on InstantAdPay', JSON.stringify(hj).slice(0, 160));
|
||||||
|
// 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';
|
||||||
|
const wa = await linkWallet(IAP, await codeSignIn(IAP, A));
|
||||||
|
let ctx = await newCtx({ [IAP]: wa.sid }); let page = await ctx.newPage(); let navs = mainNavs(page);
|
||||||
|
await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?pick=1#buy')); await page.waitForLoadState('domcontentloaded');
|
||||||
|
let who = await whoami(ctx);
|
||||||
|
ok(page.url() === P + '/team?pick=1#buy' && who.address === wa.address && who.via === 'iap', 'A. signed in on IAP: back on the partner page signed in as the linked wallet', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
ok(!navs.some(u => u.startsWith(IAP + '/my')), 'A. no IAP dashboard and no login ad on the way', navs.join(' , '));
|
||||||
|
ok(/token issued p\*\*\*@example\.com for 5xYourTeam/.test(logs.iap), 'A. IAP logged a token for 5xYourTeam (never "for LinkSpin")');
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// B. signed out on IAP: sign in there, the login ad shows, its Continue goes back to the partner page
|
||||||
|
const B = 'partner-b@example.com';
|
||||||
|
const wb = await linkWallet(IAP, await codeSignIn(IAP, B));
|
||||||
|
await fetch(IAP + '/api/auth/logout', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + wb.sid }), body: '{}' });
|
||||||
|
ctx = await newCtx(); page = await ctx.newPage(); navs = mainNavs(page);
|
||||||
|
await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?pick=2')); await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||||
|
ok(page.url().startsWith(IAP + '/my') && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), 'B. signed out: IAP asks for its sign-in and remembers the trip', page.url());
|
||||||
|
await page.fill('#mcEmail', B); await page.waitForTimeout(4600); await page.click('#mcSendBtn');
|
||||||
|
await page.waitForFunction(() => document.getElementById('mcCode') && document.getElementById('mcCode').value.length === 6, null, { timeout: 15000 });
|
||||||
|
await page.click('#mcVerifyBtn');
|
||||||
|
await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 });
|
||||||
|
ok(true, 'B. the login ad shows after the fresh sign-in');
|
||||||
|
await page.click('#lgOpen');
|
||||||
|
await page.waitForSelector('#lgContinue:not([hidden])', { timeout: 20000 });
|
||||||
|
ok((await page.textContent('#lgContinue')).trim() === 'Continue', 'B. its finish button continues the trip (not "Go to dashboard")', await page.textContent('#lgContinue'));
|
||||||
|
await page.click('#lgContinue');
|
||||||
|
await page.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 });
|
||||||
|
who = await whoami(ctx);
|
||||||
|
ok(page.url() === P + '/team?pick=2' && who.address === wb.address, 'B. back on the partner page it came from, signed in', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
const again = await (await ctx.request.get(IAP + '/api/ads/slot?type=login')).json();
|
||||||
|
ok(again.notDue === true && !again.ad, 'B. the countdown restarted the clock: the next ask on IAP is not due', JSON.stringify(again).slice(0, 120));
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// C. the clock on a plain dashboard load (no sign-in on this page): due -> the gate; after the countdown, a reload shows no gate
|
||||||
|
const C = 'partner-c@example.com';
|
||||||
|
const cI = await codeSignIn(IAP, C);
|
||||||
|
ctx = await newCtx({ [IAP]: cI }); page = await ctx.newPage();
|
||||||
|
await page.goto(IAP + '/my'); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 });
|
||||||
|
ok((await page.textContent('#lgContinue')).trim() === 'Go to dashboard', 'C. signed in earlier, first dashboard load: the login ad shows (due), finish says Go to dashboard');
|
||||||
|
const early = await (await ctx.request.post(IAP + '/api/ads/login/seen')).json();
|
||||||
|
ok(early.ok === false && early.reason === 'too soon', 'C. telling the server "seen" before the countdown is refused', JSON.stringify(early));
|
||||||
|
await page.click('#lgOpen', { timeout: 10000 }); await page.waitForSelector('#lgContinue:not([hidden])', { timeout: 20000 }); await page.waitForTimeout(800); await page.click('#lgContinue');
|
||||||
|
ok(await page.locator('#loginGate').isHidden(), 'C. Go to dashboard closes the gate');
|
||||||
|
await page.reload(); await page.waitForTimeout(3500);
|
||||||
|
ok(await page.locator('#loginGate').isHidden(), 'C. a reload inside the setting (3 hours) shows no login ad');
|
||||||
|
const d2 = await ctx.newPage(); await d2.goto(IAP + '/my'); await d2.waitForTimeout(3000);
|
||||||
|
ok(await d2.locator('#loginGate').isHidden(), 'C. nor does another tab');
|
||||||
|
await ctx.close();
|
||||||
|
// and a reload DURING the countdown does not skip it
|
||||||
|
const D0 = 'partner-d0@example.com'; const d0 = await codeSignIn(IAP, D0);
|
||||||
|
ctx = await newCtx({ [IAP]: d0 }); page = await ctx.newPage();
|
||||||
|
await page.goto(IAP + '/my'); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 }); await page.click('#lgOpen'); await page.waitForTimeout(2000);
|
||||||
|
await page.reload(); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 });
|
||||||
|
ok(true, 'C. a reload during the countdown brings the login ad back');
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// D. signed in on LinkSpin with a wallet: via=linkspin, straight back to the partner
|
||||||
|
const D = 'partner-d@example.com';
|
||||||
|
const wd = await linkWallet(LS, await codeSignIn(LS, D));
|
||||||
|
ctx = await newCtx({ [LS]: wd.sid }); page = await ctx.newPage(); navs = mainNavs(page);
|
||||||
|
await page.goto(P + '/sso/start?mode=go&via=linkspin&to=' + encodeURIComponent('/team')); await page.waitForLoadState('domcontentloaded');
|
||||||
|
who = await whoami(ctx);
|
||||||
|
ok(page.url() === P + '/team' && who.address === wd.address && who.via === 'linkspin', 'D. signed in on LinkSpin: back on the partner page signed in', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
ok(/token issued p\*\*\*@example\.com for 5xYourTeam/.test(logs.ls), 'D. LinkSpin logged a token for 5xYourTeam');
|
||||||
|
// 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 {
|
||||||
|
try { if (browser) await browser.close(); } catch (e) {}
|
||||||
|
try { srvI.kill(); } catch (e) {} try { srvL.kill(); } catch (e) {} try { partner.close(); } catch (e) {}
|
||||||
|
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
|
||||||
|
}
|
||||||
|
if (fails) { for (const k of ['iap', 'ls']) console.log('--- ' + k + ' log (tail)\n' + logs[k].split('\n').filter(l => !/rpc eth_call/.test(l)).slice(-30).join('\n')); }
|
||||||
|
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||||
@@ -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';
|
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++; };
|
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 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-'));
|
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
|
// 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');
|
const SPY = path.join(TMP, 'reqlog.cjs');
|
||||||
@@ -127,7 +130,7 @@ try {
|
|||||||
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads' && starts.length === 1, 'signed in nowhere: one bounce, back on the page signed out', starts.length + ' bounce(s), ' + page.url());
|
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads' && starts.length === 1, 'signed in nowhere: one bounce, back on the page signed out', starts.length + ' bounce(s), ' + page.url());
|
||||||
ok(await page.locator('#siEmail').isVisible(), 'the normal email-code sign-in shows');
|
ok(await page.locator('#siEmail').isVisible(), 'the normal email-code sign-in shows');
|
||||||
await page.reload(); await page.waitForTimeout(2500);
|
await page.reload(); await page.waitForTimeout(2500);
|
||||||
ok(starts.length === 1, 'reload inside 30 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)');
|
ok(starts.length === 1, 'reload inside 2 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)');
|
||||||
await page.goto(IAP + '/my'); await page.waitForTimeout(3000);
|
await page.goto(IAP + '/my'); await page.waitForTimeout(3000);
|
||||||
ok(!(await meOf(ctx, IAP)).signedIn && starts.length === 2 && (await page.locator('#mcEmail').count()) === 1, 'IAP /my signed in nowhere: one bounce, then the normal sign-in', starts.length + ' bounce(s), ' + page.url());
|
ok(!(await meOf(ctx, IAP)).signedIn && starts.length === 2 && (await page.locator('#mcEmail').count()) === 1, 'IAP /my signed in nowhere: one bounce, then the normal sign-in', starts.length + ' bounce(s), ' + page.url());
|
||||||
await ctx.close();
|
await ctx.close();
|
||||||
@@ -187,7 +190,7 @@ try {
|
|||||||
const old = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads', now: Date.now() - 120000 });
|
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);
|
await hop(LS + '/sso/in?t=' + old);
|
||||||
ok(!(await meOf(ctx, LS)).signedIn && /refused: expired/.test(logs.ls), 'an expired token is refused');
|
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);
|
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');
|
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
|
// open redirect: an off-site path never leaves the site
|
||||||
|
|||||||
@@ -78,14 +78,14 @@ const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/
|
|||||||
r = await call(R('/sso/start?to=/my', '', undefined, { 'sec-fetch-dest': 'empty' }));
|
r = await call(R('/sso/start?to=/my', '', undefined, { 'sec-fetch-dest': 'empty' }));
|
||||||
ok(r.loc === '/my' && !r.set.length, 'a fetch (not a page load) never bounces');
|
ok(r.loc === '/my' && !r.set.length, 'a fetch (not a page load) never bounces');
|
||||||
r = await call(R('/sso/start?to=/my', 'nsso.tried=1'));
|
r = await call(R('/sso/start?to=/my', 'nsso.tried=1'));
|
||||||
ok(r.loc === '/my', 'loop guard: a second silent check inside 30 minutes goes straight to the page');
|
ok(r.loc === '/my', 'loop guard: a second silent check inside 2 minutes goes straight to the page');
|
||||||
r = await call(R('/sso/start?to=/my', 'nsso.off=1'));
|
r = await call(R('/sso/start?to=/my', 'nsso.off=1'));
|
||||||
ok(r.loc === '/my', 'after a sign-out here: no silent check');
|
ok(r.loc === '/my', 'after a sign-out here: no silent check');
|
||||||
r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1'));
|
r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1'));
|
||||||
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy&m=go$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
|
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy&m=go$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
|
||||||
r = await call(R('/sso/start?to=https://evil.example'));
|
r = await call(R('/sso/start?to=https://evil.example'));
|
||||||
const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1];
|
const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1];
|
||||||
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=1800/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 30-minute guard, off-site path replaced', r.loc);
|
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=120/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 2-minute guard, off-site path replaced', r.loc);
|
||||||
r = await call(R('/sso/start?to=/my', 'sid=tok-a'));
|
r = await call(R('/sso/start?to=/my', 'sid=tok-a'));
|
||||||
ok(r.loc === '/my' && !r.set.length, 'already signed in here: no bounce');
|
ok(r.loc === '/my' && !r.set.length, 'already signed in here: no bounce');
|
||||||
r = await call(R('/sso/check?st=' + st + '&to=/ads'));
|
r = await call(R('/sso/check?st=' + st + '&to=/ads'));
|
||||||
@@ -95,6 +95,8 @@ const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/
|
|||||||
r = await call(R('/sso/check?st=' + st + '&to=/ads', 'sid=tok-a'));
|
r = await call(R('/sso/check?st=' + st + '&to=/ads', 'sid=tok-a'));
|
||||||
const issued = new URL(r.loc).searchParams.get('t');
|
const issued = new URL(r.loc).searchParams.get('t');
|
||||||
ok(r.loc.startsWith('https://ls.example/sso/in?t=v1.') && N.verify(issued, { iss: 'iap', aud: 'linkspin', st }).email === 'a@example.com', 'provider, signed in: a token for the other site only, bound to the state');
|
ok(r.loc.startsWith('https://ls.example/sso/in?t=v1.') && N.verify(issued, { iss: 'iap', aud: 'linkspin', st }).email === 'a@example.com', 'provider, signed in: a token for the other site only, bound to the state');
|
||||||
|
r = await call(R('/sso/check?st=' + st + '&r=fivex&to=/team', 'sid=tok-a'));
|
||||||
|
ok(r.loc === '/my' && !/sso\/in/.test(r.loc), 'provider: a site it does not know (r=fivex with no wallets entry) gets nothing, never a token for the peer (2026-11-15)', r.loc);
|
||||||
// receiver: a LinkSpin-issued token arriving here
|
// receiver: a LinkSpin-issued token arriving here
|
||||||
const mk = (email, to) => N.mint({ iss: 'linkspin', aud: 'iap', email, st, to });
|
const mk = (email, to) => N.mint({ iss: 'linkspin', aud: 'iap', email, st, to });
|
||||||
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my#buy'), 'nsso.st=' + st));
|
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my#buy'), 'nsso.st=' + st));
|
||||||
|
|||||||
@@ -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 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 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 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)
|
# 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
|
# 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
|
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
|
||||||
@@ -66,18 +67,32 @@ if [ "$MODE" = "public" ]; then
|
|||||||
elif [ "$MODE" = "sso" ]; then
|
elif [ "$MODE" = "sso" ]; then
|
||||||
node qa/networksso.test.cjs || status=1
|
node qa/networksso.test.cjs || status=1
|
||||||
node qa/networksso.e2e.mjs || 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
|
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.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.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-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/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/walletnudge.test.cjs || status=1
|
||||||
node qa/bixpay.test.cjs || status=1
|
node qa/bixpay.test.cjs || status=1
|
||||||
node qa/profile-policy.test.cjs || status=1
|
node qa/profile-policy.test.cjs || status=1
|
||||||
node qa/sov-heroes-store.cjs || status=1
|
node qa/sov-heroes-store.cjs || status=1
|
||||||
|
node qa/erase.test.cjs || status=1 # member erase (erase.js + scrub.js, 2026-11-15); qa/erase.mysql.test.cjs needs TEST_DATABASE_URL
|
||||||
|
node --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
|
elif [ "$MODE" = "draft" ]; then
|
||||||
node qa/draft-partner.test.mjs || status=1
|
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
|
elif [ "$MODE" = "theme" ]; then
|
||||||
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/theme-contrast.mjs || status=1; }; stop_local 8797
|
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/theme-contrast.mjs || status=1; }; stop_local 8797
|
||||||
elif [ "$MODE" = "policy" ]; then
|
elif [ "$MODE" = "policy" ]; then
|
||||||
@@ -90,12 +105,16 @@ elif [ "$MODE" = "walletnudge" ]; then
|
|||||||
node qa/walletnudge.test.cjs || status=1
|
node qa/walletnudge.test.cjs || status=1
|
||||||
elif [ "$MODE" = "tankhold" ]; then
|
elif [ "$MODE" = "tankhold" ]; then
|
||||||
node qa/tank-hold.mjs || status=1
|
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
|
elif [ "$MODE" = "sponsorfollow" ]; then
|
||||||
node qa/sponsorfollow.test.cjs || status=1
|
node qa/sponsorfollow.test.cjs || status=1
|
||||||
node qa/sponsorfollow-e2e.mjs || status=1
|
node qa/sponsorfollow-e2e.mjs || status=1
|
||||||
elif [ "$MODE" = "kb" ]; then
|
elif [ "$MODE" = "kb" ]; then
|
||||||
node qa/kb-retrieval.cjs || status=1
|
node qa/kb-retrieval.cjs || status=1
|
||||||
node qa/kb-chat.mjs || 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
|
elif [ "$MODE" = "door" ]; then
|
||||||
node qa/door.mjs || status=1
|
node qa/door.mjs || status=1
|
||||||
elif [ "$MODE" = "warpwares" ]; then
|
elif [ "$MODE" = "warpwares" ]; then
|
||||||
@@ -105,6 +124,7 @@ elif [ "$MODE" = "gamepass" ]; then
|
|||||||
elif [ "$MODE" = "sov-passes" ]; then
|
elif [ "$MODE" = "sov-passes" ]; then
|
||||||
node qa/sov-passes-store.cjs || status=1
|
node qa/sov-passes-store.cjs || status=1
|
||||||
node qa/sov-heroes-store.cjs || status=1
|
node qa/sov-heroes-store.cjs || status=1
|
||||||
|
node qa/erase.test.cjs || status=1 # member erase (erase.js + scrub.js, 2026-11-15); qa/erase.mysql.test.cjs needs TEST_DATABASE_URL
|
||||||
node qa/sov-passes-local.mjs || status=1
|
node qa/sov-passes-local.mjs || status=1
|
||||||
elif [ "$MODE" = "nas" ]; then
|
elif [ "$MODE" = "nas" ]; then
|
||||||
node qa/nas-served.mjs || status=1
|
node qa/nas-served.mjs || status=1
|
||||||
|
|||||||
@@ -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); });
|
||||||
@@ -305,4 +305,4 @@ function resetConversions(kinds) {
|
|||||||
return { cleared: n };
|
return { cleared: n };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, tick, stats, resetConversions, PACKS, compose };
|
module.exports = { init, tick, stats, resetConversions, PACKS, compose, _state: () => S, _save: save }; // _state/_save: the member erase (erase.js)
|
||||||
|
|||||||
@@ -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(() => []); }
|
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 ------------------------------------------------------------------------------------------
|
// ---- admin ------------------------------------------------------------------------------------------
|
||||||
async function stats() {
|
async function stats() {
|
||||||
const c = cfg(); const recs = await allRecs(); const rows = await outRows();
|
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 })) };
|
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 };
|
_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 += '<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 += 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 += '<p class="muted small" style="margin-top:30px">Suggestions and bug reports: the chat bubble on any page, or the InstantAdPay Telegram group.</p>';
|
||||||
h += '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
h += '</div><script src="/assets/common.js?v=20261117nw"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
module.exports = { init, notes, roadmap, saveNote, saveRoadmap, remove, publicView, renderPage, bodyHtml, TAGS, STATUSES };
|
module.exports = { init, notes, roadmap, saveNote, saveRoadmap, remove, publicView, renderPage, bodyHtml, TAGS, STATUSES };
|
||||||
|
|||||||